这期内容当中小编将会给大家带来有关使用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了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。