58 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			58 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package render
 | |
| 
 | |
| import (
 | |
| 	"encoding/json"
 | |
| 	"net/http"
 | |
| )
 | |
| 
 | |
| type Response struct {
 | |
| 	Success bool   `json:"success"`
 | |
| 	Message string `json:"msg"`
 | |
| 	Data    any    `json:"data"`
 | |
| }
 | |
| 
 | |
| type ResponseTree struct {
 | |
| 	Status ResponseTreeStatus `json:"status"`
 | |
| 	Data   any                `json:"data"`
 | |
| }
 | |
| 
 | |
| type ResponseTreeStatus 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 (r *render) JSONOk(w http.ResponseWriter, message string) {
 | |
| 	r.JSON(w, Response{Success: true, Message: message})
 | |
| }
 | |
| 
 | |
| func (r *render) JSONErr(w http.ResponseWriter, message string) {
 | |
| 	r.JSON(w, Response{Success: false, Message: message})
 | |
| }
 | |
| 
 | |
| func (r *render) JSONObj(w http.ResponseWriter, message string, data any) {
 | |
| 	r.JSON(w, Response{Success: true, Message: message, Data: data})
 | |
| }
 | |
| 
 | |
| 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
 | |
| 	}
 | |
| }
 |