华域联盟 Golang 详解Golang实现http重定向https的方式

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

以前写代码时,都是直接将程序绑定到唯一端口提供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 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的方式

转载请保留出处和原文链接:https://www.cnhackhy.com/110414.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

Golang中time.After的使用理解与释放问题

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们