人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動態(tài)

Golang實(shí)現(xiàn)http重定向https

發(fā)布日期:2022-07-15 19:13 | 文章來源:CSDN

用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í)有所幫助,也希望大家多多支持本站。

國外服務(wù)器租用

版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時開通

自選配置、實(shí)時開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對1客戶咨詢顧問

在線
客服

在線客服:7*24小時在線

客服
熱線

400-630-3752
7*24小時客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部