25 lines
588 B
Go
25 lines
588 B
Go
package utils
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
// Json set the content type to json and encode the data
|
|
func Json(w http.ResponseWriter, data any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
var buf bytes.Buffer
|
|
err := json.NewEncoder(&buf).Encode(data)
|
|
if err != nil {
|
|
if recoverErr, ok := data.(recoverErr); ok {
|
|
w.WriteHeader(recoverErr.Code)
|
|
fmt.Fprint(w, recoverErr.Json())
|
|
} else {
|
|
http.Error(w, fmt.Sprintf("encode [%v] failed: %v", data, err), http.StatusInternalServerError)
|
|
}
|
|
}
|
|
fmt.Fprint(w, buf.String())
|
|
}
|