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())
}
}服務(wù)運行后,我們通常通過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。
到此這篇關(guān)于Golang實現(xiàn)http重定向https的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Golang?中的json.Marshal問題總結(jié)(推薦)
這篇文章主要介紹了Golang中的json.Marshal問題總結(jié),本文通過一個例子給大家詳細講解,本次提出的問題中,我們不難注意到其中的time.Time是一個匿名(Anonymous)字段,而這個就是答案的由來,需要的朋友可以參考下2022-06-06
從并發(fā)到并行解析Go語言中的sync.WaitGroup
Go?語言提供了許多工具和機制來實現(xiàn)并發(fā)編程,其中之一就是?sync.WaitGroup。本文就來深入討論?sync.WaitGroup,探索其工作原理和在實際應(yīng)用中的使用方法吧2023-05-05

