2025-03-21 11:05:42 +08:00

62 lines
1.3 KiB
Go

package tpl
import (
"encoding/json"
"net/http"
)
type Response struct {
Success bool `json:"success"`
Message string `json:"msg"`
Data any `json:"data"`
}
type ResponseDtree struct {
Status ResponseDtreeStatus `json:"status"`
Data any `json:"data"`
}
type ResponseDtreeStatus struct {
Code int `json:"code"`
Message string `json:"message"`
}
type ResponseList struct {
Code int `json:"code"`
Message string `json:"msg"`
Count int64 `json:"count"`
Data any `json:"data"`
}
func JSON(w http.ResponseWriter, data any) {
rndr.json(w, data)
}
func JSONF(w http.ResponseWriter, success bool, message string) {
rndr.json(w, Response{Success: success, Message: message})
}
func JSONOK(w http.ResponseWriter, message string) {
rndr.json(w, Response{Success: true, Message: message})
}
func JSONERR(w http.ResponseWriter, message string) {
rndr.json(w, Response{Success: false, Message: message})
}
func (r *render) json(w http.ResponseWriter, data any) {
v, err := json.Marshal(data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, err = w.Write(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}