Golang实现http重定向https
作者:taadis 时间:2024-04-26 17:27:57
用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。
来源:https://www.cnblogs.com/taadis/p/12126228.html
标签:Golang,http,重定向,https
0
投稿
猜你喜欢
Perl的经典用法分享
2023-07-22 15:17:40
高性能WEB开发 JS、CSS的合并、压缩、缓存管理
2023-01-02 11:03:26
WorkBench管理操作MySQL
2010-10-14 14:21:00
Python Timer和TimerFPS计时工具类
2022-06-13 12:48:38
php删除路径下的所有文件夹和文件的代码
2023-05-27 18:44:35
一文弄懂MySQL中redo log与binlog的区别
2024-01-12 22:20:37
Python不使用int()函数把字符串转换为数字的方法
2022-04-22 02:32:33
再也不用花钱买漫画!Python爬取某漫画的脚本及源码
2021-03-19 17:44:43
anaconda中安装的python环境中没有pip3的问题及解决
2022-07-19 08:45:34
Pygame改编飞机大战制作兔子接月饼游戏
2023-04-09 02:57:22
Python模块的加载讲解
2023-04-05 08:42:01
WML初级教程之从实际应用中了解WML
2008-09-04 11:24:00
Python数据可视化编程通过Matplotlib创建散点图代码示例
2022-01-04 17:23:34
关于Flask项目无法使用公网IP访问的解决方式
2021-01-03 10:04:00
javascript对select标签的控制(option选项/select)
2024-04-19 10:15:54
数据库连接字符串的常见问题和解决方法
2008-11-28 15:16:00
深入浅析mybatis oracle BLOB类型字段保存与读取
2024-01-15 02:21:26
python怎么判断素数
2021-09-30 11:10:33
pytorch教程之网络的构建流程笔记
2021-11-24 10:58:59
Python yield 的使用浅析
2022-09-30 13:47:01