Nessuna descrizione
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

web_service.go 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package webx
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "reflect"
  6. "strings"
  7. )
  8. // WebService 路由服务
  9. type WebService struct {
  10. router *http.ServeMux
  11. }
  12. // NewWebService 创建WebService
  13. func NewWebService(router *http.ServeMux) *WebService {
  14. return &WebService{router: router}
  15. }
  16. // RouteBuilder 路由构建器
  17. type RouteBuilder struct {
  18. method string
  19. path string
  20. handlerFunc reflect.Value
  21. paramNames []string
  22. paramTypes []reflect.Type
  23. middlewares []func(http.Handler) http.Handler
  24. router *http.ServeMux
  25. }
  26. // GET 注册GET请求
  27. func (ws *WebService) GET(path string, handler interface{}) *RouteBuilder {
  28. return ws.handle("GET", path, handler)
  29. }
  30. // POST 注册POST请求
  31. func (ws *WebService) POST(path string, handler interface{}) *RouteBuilder {
  32. return ws.handle("POST", path, handler)
  33. }
  34. // PUT 注册PUT请求
  35. func (ws *WebService) PUT(path string, handler interface{}) *RouteBuilder {
  36. return ws.handle("PUT", path, handler)
  37. }
  38. // DELETE 注册DELETE请求
  39. func (ws *WebService) DELETE(path string, handler interface{}) *RouteBuilder {
  40. return ws.handle("DELETE", path, handler)
  41. }
  42. // handle 统一处理方法
  43. func (ws *WebService) handle(method, path string, handler interface{}) *RouteBuilder {
  44. // 解析路径参数名
  45. paramNames := extractPathParams(path)
  46. // 获取处理器函数信息
  47. handlerValue := reflect.ValueOf(handler)
  48. handlerType := handlerValue.Type()
  49. // 验证处理器函数
  50. if handlerType.Kind() != reflect.Func {
  51. panic("handler must be a function")
  52. }
  53. // 获取参数类型
  54. paramTypes := make([]reflect.Type, handlerType.NumIn())
  55. for i := 0; i < handlerType.NumIn(); i++ {
  56. paramTypes[i] = handlerType.In(i)
  57. }
  58. // 验证返回值
  59. if handlerType.NumOut() != 2 {
  60. panic("handler must return exactly 2 values: (T, error)")
  61. }
  62. return &RouteBuilder{
  63. method: method,
  64. path: path,
  65. handlerFunc: handlerValue,
  66. paramNames: paramNames,
  67. paramTypes: paramTypes,
  68. router: ws.router,
  69. }
  70. }
  71. // Use 添加中间件
  72. func (rb *RouteBuilder) Use(middleware ...func(http.Handler) http.Handler) *RouteBuilder {
  73. rb.middlewares = append(rb.middlewares, middleware...)
  74. return rb
  75. }
  76. // Register 注册路由
  77. func (rb *RouteBuilder) Register() {
  78. // 创建适配器
  79. adapter := &handlerAdapter{
  80. method: rb.method,
  81. pathPattern: rb.path,
  82. paramNames: rb.paramNames,
  83. paramTypes: rb.paramTypes,
  84. handlerFunc: rb.handlerFunc,
  85. }
  86. // 应用中间件
  87. var handler http.Handler = adapter
  88. for i := len(rb.middlewares) - 1; i >= 0; i-- {
  89. handler = rb.middlewares[i](handler)
  90. }
  91. // 注册到路由器
  92. rb.router.Handle(rb.path, handler)
  93. }
  94. // handlerAdapter 处理器适配器
  95. type handlerAdapter struct {
  96. method string
  97. pathPattern string
  98. paramNames []string
  99. paramTypes []reflect.Type
  100. handlerFunc reflect.Value
  101. }
  102. func (ha *handlerAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  103. // 只处理指定方法的请求
  104. if r.Method != ha.method {
  105. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  106. return
  107. }
  108. // 1. 解析路径参数
  109. pathParams := ha.parsePathParams(r.URL.Path)
  110. // 2. 构建函数参数
  111. args := ha.buildArgs(r, pathParams)
  112. if args == nil {
  113. http.Error(w, "Invalid parameters", http.StatusBadRequest)
  114. return
  115. }
  116. // 3. 调用处理器函数
  117. results := ha.handlerFunc.Call(args)
  118. // 4. 处理返回结果
  119. ha.handleResponse(w, results)
  120. }
  121. // parsePathParams 解析路径参数
  122. func (ha *handlerAdapter) parsePathParams(requestPath string) map[string]string {
  123. params := make(map[string]string)
  124. // 简单实现:按/分割,然后匹配
  125. patternParts := strings.Split(ha.pathPattern, "/")
  126. requestParts := strings.Split(requestPath, "/")
  127. if len(patternParts) != len(requestParts) {
  128. return params
  129. }
  130. for i, patternPart := range patternParts {
  131. if strings.HasPrefix(patternPart, "{") && strings.HasSuffix(patternPart, "}") {
  132. paramName := patternPart[1 : len(patternPart)-1]
  133. params[paramName] = requestParts[i]
  134. }
  135. }
  136. return params
  137. }
  138. // buildArgs 构建函数参数
  139. func (ha *handlerAdapter) buildArgs(r *http.Request, pathParams map[string]string) []reflect.Value {
  140. args := make([]reflect.Value, len(ha.paramTypes))
  141. // 参数索引
  142. pathParamIndex := 0
  143. for i, paramType := range ha.paramTypes {
  144. // 情况1:路径参数(必须是string类型)
  145. if pathParamIndex < len(ha.paramNames) && paramType.Kind() == reflect.String {
  146. paramName := ha.paramNames[pathParamIndex]
  147. if value, ok := pathParams[paramName]; ok {
  148. args[i] = reflect.ValueOf(value)
  149. pathParamIndex++
  150. continue
  151. }
  152. }
  153. // 情况2:Body参数(POST/PUT等请求的结构体)
  154. if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" {
  155. // 检查是否是结构体类型
  156. if paramType.Kind() == reflect.Struct ||
  157. (paramType.Kind() == reflect.Ptr && paramType.Elem().Kind() == reflect.Struct) {
  158. bodyParam, err := ha.parseBody(r, paramType)
  159. if err != nil {
  160. return nil
  161. }
  162. args[i] = bodyParam
  163. continue
  164. }
  165. }
  166. // 无法处理的参数类型
  167. return nil
  168. }
  169. return args
  170. }
  171. // parseBody 解析请求体
  172. func (ha *handlerAdapter) parseBody(r *http.Request, paramType reflect.Type) (reflect.Value, error) {
  173. // 创建参数实例
  174. var paramValue reflect.Value
  175. if paramType.Kind() == reflect.Ptr {
  176. paramValue = reflect.New(paramType.Elem())
  177. } else {
  178. paramValue = reflect.New(paramType)
  179. }
  180. // 解析JSON
  181. if err := json.NewDecoder(r.Body).Decode(paramValue.Interface()); err != nil {
  182. return reflect.Value{}, err
  183. }
  184. // 如果是非指针类型,需要解引用
  185. if paramType.Kind() != reflect.Ptr {
  186. paramValue = paramValue.Elem()
  187. }
  188. return paramValue, nil
  189. }
  190. // handleResponse 处理响应
  191. func (ha *handlerAdapter) handleResponse(w http.ResponseWriter, results []reflect.Value) {
  192. // 第一个返回值是数据
  193. data := results[0].Interface()
  194. // 第二个返回值是error
  195. errVal := results[1].Interface()
  196. if errVal != nil {
  197. err := errVal.(error)
  198. http.Error(w, err.Error(), http.StatusInternalServerError)
  199. return
  200. }
  201. // 返回JSON响应
  202. w.Header().Set("Content-Type", "application/json")
  203. json.NewEncoder(w).Encode(data)
  204. }
  205. // extractPathParams 从路径中提取参数名
  206. func extractPathParams(path string) []string {
  207. var params []string
  208. parts := strings.Split(path, "/")
  209. for _, part := range parts {
  210. if strings.HasPrefix(part, "{") && strings.HasSuffix(part, "}") {
  211. paramName := part[1 : len(part)-1]
  212. params = append(params, paramName)
  213. }
  214. }
  215. return params
  216. }