http服务启动、路由注册方法封装

This commit is contained in:
2025-11-25 13:52:20 +08:00
parent 7e8f10e557
commit 53243082fd

View File

@@ -3,6 +3,8 @@ package http
import (
"context"
"errors"
"fmt"
"gitee.com/red-future---jilin-g/common/jaeger"
"gitee.com/red-future---jilin-g/common/utils"
"github.com/gogf/gf/contrib/registry/consul/v2"
"github.com/gogf/gf/v2/frame/g"
@@ -13,6 +15,9 @@ import (
"github.com/gogf/gf/v2/os/glog"
"github.com/gogf/gf/v2/util/gconv"
"net/http"
"reflect"
"regexp"
"strings"
)
type ResponseEmpty struct {
@@ -26,6 +31,29 @@ type Page struct {
Total int //总页数
}
var HttpServer = g.Server()
func init() {
//s.Use(common.Cors) //中间件验证
//s.EnablePProf() //启用性能分析
HttpServer.SetOpenApiPath("/api.json")
HttpServer.SetSwaggerPath("/swagger") //api文档访问路径
HttpServer.SetDumpRouterMap(true) //关闭打印路由注册信息
HttpServer.BindMiddlewareDefault(ghttp.MiddlewareHandlerResponse, jaeger.NewTracer) //使用默认http返回结构
go HttpServer.Run()
}
func RouteRegister(controllers []interface{}) {
re := regexp.MustCompile("[A-Z]")
for _, t := range controllers {
sName := reflect.ValueOf(t).Elem().Type().Name()
convertedStr := re.ReplaceAllStringFunc(sName, func(s string) string {
return fmt.Sprintf("/%s", strings.ToLower(s))
})
HttpServer.Group(convertedStr, func(group *ghttp.RouterGroup) {
group.Bind(t)
})
}
}
func getHttpClient(ctx context.Context) (client *gclient.Client, err error) {
consulCfg, _ := g.Cfg().Get(context.Background(), "consul.address")
consulAddr := consulCfg.String()