日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Golang實現http重定向https_Golang

作者:taadis ? 更新時間: 2022-09-06 編程語言

用golang來實現的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的形式來訪問,
而我們要實現的是通過https://localhost的形式來訪問.

那么如何用golang來實現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()。其次注意下端口號的區別,還有就是CA證書的問題,這里我采用了Let's Encrypt。

原文鏈接:https://www.cnblogs.com/taadis/p/12126228.html

欄目分類
最近更新