standard/server/hertz/main.go
2026-03-28 19:31:44 +08:00

74 lines
1.5 KiB
Go

package hertz
import (
"compress/gzip"
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/middlewares/server/recovery"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"gitea.micah.com/micah/standard/conf"
"gitea.micah.com/micah/standard/initialize"
)
func Run() {
main()
}
func main() {
// init
initialize.Init()
address := conf.GetConf().Hertz.Address
h := server.New(server.WithHostPorts(address))
// add a ping route to test
h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"})
})
router.GeneratedRegister(h)
// do what you wanted
// add some render data: <no value>
registerMiddleware(h)
h.Spin()
}
func registerMiddleware(h *server.Hertz) {
// pprof
if conf.GetConf().Hertz.EnablePprof {
pprof.Register(h)
}
// gzip
if conf.GetConf().Hertz.EnableGzip {
h.Use(gzip.Gzip(gzip.DefaultCompression))
}
// access log
if conf.GetConf().Hertz.EnableAccessLog {
h.Use(accesslog.New())
}
// log
logger := hertzlogrus.NewLogger()
hlog.SetLogger(logger)
hlog.SetLevel(conf.LogLevel())
hlog.SetOutput(&lumberjack.Logger{
Filename: conf.GetConf().Hertz.LogFileName,
MaxSize: conf.GetConf().Hertz.LogMaxSize,
MaxBackups: conf.GetConf().Hertz.LogMaxBackups,
MaxAge: conf.GetConf().Hertz.LogMaxAge,
})
// recovery
h.Use(recovery.Recovery())
// cores
h.Use(cors.Default())
}