使用 TLS 的 HTTPS 示例
本项目演示了如何在使用 Fiber 框架的 Go 应用中设置使用 TLS 的 HTTPS 服务器。
先决条件
请确保已安装以下内容
- Golang
- Fiber 包
- TLS 证书(自签名或来自受信任的 CA)
设置
-
克隆仓库
git clone https://github.com/gofiber/recipes.git
cd recipes/https-tls -
安装依赖
go get
-
将您的 TLS 证书 (
cert.pem
) 和私钥 (key.pem
) 放在项目目录中。
运行应用
-
启动应用
go run main.go
-
在
https://localhost:3000
访问应用。
示例
这是一个如何在 Fiber 应用中设置使用 TLS 的 HTTPS 服务器的示例
package main
import (
"log"
"github.com/gofiber/fiber/v2"
)
func main() {
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, HTTPS with TLS!")
})
// Start server with TLS
log.Fatal(app.ListenTLS(":3000", "cert.pem", "key.pem"))
}