Golang實現(xiàn)http重定向https
更新時間:2022年07月13日 15:35:32 作者:taadis
這篇文章介紹了Golang實現(xiàn)http重定向https的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
用golang來實現(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()) } }
服務運行后,我們通常通過http://localhost
的形式來訪問,
而我們要實現(xiàn)的是通過https://localhost
的形式來訪問.
那么如何用golang來實現(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。
到此這篇關于Golang實現(xiàn)http重定向https的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
從并發(fā)到并行解析Go語言中的sync.WaitGroup
Go?語言提供了許多工具和機制來實現(xiàn)并發(fā)編程,其中之一就是?sync.WaitGroup。本文就來深入討論?sync.WaitGroup,探索其工作原理和在實際應用中的使用方法吧2023-05-05