You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/ngin/httpx/responses.go

30 lines
736 B
Go

package httpx
import (
"encoding/json"
"net/http"
"zero/core/logx"
)
func OkJson(w http.ResponseWriter, v interface{}) {
WriteJson(w, http.StatusOK, v)
}
func WriteJson(w http.ResponseWriter, code int, v interface{}) {
w.Header().Set(ContentType, ApplicationJson)
w.WriteHeader(code)
if bs, err := json.Marshal(v); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else if n, err := w.Write(bs); err != nil {
// http.ErrHandlerTimeout has been handled by http.TimeoutHandler,
// so it's ignored here.
if err != http.ErrHandlerTimeout {
logx.Errorf("write response failed, error: %s", err)
}
} else if n < len(bs) {
logx.Errorf("actual bytes: %d, written bytes: %d", len(bs), n)
}
}