Keine Beschreibung
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

router_service.go 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. package router
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "git.x2erp.com/qdy/go-base/ctx"
  9. )
  10. // WebService 路由服务
  11. type RouterService struct {
  12. router *http.ServeMux
  13. middlewares []func(http.Handler) http.Handler
  14. }
  15. // NewWebService 创建WebService
  16. func NewWebService(router *http.ServeMux) *RouterService {
  17. ws := &RouterService{
  18. router: router,
  19. }
  20. return ws
  21. }
  22. // Use 添加全局中间件
  23. func (ws *RouterService) Use(middleware func(http.Handler) http.Handler) *RouterService {
  24. ws.middlewares = append(ws.middlewares, middleware)
  25. return ws
  26. }
  27. // GET 注册GET请求
  28. func (ws *RouterService) GET(path string, handler interface{}) *RouteBuilder {
  29. return ws.handle("GET", path, handler)
  30. }
  31. // POST 注册POST请求
  32. func (ws *RouterService) POST(path string, handler interface{}) *RouteBuilder {
  33. return ws.handle("POST", path, handler)
  34. }
  35. // PUT 注册PUT请求
  36. func (ws *RouterService) PUT(path string, handler interface{}) *RouteBuilder {
  37. return ws.handle("PUT", path, handler)
  38. }
  39. // DELETE 注册DELETE请求
  40. func (ws *RouterService) DELETE(path string, handler interface{}) *RouteBuilder {
  41. return ws.handle("DELETE", path, handler)
  42. }
  43. // handle 统一处理方法
  44. func (ws *RouterService) handle(method, path string, handler interface{}) *RouteBuilder {
  45. // 解析路径参数名
  46. paramNames := extractPathParams(path)
  47. // 获取处理器函数信息
  48. handlerValue := reflect.ValueOf(handler)
  49. handlerType := handlerValue.Type()
  50. // 验证处理器函数
  51. if handlerType.Kind() != reflect.Func {
  52. panic("handler must be a function")
  53. }
  54. // 验证返回值
  55. if handlerType.NumOut() != 2 {
  56. panic("handler must return exactly 2 values: (T, error)")
  57. }
  58. return &RouteBuilder{
  59. ws: ws,
  60. method: method,
  61. path: path,
  62. handlerFunc: handlerValue,
  63. paramNames: paramNames,
  64. }
  65. }
  66. // RouteBuilder 路由构建器
  67. type RouteBuilder struct {
  68. ws *RouterService
  69. method string
  70. path string
  71. handlerFunc reflect.Value
  72. paramNames []string
  73. middlewares []func(http.Handler) http.Handler
  74. description string
  75. }
  76. // Use 添加路由级中间件
  77. func (rb *RouteBuilder) Use(middleware ...func(http.Handler) http.Handler) *RouteBuilder {
  78. rb.middlewares = append(rb.middlewares, middleware...)
  79. return rb
  80. }
  81. // Desc 添加描述
  82. func (rb *RouteBuilder) Desc(description string) *RouteBuilder {
  83. rb.description = description
  84. return rb
  85. }
  86. // Register 注册路由
  87. func (rb *RouteBuilder) Register() {
  88. // 创建适配器
  89. adapter := &handlerAdapter{
  90. ws: rb.ws,
  91. method: rb.method,
  92. pathPattern: rb.path,
  93. paramNames: rb.paramNames,
  94. handlerFunc: rb.handlerFunc,
  95. }
  96. // 构建处理链:全局中间件 → 路由中间件 → 处理器
  97. var handler http.Handler = adapter
  98. // 1. 应用路由级中间件(从后往前)
  99. for i := len(rb.middlewares) - 1; i >= 0; i-- {
  100. handler = rb.middlewares[i](handler)
  101. }
  102. // 2. 应用全局中间件(从后往前)
  103. for i := len(rb.ws.middlewares) - 1; i >= 0; i-- {
  104. handler = rb.ws.middlewares[i](handler)
  105. }
  106. // 注册到路由器
  107. rb.ws.router.Handle(rb.path, handler)
  108. }
  109. // handlerAdapter 处理器适配器
  110. type handlerAdapter struct {
  111. ws *RouterService
  112. method string
  113. pathPattern string
  114. paramNames []string
  115. handlerFunc reflect.Value
  116. }
  117. func (ha *handlerAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  118. // 只处理指定方法的请求
  119. if r.Method != ha.method {
  120. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  121. return
  122. }
  123. // 1. 解析路径参数
  124. pathParams := ha.parsePathParams(r.URL.Path)
  125. // 2. 构建函数参数
  126. args := ha.buildArgs(w, r, pathParams)
  127. if args == nil {
  128. http.Error(w, "Invalid parameters", http.StatusBadRequest)
  129. return
  130. }
  131. // 3. 调用处理器函数
  132. results := ha.handlerFunc.Call(args)
  133. // 4. 处理返回结果
  134. ha.handleResponse(w, results)
  135. }
  136. // parsePathParams 解析路径参数
  137. func (ha *handlerAdapter) parsePathParams(requestPath string) map[string]string {
  138. params := make(map[string]string)
  139. pattern := strings.Trim(ha.pathPattern, "/")
  140. request := strings.Trim(requestPath, "/")
  141. patternParts := strings.Split(pattern, "/")
  142. requestParts := strings.Split(request, "/")
  143. for i, patternPart := range patternParts {
  144. if strings.HasPrefix(patternPart, "{") && strings.HasSuffix(patternPart, "}") {
  145. paramName := patternPart[1 : len(patternPart)-1]
  146. if i < len(requestParts) {
  147. params[paramName] = requestParts[i]
  148. }
  149. }
  150. }
  151. return params
  152. }
  153. func (ha *handlerAdapter) buildArgs(w http.ResponseWriter, r *http.Request, pathParams map[string]string) []reflect.Value {
  154. handlerType := ha.handlerFunc.Type()
  155. numIn := handlerType.NumIn()
  156. args := make([]reflect.Value, numIn)
  157. for i := 0; i < numIn; i++ {
  158. paramType := handlerType.In(i)
  159. paramName := getParamName(i, handlerType, ha.paramNames)
  160. // 1. 检查是否是特殊类型
  161. if arg := ha.bindSpecialType(paramType, w, r); arg.IsValid() {
  162. args[i] = arg
  163. continue
  164. }
  165. // 2. 检查是否是 *ctx.RequestContext 类型
  166. if paramType == reflect.TypeOf((*ctx.RequestContext)(nil)) {
  167. reqCtx := ctx.GetContext(r)
  168. args[i] = reflect.ValueOf(reqCtx)
  169. continue
  170. }
  171. // 3. 只按名称匹配路径参数
  172. if value, ok := pathParams[paramName]; ok {
  173. args[i] = convertToType(value, paramType)
  174. continue
  175. }
  176. // 4. 尝试从查询参数获取
  177. if queryValue := r.URL.Query().Get(paramName); queryValue != "" {
  178. args[i] = convertToType(queryValue, paramType)
  179. continue
  180. }
  181. // 5. 尝试从JSON body获取(POST/PUT请求)
  182. if (r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH") &&
  183. (paramType.Kind() == reflect.Struct ||
  184. (paramType.Kind() == reflect.Ptr && paramType.Elem().Kind() == reflect.Struct)) {
  185. if arg := ha.parseBody(r, paramType); arg.IsValid() {
  186. args[i] = arg
  187. continue
  188. }
  189. }
  190. // 6. 返回零值
  191. args[i] = reflect.Zero(paramType)
  192. }
  193. return args
  194. }
  195. // bindSpecialType 绑定特殊类型
  196. func (ha *handlerAdapter) bindSpecialType(paramType reflect.Type, w http.ResponseWriter, r *http.Request) reflect.Value {
  197. switch paramType {
  198. case reflect.TypeOf((*http.ResponseWriter)(nil)).Elem():
  199. return reflect.ValueOf(w)
  200. case reflect.TypeOf((*http.Request)(nil)):
  201. return reflect.ValueOf(r)
  202. }
  203. return reflect.Value{}
  204. }
  205. // getParamName 获取参数名
  206. func getParamName(index int, handlerType reflect.Type, pathParamNames []string) string {
  207. // 如果有路径参数名,优先使用
  208. if index < len(pathParamNames) {
  209. return pathParamNames[index]
  210. }
  211. // 使用类型名的蛇形格式
  212. paramType := handlerType.In(index)
  213. typeName := paramType.Name()
  214. if typeName == "" {
  215. return strconv.Itoa(index)
  216. }
  217. // 转换为蛇形格式:MyInterface -> my_interface
  218. var result []rune
  219. for i, r := range typeName {
  220. if i > 0 && 'A' <= r && r <= 'Z' {
  221. result = append(result, '_')
  222. }
  223. result = append(result, r)
  224. }
  225. return strings.ToLower(string(result))
  226. }
  227. // convertToType 字符串转换为指定类型
  228. func convertToType(str string, targetType reflect.Type) reflect.Value {
  229. switch targetType.Kind() {
  230. case reflect.String:
  231. return reflect.ValueOf(str)
  232. case reflect.Int:
  233. if i, err := strconv.Atoi(str); err == nil {
  234. return reflect.ValueOf(i)
  235. }
  236. case reflect.Int64:
  237. if i, err := strconv.ParseInt(str, 10, 64); err == nil {
  238. return reflect.ValueOf(i)
  239. }
  240. case reflect.Bool:
  241. if b, err := strconv.ParseBool(str); err == nil {
  242. return reflect.ValueOf(b)
  243. }
  244. case reflect.Float64:
  245. if f, err := strconv.ParseFloat(str, 64); err == nil {
  246. return reflect.ValueOf(f)
  247. }
  248. }
  249. return reflect.Value{}
  250. }
  251. // parseBody 解析请求体
  252. func (ha *handlerAdapter) parseBody(r *http.Request, paramType reflect.Type) reflect.Value {
  253. // 创建参数实例
  254. var paramValue reflect.Value
  255. if paramType.Kind() == reflect.Ptr {
  256. paramValue = reflect.New(paramType.Elem())
  257. } else {
  258. paramValue = reflect.New(paramType)
  259. }
  260. // 解析JSON
  261. if err := json.NewDecoder(r.Body).Decode(paramValue.Interface()); err != nil {
  262. return reflect.Value{}
  263. }
  264. defer r.Body.Close()
  265. // 如果是非指针类型,需要解引用
  266. if paramType.Kind() != reflect.Ptr {
  267. paramValue = paramValue.Elem()
  268. }
  269. return paramValue
  270. }
  271. // handleResponse 处理响应
  272. func (ha *handlerAdapter) handleResponse(w http.ResponseWriter, results []reflect.Value) {
  273. // 第一个返回值是数据
  274. data := results[0].Interface()
  275. // 第二个返回值是error
  276. errVal := results[1].Interface()
  277. if errVal != nil {
  278. err := errVal.(error)
  279. http.Error(w, err.Error(), http.StatusInternalServerError)
  280. return
  281. }
  282. // 检查是否是 []byte 类型
  283. if bytes, ok := data.([]byte); ok {
  284. // 如果是 []byte,直接写入响应,不进行 JSON 编码
  285. w.Write(bytes)
  286. return
  287. }
  288. // 返回JSON响应
  289. w.Header().Set("Content-Type", "application/json")
  290. json.NewEncoder(w).Encode(data)
  291. }
  292. // extractPathParams 从路径中提取参数名
  293. func extractPathParams(path string) []string {
  294. var params []string
  295. parts := strings.Split(strings.Trim(path, "/"), "/")
  296. for _, part := range parts {
  297. if strings.HasPrefix(part, "{") && strings.HasSuffix(part, "}") {
  298. paramName := part[1 : len(part)-1]
  299. params = append(params, paramName)
  300. }
  301. }
  302. return params
  303. }