首页 > 其他分享 >mac下golang测试https

mac下golang测试https

时间:2022-12-08 17:34:41浏览次数:37  
标签:mydomain key crt ext golang mac err https com

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. 测试访问成功

 

标签:mydomain,key,crt,ext,golang,mac,err,https,com
From: https://www.cnblogs.com/zhengzhihua/p/16966288.html

相关文章