Browse Source

自动建立表通过-doris

qdy 2 months ago
parent
commit
33a35167ec
5 changed files with 704 additions and 0 deletions
  1. 156
    0
      myservice/crypto_service.go
  2. 0
    0
      myservice/start_service.go
  3. 159
    0
      webx/web_binder.go
  4. 128
    0
      webx/web_router.go
  5. 261
    0
      webx/web_service.go

+ 156
- 0
myservice/crypto_service.go View File

@@ -0,0 +1,156 @@
1
+package myservice
2
+
3
+import (
4
+	"crypto/aes"
5
+	"crypto/cipher"
6
+	"crypto/rand"
7
+	"encoding/base64"
8
+	"errors"
9
+	"fmt"
10
+	"io"
11
+	"strings"
12
+)
13
+
14
+// CryptoService 加密服务结构体
15
+type CryptoService struct {
16
+	key    []byte
17
+	prefix string // 加密文本前缀,用于识别是否已加密
18
+}
19
+
20
+// NewCryptoService 创建加密服务
21
+func NewCryptoService(key string) (*CryptoService, error) {
22
+	keyBytes := []byte(key)
23
+
24
+	// 如果密钥长度不足,使用PBKDF2派生密钥
25
+	if len(keyBytes) < 32 {
26
+		derivedKey, err := deriveKey(keyBytes, 32)
27
+		if err != nil {
28
+			return nil, err
29
+		}
30
+		keyBytes = derivedKey
31
+	} else if len(keyBytes) > 32 {
32
+		keyBytes = keyBytes[:32] // 截取前32字节
33
+	}
34
+
35
+	return &CryptoService{
36
+		key:    keyBytes,
37
+		prefix: "ENC::", // 加密文本前缀
38
+	}, nil
39
+}
40
+
41
+// deriveKey 使用PBKDF2派生密钥
42
+func deriveKey(password []byte, keyLen int) ([]byte, error) {
43
+	// 这里简化实现,实际应该使用crypto/sha256和更复杂的盐
44
+	// 为了简单示例,使用固定盐(生产环境应该使用随机盐)
45
+	salt := []byte("fixed-salt-for-demo")
46
+
47
+	hash := make([]byte, keyLen)
48
+	for i := 0; i < keyLen; i++ {
49
+		if i < len(password) {
50
+			hash[i] = password[i] ^ salt[i%len(salt)]
51
+		} else {
52
+			hash[i] = salt[i%len(salt)]
53
+		}
54
+	}
55
+	return hash, nil
56
+}
57
+
58
+// Encrypt 加密文本
59
+func (cs *CryptoService) Encrypt(plaintext string) (string, error) {
60
+	// 如果已经是加密文本,直接返回
61
+	if cs.IsEncrypted(plaintext) {
62
+		return plaintext, nil
63
+	}
64
+
65
+	block, err := aes.NewCipher(cs.key)
66
+	if err != nil {
67
+		return "", fmt.Errorf("创建密码块失败: %w", err)
68
+	}
69
+
70
+	gcm, err := cipher.NewGCM(block)
71
+	if err != nil {
72
+		return "", fmt.Errorf("创建GCM模式失败: %w", err)
73
+	}
74
+
75
+	nonce := make([]byte, gcm.NonceSize())
76
+	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
77
+		return "", fmt.Errorf("生成随机数失败: %w", err)
78
+	}
79
+
80
+	ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
81
+	encoded := base64.StdEncoding.EncodeToString(ciphertext)
82
+
83
+	// 添加前缀标识
84
+	return cs.prefix + encoded, nil
85
+}
86
+
87
+// Decrypt 解密文本
88
+func (cs *CryptoService) Decrypt(input string) (string, error) {
89
+	// 如果不是加密文本,直接返回原文本
90
+	if !cs.IsEncrypted(input) {
91
+		return input, nil
92
+	}
93
+
94
+	// 移除前缀
95
+	encoded := strings.TrimPrefix(input, cs.prefix)
96
+
97
+	ciphertext, err := base64.StdEncoding.DecodeString(encoded)
98
+	if err != nil {
99
+		// 如果不是有效的Base64,返回原文本
100
+		return input, nil
101
+	}
102
+
103
+	block, err := aes.NewCipher(cs.key)
104
+	if err != nil {
105
+		return "", fmt.Errorf("创建密码块失败: %w", err)
106
+	}
107
+
108
+	gcm, err := cipher.NewGCM(block)
109
+	if err != nil {
110
+		return "", fmt.Errorf("创建GCM模式失败: %w", err)
111
+	}
112
+
113
+	if len(ciphertext) < gcm.NonceSize() {
114
+		return "", errors.New("密文太短")
115
+	}
116
+
117
+	nonce, ciphertext := ciphertext[:gcm.NonceSize()], ciphertext[gcm.NonceSize():]
118
+
119
+	plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
120
+	if err != nil {
121
+		// 如果解密失败,返回原文本(可能是格式相似但不是真正的加密文本)
122
+		return input, nil
123
+	}
124
+
125
+	return string(plaintext), nil
126
+}
127
+
128
+// IsEncrypted 检查文本是否已加密
129
+func (cs *CryptoService) IsEncrypted(text string) bool {
130
+	return strings.HasPrefix(text, cs.prefix)
131
+}
132
+
133
+// EncryptOrDecrypt 智能加密或解密
134
+// 如果输入是明文则加密,如果已是密文则解密
135
+func (cs *CryptoService) EncryptOrDecrypt(input string) (string, error) {
136
+	if cs.IsEncrypted(input) {
137
+		return cs.Decrypt(input)
138
+	}
139
+	return cs.Encrypt(input)
140
+}
141
+
142
+// EncryptIfNeeded 如果需要则加密
143
+func (cs *CryptoService) EncryptIfNeeded(input string) (string, error) {
144
+	if cs.IsEncrypted(input) {
145
+		return input, nil
146
+	}
147
+	return cs.Encrypt(input)
148
+}
149
+
150
+// DecryptIfNeeded 如果需要则解密
151
+func (cs *CryptoService) DecryptIfNeeded(input string) (string, error) {
152
+	if cs.IsEncrypted(input) {
153
+		return cs.Decrypt(input)
154
+	}
155
+	return input, nil
156
+}

myservice/service.go → myservice/start_service.go View File


+ 159
- 0
webx/web_binder.go View File

@@ -0,0 +1,159 @@
1
+package webx
2
+
3
+import (
4
+	"context"
5
+	"encoding/json"
6
+	"net/http"
7
+	"reflect"
8
+	"strconv"
9
+	"strings"
10
+)
11
+
12
+// invokeHandler 调用处理器函数
13
+func (rb *routeBuilder) invokeHandler(ctx context.Context, w http.ResponseWriter, req *http.Request) {
14
+	handlerType := reflect.TypeOf(rb.handler)
15
+	handlerValue := reflect.ValueOf(rb.handler)
16
+
17
+	// 获取参数数量
18
+	numIn := handlerType.NumIn()
19
+	args := make([]reflect.Value, numIn)
20
+
21
+	// 绑定每个参数
22
+	for i := 0; i < numIn; i++ {
23
+		paramType := handlerType.In(i)
24
+		args[i] = rb.bindParam(i, paramType, ctx, w, req)
25
+	}
26
+
27
+	// 调用处理器函数
28
+	results := handlerValue.Call(args)
29
+
30
+	// 处理返回值
31
+	rb.handleResults(results, w)
32
+}
33
+
34
+// bindParam 绑定单个参数
35
+func (rb *routeBuilder) bindParam(index int, paramType reflect.Type, ctx context.Context, w http.ResponseWriter, req *http.Request) reflect.Value {
36
+	// 特殊类型绑定
37
+	switch paramType {
38
+	case reflect.TypeOf((*http.ResponseWriter)(nil)).Elem():
39
+		return reflect.ValueOf(w)
40
+	case reflect.TypeOf((*http.Request)(nil)):
41
+		return reflect.ValueOf(req)
42
+	case reflect.TypeOf((*context.Context)(nil)).Elem():
43
+		return reflect.ValueOf(ctx)
44
+	}
45
+
46
+	// 基本类型 - 尝试从路径参数绑定
47
+	if paramType.Kind() == reflect.String || paramType.Kind() == reflect.Int || paramType.Kind() == reflect.Int64 {
48
+		// 尝试从路径中提取参数
49
+		if pathParam := extractPathParam(rb.path, req.URL.Path, index); pathParam != "" {
50
+			return convertToType(pathParam, paramType)
51
+		}
52
+
53
+		// 尝试从查询参数绑定
54
+		if queryParam := extractQueryParam(paramType.Name(), req); queryParam != "" {
55
+			return convertToType(queryParam, paramType)
56
+		}
57
+	}
58
+
59
+	// 结构体 - 从 JSON 请求体绑定
60
+	if paramType.Kind() == reflect.Struct || (paramType.Kind() == reflect.Ptr && paramType.Elem().Kind() == reflect.Struct) {
61
+		return rb.bindFromJSON(paramType, req)
62
+	}
63
+
64
+	// 返回零值
65
+	return reflect.Zero(paramType)
66
+}
67
+
68
+// extractPathParam 从路径提取参数
69
+func extractPathParam(pattern, actualPath string, index int) string {
70
+	patternParts := strings.Split(strings.Trim(pattern, "/"), "/")
71
+	actualParts := strings.Split(strings.Trim(actualPath, "/"), "/")
72
+
73
+	for i, part := range patternParts {
74
+		if strings.HasPrefix(part, "{") && strings.HasSuffix(part, "}") {
75
+			if i < len(actualParts) {
76
+				return actualParts[i]
77
+			}
78
+		}
79
+	}
80
+
81
+	// 如果路径中没有参数,尝试最后一个部分
82
+	if len(actualParts) > 0 {
83
+		return actualParts[len(actualParts)-1]
84
+	}
85
+
86
+	return ""
87
+}
88
+
89
+// extractQueryParam 从查询参数提取
90
+func extractQueryParam(paramName string, req *http.Request) string {
91
+	// 转换为小写查找
92
+	key := strings.ToLower(paramName)
93
+	return req.URL.Query().Get(key)
94
+}
95
+
96
+// bindFromJSON 从 JSON 绑定
97
+func (rb *routeBuilder) bindFromJSON(paramType reflect.Type, req *http.Request) reflect.Value {
98
+	var val reflect.Value
99
+
100
+	if paramType.Kind() == reflect.Ptr {
101
+		val = reflect.New(paramType.Elem())
102
+	} else {
103
+		val = reflect.New(paramType)
104
+	}
105
+
106
+	if req.Body != nil {
107
+		defer req.Body.Close()
108
+		json.NewDecoder(req.Body).Decode(val.Interface())
109
+	}
110
+
111
+	if paramType.Kind() == reflect.Ptr {
112
+		return val
113
+	}
114
+	return val.Elem()
115
+}
116
+
117
+// convertToType 字符串转换为指定类型
118
+func convertToType(str string, targetType reflect.Type) reflect.Value {
119
+	switch targetType.Kind() {
120
+	case reflect.String:
121
+		return reflect.ValueOf(str)
122
+	case reflect.Int:
123
+		if i, err := strconv.Atoi(str); err == nil {
124
+			return reflect.ValueOf(i)
125
+		}
126
+	case reflect.Int64:
127
+		if i, err := strconv.ParseInt(str, 10, 64); err == nil {
128
+			return reflect.ValueOf(i)
129
+		}
130
+	case reflect.Bool:
131
+		if b, err := strconv.ParseBool(str); err == nil {
132
+			return reflect.ValueOf(b)
133
+		}
134
+	}
135
+	return reflect.Zero(targetType)
136
+}
137
+
138
+// handleResults 处理返回值
139
+func (rb *routeBuilder) handleResults(results []reflect.Value, w http.ResponseWriter) {
140
+	if len(results) == 0 {
141
+		return
142
+	}
143
+
144
+	// 第一个返回值处理
145
+	firstResult := results[0].Interface()
146
+
147
+	// 如果是错误
148
+	if err, ok := firstResult.(error); ok {
149
+		w.WriteHeader(http.StatusInternalServerError)
150
+		json.NewEncoder(w).Encode(map[string]interface{}{
151
+			"error": err.Error(),
152
+		})
153
+		return
154
+	}
155
+
156
+	// 如果是其他类型,返回 JSON
157
+	w.Header().Set("Content-Type", "application/json")
158
+	json.NewEncoder(w).Encode(firstResult)
159
+}

+ 128
- 0
webx/web_router.go View File

@@ -0,0 +1,128 @@
1
+package webx
2
+
3
+import (
4
+	"net/http"
5
+)
6
+
7
+// HandlerFunc 通用的处理器函数类型
8
+type HandlerFunc interface{}
9
+
10
+// Router 路由器
11
+type Router struct {
12
+	mux          *http.ServeMux
13
+	globalBefore []func(http.Handler) http.Handler
14
+	globalAfter  []func(http.ResponseWriter, *http.Request)
15
+}
16
+
17
+func NewRouter(mux *http.ServeMux) *Router {
18
+	return &Router{
19
+		mux: mux,
20
+	}
21
+}
22
+
23
+// UseBefore 在处理器前执行的中间件
24
+func (r *Router) UseBefore(middleware ...func(http.Handler) http.Handler) *Router {
25
+	r.globalBefore = append(r.globalBefore, middleware...)
26
+	return r
27
+}
28
+
29
+// UseAfter 在处理器后执行的中间件
30
+func (r *Router) UseAfter(middleware ...func(http.ResponseWriter, *http.Request)) *Router {
31
+	r.globalAfter = append(r.globalAfter, middleware...)
32
+	return r
33
+}
34
+
35
+// GET 注册 GET 请求
36
+func (r *Router) GET(path string, handler HandlerFunc) *routeBuilder {
37
+	return r.handle("GET", path, handler)
38
+}
39
+
40
+// POST 注册 POST 请求
41
+func (r *Router) POST(path string, handler HandlerFunc) *routeBuilder {
42
+	return r.handle("POST", path, handler)
43
+}
44
+
45
+// handle 内部处理方法
46
+func (r *Router) handle(method, path string, handler HandlerFunc) *routeBuilder {
47
+	return &routeBuilder{
48
+		router:  r,
49
+		method:  method,
50
+		path:    path,
51
+		handler: handler,
52
+	}
53
+}
54
+
55
+// 路由构建器
56
+type routeBuilder struct {
57
+	router      *Router
58
+	method      string
59
+	path        string
60
+	handler     HandlerFunc
61
+	before      []func(http.Handler) http.Handler
62
+	after       []func(http.ResponseWriter, *http.Request)
63
+	description string
64
+}
65
+
66
+// Before 添加路由前中间件
67
+func (rb *routeBuilder) Before(middleware ...func(http.Handler) http.Handler) *routeBuilder {
68
+	rb.before = append(rb.before, middleware...)
69
+	return rb
70
+}
71
+
72
+// After 添加路由后中间件
73
+func (rb *routeBuilder) After(middleware ...func(http.ResponseWriter, *http.Request)) *routeBuilder {
74
+	rb.after = append(rb.after, middleware...)
75
+	return rb
76
+}
77
+
78
+// Desc 添加描述
79
+func (rb *routeBuilder) Desc(desc string) *routeBuilder {
80
+	rb.description = desc
81
+	return rb
82
+}
83
+
84
+// Register 注册路由
85
+func (rb *routeBuilder) Register() {
86
+	// 创建最终的 HTTP 处理器
87
+	finalHandler := rb.createHandler()
88
+
89
+	// 应用路由级 before 中间件
90
+	for i := len(rb.before) - 1; i >= 0; i-- {
91
+		finalHandler = rb.before[i](finalHandler)
92
+	}
93
+
94
+	// 应用全局 before 中间件
95
+	for i := len(rb.router.globalBefore) - 1; i >= 0; i-- {
96
+		finalHandler = rb.router.globalBefore[i](finalHandler)
97
+	}
98
+
99
+	// 注册到 ServeMux
100
+	rb.router.mux.Handle(rb.path, finalHandler)
101
+}
102
+
103
+// 创建处理器
104
+func (rb *routeBuilder) createHandler() http.Handler {
105
+	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
106
+		// 方法检查
107
+		if rb.method != "" && req.Method != rb.method {
108
+			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
109
+			return
110
+		}
111
+
112
+		// 创建上下文
113
+		ctx := req.Context()
114
+
115
+		// 执行处理器
116
+		rb.invokeHandler(ctx, w, req)
117
+
118
+		// 执行路由级 after 中间件
119
+		for _, after := range rb.after {
120
+			after(w, req)
121
+		}
122
+
123
+		// 执行全局 after 中间件
124
+		for _, after := range rb.router.globalAfter {
125
+			after(w, req)
126
+		}
127
+	})
128
+}

+ 261
- 0
webx/web_service.go View File

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

Loading…
Cancel
Save