init.
This commit is contained in:
31
respose.go
Normal file
31
respose.go
Normal file
@@ -0,0 +1,31 @@
|
||||
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})
|
||||
}
|
||||
Reference in New Issue
Block a user