63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
package http
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"github.com/gogf/gf/v2/net/ghttp"
|
|
"github.com/gogf/gf/v2/os/gtime"
|
|
)
|
|
|
|
var Httpserver = g.Server()
|
|
|
|
func init() {
|
|
err := gtime.SetTimeZone("Asia/Shanghai")
|
|
if err != nil {
|
|
panic("设置时区失败")
|
|
}
|
|
Httpserver.SetOpenApiPath("/api.json")
|
|
Httpserver.BindMiddlewareDefault(ghttp.MiddlewareHandlerResponse)
|
|
// CORS - allow all origins
|
|
Httpserver.BindMiddlewareDefault(func(r *ghttp.Request) {
|
|
r.Response.CORS(r.Response.DefaultCORSOptions())
|
|
r.Middleware.Next()
|
|
})
|
|
}
|
|
|
|
// RouteRegister 根据控制器结构体名称自动注册路由
|
|
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))
|
|
})
|
|
if len(convertedStr) > 0 && convertedStr[0] == '/' {
|
|
convertedStr = convertedStr[1:]
|
|
}
|
|
Httpserver.Group("/"+convertedStr, func(group *ghttp.RouterGroup) {
|
|
group.Bind(t)
|
|
})
|
|
}
|
|
go Httpserver.Run()
|
|
}
|
|
|
|
// RouteRegisterRaw 注册原始路径路由(支持 :param 路径参数)
|
|
func RouteRegisterRaw(method, pattern string, handler ghttp.HandlerFunc) {
|
|
switch method {
|
|
case "GET":
|
|
Httpserver.BindHandler(pattern, handler)
|
|
case "POST":
|
|
Httpserver.BindHandler(pattern, handler)
|
|
case "PUT":
|
|
Httpserver.BindHandler(pattern, handler)
|
|
case "DELETE":
|
|
Httpserver.BindHandler(pattern, handler)
|
|
default:
|
|
Httpserver.BindHandler(pattern, handler)
|
|
}
|
|
}
|