Nav apraksta
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

queryHandlerJson.go 948B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package myhandle
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "time"
  6. "git.x2erp.com/qdy/go-base/types"
  7. "git.x2erp.com/qdy/go-db/factory/database"
  8. )
  9. // queryHandler - 最简单的版本
  10. func QueryHandlerJson(
  11. w http.ResponseWriter,
  12. r *http.Request,
  13. dbFactory *database.DBFactory,
  14. handlerFunc func(*database.DBFactory, types.QueryRequest) *types.QueryResult,
  15. ) {
  16. // 解析请求参数
  17. var req types.QueryRequest
  18. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  19. // 如果解析失败,也返回 QueryResult 格式
  20. w.Header().Set("Content-Type", "application/json")
  21. json.NewEncoder(w).Encode(&types.QueryResult{
  22. Success: false,
  23. Error: "Invalid request body: " + err.Error(),
  24. Time: time.Now().Format(time.RFC3339),
  25. })
  26. return
  27. }
  28. // 执行业务逻辑
  29. result := handlerFunc(dbFactory, req)
  30. // 设置头,写入结果
  31. w.Header().Set("Content-Type", "application/json")
  32. json.NewEncoder(w).Encode(result)
  33. }