Golang實(shí)現(xiàn)http重定向https
用golang來實(shí)現(xiàn)的webserver通常是是這樣的
//main.go package main import ( "fmt" "io" "net/http" ) func defaultHandler(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "<h1>Golang HTTP</h1>") } func main() { mux := http.NewServeMux() mux.HandleFunc("/", defaultHandler) err := http.ListenAndServe(":80", mux) if err != nil { fmt.Println(err.Error()) } }
服務(wù)運(yùn)行后,我們通常通過http://localhost
的形式來訪問,
而我們要實(shí)現(xiàn)的是通過https://localhost
的形式來訪問.
那么如何用golang來實(shí)現(xiàn)HTTPS呢?
//main.go package main import ( "fmt" "io" "net/http" ) func defaultHandler(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "<h1>Golang HTTPS</h1>") } func main() { mux := http.NewServeMux() mux.HandleFunc("/", defaultHandler) certFile := "/etc/letsencrypt/live/www.taadis.com/cert.pem" keyFile := "/etc/letsencrypt/live/www.taadis.com/privkey.pem" err := http.ListenAndServeTLS(":443", certFile, keyFile, mux) if err != nil { fmt.Println(err.Error()) } }
源碼比較簡單,主要是把http.ListenAndServe()
替換成ListenAndServeTLS()
。其次注意下端口號的區(qū)別,還有就是CA證書的問題,這里我采用了Let's Encrypt。
到此這篇關(guān)于Golang實(shí)現(xiàn)http重定向https的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Golang?中的json.Marshal問題總結(jié)(推薦)
這篇文章主要介紹了Golang中的json.Marshal問題總結(jié),本文通過一個例子給大家詳細(xì)講解,本次提出的問題中,我們不難注意到其中的time.Time是一個匿名(Anonymous)字段,而這個就是答案的由來,需要的朋友可以參考下2022-06-06從并發(fā)到并行解析Go語言中的sync.WaitGroup
Go?語言提供了許多工具和機(jī)制來實(shí)現(xiàn)并發(fā)編程,其中之一就是?sync.WaitGroup。本文就來深入討論?sync.WaitGroup,探索其工作原理和在實(shí)際應(yīng)用中的使用方法吧2023-05-05基于Go語言實(shí)現(xiàn)類似tree命令的小程序
tree?命令是一個小型的跨平臺命令行程序,用于遞歸地以樹狀格式列出或顯示目錄的內(nèi)容。本文將通過Go語言實(shí)現(xiàn)類似tree命令的小程序,需要的可以參考一下2022-10-10golang組件swagger生成接口文檔實(shí)踐示例
這篇文章主要為大家介紹了golang組件swagger生成接口文檔實(shí)踐示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-04-04