mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-19 23:11:25 +02:00
api: fix validation and http response
This commit is contained in:
@@ -48,7 +48,7 @@ func SetFileContent(w http.ResponseWriter, r *http.Request) {
|
||||
// no validation for include files
|
||||
|
||||
if valErr != nil {
|
||||
U.RespondJSON(w, r, valErr, http.StatusBadRequest)
|
||||
U.RespondError(w, valErr, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
E "github.com/yusing/go-proxy/internal/error"
|
||||
"github.com/yusing/go-proxy/internal/utils/strutils/ansi"
|
||||
)
|
||||
|
||||
// HandleErr logs the error and returns an HTTP error response to the client.
|
||||
@@ -23,6 +24,13 @@ func HandleErr(w http.ResponseWriter, r *http.Request, origErr error, code ...in
|
||||
http.Error(w, http.StatusText(statusCode), statusCode)
|
||||
}
|
||||
|
||||
func RespondError(w http.ResponseWriter, err error, code ...int) {
|
||||
if len(code) > 0 {
|
||||
w.WriteHeader(code[0])
|
||||
}
|
||||
WriteBody(w, []byte(ansi.StripANSI(err.Error())))
|
||||
}
|
||||
|
||||
func ErrMissingKey(k string) error {
|
||||
return E.New("missing key '" + k + "' in query or request body")
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/yusing/go-proxy/internal/logging"
|
||||
"github.com/yusing/go-proxy/internal/utils/strutils/ansi"
|
||||
)
|
||||
|
||||
func WriteBody(w http.ResponseWriter, body []byte) {
|
||||
@@ -27,13 +28,17 @@ func RespondJSON(w http.ResponseWriter, r *http.Request, data any, code ...int)
|
||||
j = []byte(fmt.Sprintf("%q", data))
|
||||
case []byte:
|
||||
j = data
|
||||
case error:
|
||||
j, err = json.Marshal(ansi.StripANSI(data.Error()))
|
||||
default:
|
||||
j, err = json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
logging.Panic().Err(err).Msg("failed to marshal json")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logging.Panic().Err(err).Msg("failed to marshal json")
|
||||
return false
|
||||
}
|
||||
|
||||
_, err = w.Write(j)
|
||||
if err != nil {
|
||||
HandleErr(w, r, err)
|
||||
|
||||
Reference in New Issue
Block a user