api: fix validation and http response

This commit is contained in:
yusing
2025-01-04 09:01:52 +08:00
parent 112859caa5
commit c30d3f585f
6 changed files with 33 additions and 16 deletions

View File

@@ -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)