Golang实现http重定向https
更新时间:2022-08-09 08:51:17 作者:佚名 我要评论(0)
用golang来实现的webserver通常是是这样的
//main.go
package main
import (
"fmt"
"io"
"net/http"
)
func defaultHandler(w http.Res
//main.go
package main
import (
"fmt"
"io"
"net/http"
)
func defaultHandler(w http.Res
用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的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- 使用Go添加HTTPS的实现代码示例
- 详解Golang实现http重定向https的方式
- 在 Django/Flask 开发服务器上使用 HTTPS
- Go语言HTTPServer开发的六种方式小结
- Django项目如何获得SSL证书与配置HTTPS
- golang的httpserver优雅重启方法详解
您可能感兴趣的文章:
相关文章
python使用pip成功导入库后还是报错的解决方法(针对vscode)
目录前言分析产生问题的原因重点解决第二个问题补充的问题——python代码有黄色的波浪线(定期补充)总结前言 写在开始前:其实出2022-08-09
最新评论