32 lines
862 B
Go
32 lines
862 B
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
type Result[T any] struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data *T `json:"data,omitempty"`
|
|
}
|
|
|
|
func writeJSON[T any](w http.ResponseWriter, status int, payload Result[T]) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
json.NewEncoder(w).Encode(payload)
|
|
}
|
|
|
|
func ok[T any](w http.ResponseWriter, data *T) {
|
|
writeJSON(w, http.StatusOK, Result[T]{Code: 0, Message: "OK", Data: data})
|
|
}
|
|
|
|
func created[T any](w http.ResponseWriter, location string, data *T) {
|
|
w.Header().Set("Location", location)
|
|
writeJSON(w, http.StatusCreated, Result[T]{Code: 0, Message: "Created", Data: data})
|
|
}
|
|
|
|
func fail(w http.ResponseWriter, status int, msg string) {
|
|
writeJSON[any](w, status, Result[any]{Code: status, Message: msg, Data: nil})
|
|
}
|