@@ -26,6 +26,12 @@ type GeneralResponse struct {
2626 Msg string
2727}
2828
29+ type V2Response struct {
30+ Code int `json:"code"`
31+ Msg string `json:"msg"`
32+ Data any `json:"data"`
33+ }
34+
2935// APIHandler is a handler function that returns a response object or an error.
3036type APIHandler func (ctx * Context ) (any , error )
3137
@@ -64,3 +70,27 @@ func MakeHTTPHandlerFunc(handler APIHandler) http.HandlerFunc {
6470 }
6571 }
6672}
73+
74+ // MakeHTTPHandlerFuncV2 wraps a handler response in the dashboard API v2 envelope.
75+ func MakeHTTPHandlerFuncV2 (handler APIHandler ) http.HandlerFunc {
76+ return func (w http.ResponseWriter , r * http.Request ) {
77+ ctx := NewContext (w , r )
78+ res , err := handler (ctx )
79+ if err != nil {
80+ log .Warnf ("http response [%s]: error: %v" , r .URL .Path , err )
81+ code := http .StatusInternalServerError
82+ if e , ok := err .(* Error ); ok {
83+ code = e .Code
84+ }
85+
86+ w .Header ().Set ("Content-Type" , "application/json" )
87+ w .WriteHeader (code )
88+ _ = json .NewEncoder (w ).Encode (V2Response {Code : code , Msg : err .Error (), Data : nil })
89+ return
90+ }
91+
92+ w .Header ().Set ("Content-Type" , "application/json" )
93+ w .WriteHeader (http .StatusOK )
94+ _ = json .NewEncoder (w ).Encode (V2Response {Code : http .StatusOK , Msg : "success" , Data : res })
95+ }
96+ }
0 commit comments