check params
This commit is contained in:
@@ -3,6 +3,7 @@ package response
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -16,6 +17,12 @@ type bodyWriter struct {
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
type responseData struct {
|
||||
Code int32 `json:"code"`
|
||||
Data any `json:"data"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
func (w *bodyWriter) WriteHeader(statusCode int) {
|
||||
w.status = statusCode
|
||||
}
|
||||
@@ -28,22 +35,22 @@ func Wrap(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
bw := &bodyWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next(bw, r)
|
||||
|
||||
log.Printf("raw json: %s", bw.status)
|
||||
ctrl := BaseController{}
|
||||
if bw.status >= http.StatusBadRequest {
|
||||
if bw.status != http.StatusOK {
|
||||
ctrl.Error(w, mapHTTPError(bw.status, bw.buf.String()))
|
||||
return
|
||||
}
|
||||
|
||||
raw := bytes.TrimSpace(bw.buf.Bytes())
|
||||
var data any
|
||||
var data responseData
|
||||
if len(raw) > 0 {
|
||||
if err := json.Unmarshal(raw, &data); err != nil {
|
||||
ctrl.Fail(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
ctrl.Ok(w, data)
|
||||
ctrl.OutPut(w, data.Code, data.Data, data.Msg)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,3 +52,12 @@ func (b *BaseController) Out(w http.ResponseWriter, data any, cm Error) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
}
|
||||
|
||||
func (b *BaseController) OutPut(w http.ResponseWriter, code int32, data any, msg string) {
|
||||
// 复制一份,避免并发请求改到包级 OK/Fail 单例
|
||||
out := NewError(int(code), msg).WithData(data)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user