`)
})
app.Get("/style.css", func(c *fiber.Ctx) error {
// 推送CSS文件
c.Request().ServerPush("/style.css", "style")
return c.SendString("body{color:#037ef3}")
})
app.ListenTLS(":3000", "cert.pem", "key.pem")
}
Beego提供完整的MVC架构与ORM,适合需要快速搭建后台管理系统的场景。其核心组件包括:bee命令行工具、orm包、config配置管理。
go install github.com/beego/bee/v2@latest
bee new myproject
cd myproject
bee run
package models
import (
"github.com/beego/beego/v2/client/orm"
)
type Article struct {
Id int `orm:"pk;auto"`
Title string `orm:"size(100)"`
Content string `orm:"type(text)"`
Tags []Tag `orm:"rel(m2m)"`
}
type Tag struct {
Id int `orm:"pk;auto"`
Name string `orm:"size(50)"`
}
func init() {
orm.RegisterModel(new(Article), new(Tag))
}
func GetArticlesWithTags() ([]*Article, error) {
o := orm.NewOrm()
var articles []*Article
_, err := o.QueryTable("article").RelatedSel("Tags").All(&articles)
return articles, err
}
// conf/app.conf
appname = myproject
httpport = 8080
runmode = dev
autorender = false
copyrequestbody = true
# 数据库配置
db.driver = mysql
db.conn = root:password@tcp(127.0.0.1:3306)/mydb?charset=utf8mb4
// main.go
import (
"github.com/beego/beego/v2/server/web"
)
func main() {
web.BConfig.Listen.HTTPPort = 8080
web.BConfig.WebConfig.AutoReload = true // 开发模式自动重载
web.Run()
}
以下为完整API服务示例,整合Gin框架、JWT认证、MySQL数据库与健康检查端点:
api-service/
├── go.mod
├── go.sum
├── main.go
├── config/
│ └── config.go
├── models/
│ └── user.go
├── controllers/
│ └── auth.go
├── middlewares/
│ └── jwt.go
└── utils/
└── db.go
// config/config.go
package config
import "os"
type Config struct {
DBHost string
DBUser string
DBPass string
DBName string
JWTSecret string
ServerPort string
}
func LoadConfig() *Config {
return &Config{
DBHost: os.Getenv("DB_HOST"),
DBUser: os.Getenv("DB_USER"),
DBPass: os.Getenv("DB_PASS"),
DBName: os.Getenv("DB_NAME"),
JWTSecret: os.Getenv("JWT_SECRET"),
ServerPort: "8080",
}
}
// middlewares/jwt.go
package middlewares
import (
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) {
tokenString := c.GetHeader("Authorization")
if tokenString == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Missing token"})
return
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte("your-secret-key"), nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
return
}
c.Next()
}
}
// main.go
func main() {
r := gin.Default()
// 健康检查
r.GET("/health", func(c *gin.Context) {
if err := checkDB(); err != nil {
c.JSON(503, gin.H{"status": "unhealthy", "error": err.Error()})
return
}
c.JSON(200, gin.H{"status": "healthy"})
})
// 需认证的API
auth := r.Group("/api").Use(middlewares.JWTAuth())
{
auth.GET("/users", controllers.ListUsers)
}
r.Run(":8080")
}
根据TechEmpower基准测试(Round 21),Gin在纯文本响应场景下QPS达32,500,超过Express.js的18,200。但Node.js在I/O密集型场景(如代理服务)可能更优,需根据业务类型选型。
常见原因包括:未关闭的数据库连接、未释放的goroutine、全局变量积累。使用go tool pprof分析内存快照:go tool pprof -http=:8080 http://localhost:6060/debug/pprof/heap
Go生态有github.com/99designs/gqlgen支持GraphQL。当需要减少客户端请求次数、支持动态字段选择时,推荐GraphQL;若追求简单直接与广泛兼容性,RESTful更合适。