mac下golang测试https
1.自定义域名
sudo vi /etc/hosts 增加自定义域名 zhengzhihua.mac
保存退出
测试域名
2.生成证书脚本
创建文件build_crt.sh
#!/bin/bash set -x $(openssl genrsa -out rootCA.key 4096) $(openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.crt -subj "/C=GB/L=China/O=CN/CN=zhengzhihua.mac") $(openssl genrsa -out mydomain.com.key 2048) $(openssl req -new -sha256 -key mydomain.com.key -subj "/C=US/ST=CA/O=MyOrg, Inc./CN=$(ipconfig getifaddr en0)" -out mydomain.com.csr) echo "basicConstraints = CA:FALSE" >mydomain.com.ext echo "keyUsage = nonRepudiation, digitalSignature, keyEncipherment" >>mydomain.com.ext echo "subjectAltName=@alt_names" >>mydomain.com.ext echo "" >>mydomain.com.ext echo "[alt_names]" >>mydomain.com.ext echo "IP.1=$(ipconfig getifaddr en0)" >>mydomain.com.ext echo "DNS.1=zhengzhihua.mac" >>mydomain.com.ext $(openssl x509 -req -in mydomain.com.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -out mydomain.com.crt -days 500 -sha256 -extfile mydomain.com.ext)
zhengzhihua.mac自定义域名,然后执行 build_crt.sh
3.mac导入证书rootCA.crt
选择导入项目,选择刚刚脚本生成出的文件rootCA.crt
右键这个证书,点击显示简介
选择始终信任
之后变成这样
4.golang相关代码
1.创建目录https-test mkdir https-test
2.go mod init https_test
3.touch main.go
4.写入代码
package main import ( "log" "os" "path/filepath" "time" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() test := router.Group("/test") test.GET("/", func(context *gin.Context) { context.String(200, "访问成功 %s", time.Now().Format("当前时间:1月2日3点4分5秒")) }) crtPath, keyPath := getFilePath() // 开启端口监听 router.RunTLS(":1234", crtPath, keyPath) } func getFilePath() (crtPath, keyPath string) { pwd, err := os.Getwd() if err != nil { log.Fatal(err) } crtPath, err = filepath.Abs(pwd + "/mydomain.com.crt") //.crt文件路径 if err != nil { log.Fatal("mydomain.com.crt未找到:", err) } keyPath, err = filepath.Abs(pwd + "/mydomain.com.key") //.key文件路径 if err != nil { log.Fatal("server.key未找到:", err) } return }
5.go run main.go
6. 测试访问成功
分类:
golang相关学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!