這期內容當中小編將會給大家帶來有關使用Golang怎么實現http重定向https,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
如何我們從問題出現的場景開始分析,基本可以得出一個結論: 在需要轉換的場景中,都是用戶習慣性的首先發出了http請求,然后服務器才需要返回一個https的重定向。 因此實現的第一步就是創建一個監聽http請求的端口:
go http.ListenAndServe(":8000", http.HandlerFunc(redirect))8000端口專門用來監聽http請求,不能阻塞https主流程,因此單獨扔給一個協程來處理。 redirect用來實現重定向:
func redirect(w http.ResponseWriter, req *http.Request) {
_host := strings.Split(req.Host, ":")
_host[1] = "8443"
target := "https://" + strings.Join(_host, ":") + req.URL.Path
if len(req.URL.RawQuery) > 0 {
target += "?" + req.URL.RawQuery
}
http.Redirect(w, req, target, http.StatusTemporaryRedirect)
}8443是https監聽的端口。 如果監聽默認端口443,那么就可加可不加。 最后調用sdk中的Redirect函數封裝Response。
處理完重定向之后,再處理https就變得很容易了:
router := mux.NewRouter()
router.Path("/").HandlerFunc(handleHttps)
c := cors.New(cors.Options{
AllowedOrigins: []string{"*.devexp.cn"},
AllowedMethods: []string{"HEAD", "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"*"},
AllowCredentials: true,
Debug: false,
AllowOriginFunc: func(origin string) bool {
return true
},
})
handler := c.Handler(router)
logrus.Fatal(http.ListenAndServeTLS(":8443", "cert.crt", "cert.key", handler))完整代碼如下:
package main
import (
"github.com/gorilla/mux"
"github.com/rs/cors"
"github.com/sirupsen/logrus"
"net/http"
"encoding/json"
"log"
"strings"
)
func main() {
go http.ListenAndServe(":8000", http.HandlerFunc(redirect))
router := mux.NewRouter()
router.Path("/").HandlerFunc(handleHttps)
c := cors.New(cors.Options{
AllowedOrigins: []string{"*.devexp.cn"},
AllowedMethods: []string{"HEAD", "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"*"},
AllowCredentials: true,
Debug: false,
AllowOriginFunc: func(origin string) bool {
return true
},
})
handler := c.Handler(router)
logrus.Fatal(http.ListenAndServeTLS(":8443", "cert.crt", "cert.key", handler))
}
func redirect(w http.ResponseWriter, req *http.Request) {
_host := strings.Split(req.Host, ":")
_host[1] = "8443"
// remove/add not default ports from req.Host
target := "https://" + strings.Join(_host, ":") + req.URL.Path
if len(req.URL.RawQuery) > 0 {
target += "?" + req.URL.RawQuery
}
log.Printf("redirect to: %s", target)
http.Redirect(w, req, target,
// see @andreiavrammsd comment: often 307 > 301
http.StatusTemporaryRedirect)
}
func handleHttps(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(struct {
Name string
Age int
Https bool
}{
"lala",
11,
true,
})
}上述就是小編為大家分享的使用Golang怎么實現http重定向https了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。