详解Golang实现http重定向https的方式
作者:andy zhang 时间:2024-05-09 09:47:02
以前写代码时,都是直接将程序绑定到唯一端口提供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,
})
}
来源:https://chinazt.cc/2018/08/20/golangshi-xian-httpzhong-ding-xiang-httpsde-fang-shi/
标签:Golang,http,重定向,https
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python tkinter实现计算器功能
2023-06-29 15:41:29
![](https://img.aspxhome.com/file/2023/9/60509_0s.jpg)
js判断变量是否未定义的代码
2023-08-16 03:43:27
Python实现爬取逐浪小说的方法
2022-05-26 22:31:29
Javascript学习第一季 二
2008-06-24 18:20:00
Python实现完整的事务操作示例
2023-11-15 21:02:02
解析SQLServer2005的Top功能
2024-01-27 05:37:16
简单实现js选项卡切换效果
2024-05-03 15:05:24
Python进阶之如何快速将变量插入有序数组
2021-07-26 16:52:51
BeautifulSoup获取指定class样式的div的实现
2023-05-10 20:39:14
Python tkinter之ComboBox(下拉框)的使用简介
2021-11-10 02:40:29
![](https://img.aspxhome.com/file/2023/3/127813_0s.png)
Python实现将Excel内容插入到Word模版中
2022-05-04 23:21:03
![](https://img.aspxhome.com/file/2023/3/130983_0s.png)
Python实现打砖块小游戏代码实例
2021-02-27 00:35:38
![](https://img.aspxhome.com/file/2023/3/82693_0s.gif)
asp生成不需要数据库的中奖码
2008-07-18 12:31:00
php中关于hook钩子函数底层理解
2023-06-12 06:49:55
python批量修改xml属性的实现方式
2022-10-03 12:34:58
![](https://img.aspxhome.com/file/2023/6/135046_0s.jpg)
SqlServer中tempdb的日志机制原理解析及示例分享
2024-01-15 20:31:38
![](https://img.aspxhome.com/file/2023/3/113593_0s.png)
对python中return与yield的区别详解
2022-10-19 00:47:33
python练习之循环控制语句 break 与 continue
2022-04-15 12:31:20
![](https://img.aspxhome.com/file/2023/1/86331_0s.png)
Python爬虫requests库多种用法实例
2021-01-10 13:31:56
Django模型验证器介绍与源码分析
2023-10-19 13:49:53
![](https://img.aspxhome.com/file/2023/5/76115_0s.png)