使用 PKCS12 TLS 的 HTTPS 示例
本项目演示了如何使用 Fiber 框架在 Go 应用程序中设置带有 PKCS12 TLS 的 HTTPS 服务器。
先决条件
确保您已安装以下软件
- Golang
- Fiber 包
- PKCS12 证书文件 (
cert.p12
)
设置
-
克隆仓库
git clone https://github.com/gofiber/recipes.git
cd recipes/https-pkcs12-tls -
安装依赖
go get
-
将您的 PKCS12 证书文件 (
cert.p12
) 放入项目目录。
运行应用程序
-
启动应用程序
go run main.go
-
通过
https://localhost:3000
访问应用程序。
示例
这里是一个如何在 Fiber 应用程序中设置带有 PKCS12 TLS 的 HTTPS 服务器的示例
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"log"
"github.com/gofiber/fiber/v2"
"golang.org/x/crypto/pkcs12"
)
func main() {
// Load PKCS12 certificate
p12Data, err := ioutil.ReadFile("cert.p12")
if err != nil {
log.Fatal(err)
}
// Decode PKCS12 certificate
blocks, err := pkcs12.ToPEM(p12Data, "password")
if err != nil {
log.Fatal(err)
}
var pemData []byte
for _, b := range blocks {
pemData = append(pemData, pem.EncodeToMemory(b)...)
}
// Load certificate and key
cert, err := tls.X509KeyPair(pemData, pemData)
if err != nil {
log.Fatal(err)
}
// Create TLS configuration
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: x509.NewCertPool(),
}
// Fiber instance
app := fiber.New()
// Routes
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, HTTPS with PKCS12 TLS!")
})
// Start server with TLS
log.Fatal(app.ListenTLS(":3000", tlsConfig))
}