Documentation
¶
Overview ¶
Package response provides JSON response helpers. Package response 提供 JSON 响应辅助函数。
Index ¶
- func InternalServerError() http.HandlerFunc
- func MethodNotAllowed() http.HandlerFunc
- func NotFound() http.HandlerFunc
- func Unauthorized() http.HandlerFunc
- func WriteJSON(w http.ResponseWriter, status int, v any)
- func WriteJSONError(w http.ResponseWriter, status int, code, msg string)
- type ErrorResponse
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func InternalServerError ¶ added in v0.4.2
func InternalServerError() http.HandlerFunc
InternalServerError returns a JSON 500 handler without internal error details. InternalServerError 返回不含内部错误详情的 JSON 500 handler。
func MethodNotAllowed ¶ added in v0.4.2
func MethodNotAllowed() http.HandlerFunc
MethodNotAllowed returns a JSON 405 handler. The router must set Allow. MethodNotAllowed 返回 JSON 405 handler;Allow 必须由路由器设置。
func NotFound ¶ added in v0.4.2
func NotFound() http.HandlerFunc
NotFound returns a JSON 404 handler for any request path. NotFound 返回适用于任意请求路径的 JSON 404 handler。
Example ¶
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/Ithildur/EiluneKit/http/middleware"
"github.com/Ithildur/EiluneKit/http/response"
"github.com/Ithildur/EiluneKit/http/routes"
)
func main() {
api := routes.NewBlueprint()
endpoint := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }
api.Get("/items", "", endpoint)
api.Get("/private", "", endpoint, routes.Auth(routes.AuthRequired))
api.Get("/panic", "", func(http.ResponseWriter, *http.Request) { panic("private details") })
h, err := routes.NewHandler(api.Routes(), routes.HandlerOptions{
NotFound: response.NotFound(),
MethodNotAllowed: response.MethodNotAllowed(),
Unauthorized: response.Unauthorized(),
Middleware: []routes.Middleware{
middleware.Recover(middleware.RecoverOptions{
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
OnPanic: response.InternalServerError(),
}),
},
})
if err != nil {
panic(err)
}
for _, request := range []struct{ method, path string }{
{"GET", "/missing"}, {"POST", "/items"}, {"GET", "/private"}, {"GET", "/panic"},
} {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest(request.method, request.path, nil))
fmt.Println(w.Code, w.Header().Get("Content-Type"), w.Body.String())
if w.Code == http.StatusMethodNotAllowed {
fmt.Println("Allow:", w.Header().Get("Allow"))
}
}
}
Output: 404 application/json; charset=utf-8 {"code":"not_found","message":"resource not found"} 405 application/json; charset=utf-8 {"code":"method_not_allowed","message":"method not allowed"} Allow: GET 401 application/json; charset=utf-8 {"code":"unauthorized","message":"authentication required"} 500 application/json; charset=utf-8 {"code":"internal_error","message":"internal server error"}
func Unauthorized ¶ added in v0.4.2
func Unauthorized() http.HandlerFunc
Unauthorized returns a JSON 401 handler. Authentication headers belong to the application. Unauthorized 返回 JSON 401 handler;认证响应头由应用设置。
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, status int, v any)
WriteJSON writes v as JSON with status. Call WriteJSON(w, status, value). WriteJSON 以 JSON 写入 value 和 status。 调用 WriteJSON(w, status, value)。
Example / 示例:
response.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
func WriteJSONError ¶
func WriteJSONError(w http.ResponseWriter, status int, code, msg string)
WriteJSONError writes ErrorResponse as JSON. Call WriteJSONError(w, status, code, message). WriteJSONError 以 JSON 写入 ErrorResponse。 调用 WriteJSONError(w, status, code, message)。
Example / 示例:
response.WriteJSONError(w, http.StatusBadRequest, "invalid_json", "invalid json")
Example (CustomHandler) ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/Ithildur/EiluneKit/http/middleware"
"github.com/Ithildur/EiluneKit/http/response"
)
func quotaExceeded(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", "60")
response.WriteJSONError(w, http.StatusTooManyRequests, "export_quota_exceeded", "try again in one minute")
}
func main() {
h := middleware.RateLimit(middleware.RateLimitOptions{
Requests: 1,
Window: time.Minute,
OnLimit: quotaExceeded,
})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
for range 2 {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/exports", nil))
fmt.Println(w.Code)
if w.Code == http.StatusTooManyRequests {
fmt.Println("Retry-After:", w.Header().Get("Retry-After"))
fmt.Println(w.Body.String())
}
}
}
Output: 204 429 Retry-After: 60 {"code":"export_quota_exceeded","message":"try again in one minute"}
Types ¶
type ErrorResponse ¶
ErrorResponse is the standard JSON error payload. ErrorResponse 是标准 JSON 错误响应体。