|
|
@ -3,12 +3,22 @@ package httpx
|
|
|
|
import (
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
|
|
|
|
"github.com/tal-tech/go-zero/core/logx"
|
|
|
|
"github.com/tal-tech/go-zero/core/logx"
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var (
|
|
|
|
|
|
|
|
errorHandler = defaultErrorHandler
|
|
|
|
|
|
|
|
lock sync.RWMutex
|
|
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
func Error(w http.ResponseWriter, err error) {
|
|
|
|
func Error(w http.ResponseWriter, err error) {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
lock.RLock()
|
|
|
|
|
|
|
|
code, body := errorHandler(err)
|
|
|
|
|
|
|
|
lock.RUnlock()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
WriteJson(w, code, body)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func Ok(w http.ResponseWriter) {
|
|
|
|
func Ok(w http.ResponseWriter) {
|
|
|
@ -19,6 +29,12 @@ func OkJson(w http.ResponseWriter, v interface{}) {
|
|
|
|
WriteJson(w, http.StatusOK, v)
|
|
|
|
WriteJson(w, http.StatusOK, v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func SetErrorHandler(handler func(error) (int, interface{})) {
|
|
|
|
|
|
|
|
lock.Lock()
|
|
|
|
|
|
|
|
defer lock.Unlock()
|
|
|
|
|
|
|
|
errorHandler = handler
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func WriteJson(w http.ResponseWriter, code int, v interface{}) {
|
|
|
|
func WriteJson(w http.ResponseWriter, code int, v interface{}) {
|
|
|
|
w.Header().Set(ContentType, ApplicationJson)
|
|
|
|
w.Header().Set(ContentType, ApplicationJson)
|
|
|
|
w.WriteHeader(code)
|
|
|
|
w.WriteHeader(code)
|
|
|
@ -35,3 +51,7 @@ func WriteJson(w http.ResponseWriter, code int, v interface{}) {
|
|
|
|
logx.Errorf("actual bytes: %d, written bytes: %d", len(bs), n)
|
|
|
|
logx.Errorf("actual bytes: %d, written bytes: %d", len(bs), n)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func defaultErrorHandler(err error) (int, interface{}) {
|
|
|
|
|
|
|
|
return http.StatusBadRequest, err
|
|
|
|
|
|
|
|
}
|
|
|
|