新闻动态

Golang实现http重定向https

发布日期:2022-07-15 19:13 | 文章来源:CSDN

用golang来实现的webserver通常是是这样的

//main.go
package main
import (
	"fmt"
	"io"
	"net/http"
)
func defaultHandler(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "<h1>Golang HTTP</h1>")
}
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", defaultHandler)
	err := http.ListenAndServe(":80", mux)
	if err != nil {
		fmt.Println(err.Error())
	}
}

服务运行后,我们通常通过http://localhost的形式来访问,
而我们要实现的是通过https://localhost的形式来访问.

那么如何用golang来实现HTTPS呢?

//main.go
package main
import (
	"fmt"
	"io"
	"net/http"
)
func defaultHandler(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "<h1>Golang HTTPS</h1>")
}
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", defaultHandler)
	certFile := "/etc/letsencrypt/live/www.taadis.com/cert.pem"
	keyFile := "/etc/letsencrypt/live/www.taadis.com/privkey.pem"
	err := http.ListenAndServeTLS(":443", certFile, keyFile, mux)
	if err != nil {
		fmt.Println(err.Error())
	}
}

源码比较简单,主要是把http.ListenAndServe()替换成ListenAndServeTLS()。其次注意下端口号的区别,还有就是CA证书的问题,这里我采用了Let's Encrypt。

到此这篇关于Golang实现http重定向https的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持本站。

国外服务器租用

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

相关文章

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部