github.com/tuingking/flamingo@v0.0.0-20220403134817-2796ae0e84ca/handler/rest/response.go (about) 1 package rest 2 3 import ( 4 "net/http" 5 "time" 6 7 "github.com/go-chi/render" 8 "github.com/pkg/errors" 9 "github.com/sirupsen/logrus" 10 ) 11 12 // Response defines http response for the client 13 type Response struct { 14 Code int `json:"code"` 15 Data interface{} `json:"data,omitempty"` 16 Error Error `json:"error"` 17 Message string `json:"message"` 18 ServerTime int64 `json:"serverTime"` 19 Pagination interface{} `json:"pagination,omitempty"` 20 } 21 22 // Error defines the error 23 type Error struct { 24 Status bool `json:"status" example:"false"` // true if we have error 25 Msg string `json:"msg" example:" "` // error message 26 Code int `json:"code" example:"0"` // application error code for tracing 27 } 28 29 // SetError set the response to return the given error. 30 // code is http status code, http.StatusInternalServerError is the default value 31 func (res *Response) SetError(err error, code ...int) { 32 logrus.Error(errors.Wrap(err, "ERR")) 33 res.ServerTime = time.Now().Unix() 34 35 if len(code) > 0 { 36 res.Code = code[0] 37 } else { 38 res.Code = http.StatusInternalServerError 39 } 40 41 if err != nil { 42 res.Error = Error{ 43 Msg: err.Error(), 44 Status: true, 45 } 46 } 47 48 } 49 50 // Render writes the http response to the client 51 func (res *Response) Render(w http.ResponseWriter, r *http.Request) { 52 res.ServerTime = time.Now().Unix() 53 54 if res.Code == 0 { 55 res.Code = http.StatusOK 56 } 57 58 render.Status(r, res.Code) 59 render.JSON(w, r, res) 60 }