詳解Golang實(shí)現(xiàn)http重定向https的方式
以前寫代碼時(shí),都是直接將程序綁定到唯一端口提供http/https服務(wù),在外層通過(guò)反向代理(nginx/caddy)來(lái)實(shí)現(xiàn)http和https的切換。隨著上線后的服務(wù)越來(lái)越多,有一些服務(wù)無(wú)法直接通過(guò)反向代理來(lái)提供這種重定向,只能依靠代碼自己實(shí)現(xiàn)。所以簡(jiǎn)要記錄一下如何在代碼中實(shí)現(xiàn)http到https的重定向。
分析
無(wú)論是反向代理還是代碼自己實(shí)現(xiàn),問(wèn)題的本質(zhì)都是判斷請(qǐng)求是否是https請(qǐng)求。 如果是則直接處理,如果不是,則修改請(qǐng)求中的url地址,同時(shí)返回客戶端一個(gè)重定向狀態(tài)碼(301/302/303/307)。但如果仔細(xì)分析的話,會(huì)衍生出另外的問(wèn)題,返回哪個(gè)重定向碼是合理的?
這個(gè)問(wèn)題展開(kāi)討論,估計(jì)要寫滿滿一大頁(yè),可能還得不出結(jié)論。 因此這里就不糾結(jié)到底返回哪個(gè)了,我使用的是307.
實(shí)現(xiàn)
如何我們從問(wèn)題出現(xiàn)的場(chǎng)景開(kāi)始分析,基本可以得出一個(gè)結(jié)論: 在需要轉(zhuǎn)換的場(chǎng)景中,都是用戶習(xí)慣性的首先發(fā)出了http請(qǐng)求,然后服務(wù)器才需要返回一個(gè)https的重定向。 因此實(shí)現(xiàn)的第一步就是創(chuàng)建一個(gè)監(jiān)聽(tīng)http請(qǐng)求的端口:
go http.ListenAndServe(":8000", http.HandlerFunc(redirect))
8000端口專門用來(lái)監(jiān)聽(tīng)http請(qǐng)求,不能阻塞https主流程,因此單獨(dú)扔給一個(gè)協(xié)程來(lái)處理。 redirect用來(lái)實(shí)現(xiàn)重定向:
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監(jiān)聽(tīng)的端口。 如果監(jiān)聽(tīng)默認(rèn)端口443,那么就可加可不加。 最后調(diào)用sdk中的Redirect函數(shù)封裝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,
})
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Go語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單網(wǎng)絡(luò)聊天室(命令行模式)
這篇文章主要為大家詳細(xì)介紹了如何基于Go語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單網(wǎng)絡(luò)聊天室,文中的示例代碼簡(jiǎn)潔易懂,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-02-02
go微服務(wù)PolarisMesh源碼解析服務(wù)端啟動(dòng)流程
這篇文章主要為大家介紹了go微服務(wù)PolarisMesh源碼解析服務(wù)端啟動(dòng)流程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Go 請(qǐng)求兔子識(shí)別接口實(shí)現(xiàn)流程示例詳解
這篇文章主要為大家介紹了Go 請(qǐng)求兔子識(shí)別接口實(shí)現(xiàn)流程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
Golang語(yǔ)言實(shí)現(xiàn)gRPC的具體使用
本文主要介紹了Golang語(yǔ)言實(shí)現(xiàn)gRPC的具體使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

