咔叽游戏

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 200|回复: 0

[Golang] 详解Golang实现http重定向https的方式

[复制链接]
  • TA的每日心情
    无聊
    2019-6-2 14:11
  • 签到天数: 4 天

    [LV.2]圆转纯熟

    发表于 2020-3-4 09:53:39 | 显示全部楼层 |阅读模式
    以前写代码时,都是直接将程序绑定到唯一端口提供http/https服务,在外层通过反向代理(nginx/caddy)来实现http和https的切换。随着上线后的服务越来越多,有一些服务无法直接通过反向代理来提供这种重定向,只能依靠代码自己实现。所以简要记录一下如何在代码中实现http到https的重定向。
    分析

    无论是反向代理还是代码自己实现,问题的本质都是判断请求是否是https请求。 如果是则直接处理,如果不是,则修改请求中的url地址,同时返回客户端一个重定向状态码(301/302/303/307)。但如果仔细分析的话,会衍生出另外的问题,返回哪个重定向码是合理的?
    这个问题展开讨论,估计要写满满一大页,可能还得不出结论。 因此这里就不纠结到底返回哪个了,我使用的是307.
    实现

    如何我们从问题出现的场景开始分析,基本可以得出一个结论: 在需要转换的场景中,都是用户习惯性的首先发出了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 mainimport (   "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,  })}
    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持咔叽网单www.2nzz.com。

    QQ|免责声明|小黑屋|手机版|Archiver|咔叽游戏

    GMT+8, 2024-3-29 18:20

    Powered by Discuz! X3.4

    © 2001-2023 Discuz! Team.

    快速回复 返回顶部 返回列表