This repository has been archived on 2026-05-13. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
programA-3/respose.go
2025-11-12 19:55:29 +08:00

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})
}