47 lines
1.3 KiB
Go
47 lines
1.3 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
)
|
|
|
|
type ErrorResponse struct {
|
|
Error string `json:"error"`
|
|
Details string `json:"details,omitempty"`
|
|
}
|
|
|
|
func WriteError(w http.ResponseWriter, error, details string, statusCode int) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(statusCode)
|
|
json.NewEncoder(w).Encode(ErrorResponse{
|
|
Error: error,
|
|
Details: details,
|
|
})
|
|
}
|
|
|
|
// RFC-7807 (Problem Details)
|
|
type ProblemDetails struct {
|
|
Type string `json:"type" example:"https://api.triggerssmith.com/errors/role-not-found"`
|
|
Title string `json:"title" example:"Role not found"`
|
|
Status int `json:"status" example:"404"`
|
|
Detail string `json:"detail" example:"No role with ID 42"`
|
|
Instance string `json:"instance" example:"/api/acl/roles/42"`
|
|
}
|
|
|
|
var typeDomain = "https://api.triggerssmith.com"
|
|
|
|
func WriteProblem(w http.ResponseWriter, status int, typ, title, detail string, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/problem+json")
|
|
w.WriteHeader(status)
|
|
prob := ProblemDetails{
|
|
Type: typeDomain + typ,
|
|
Title: title,
|
|
Status: status,
|
|
Detail: detail,
|
|
Instance: r.URL.Path,
|
|
}
|
|
slog.Warn("new problem", "type", typ, "title", title, "detail", detail, "instance", r.URL.Path, "status", status)
|
|
_ = json.NewEncoder(w).Encode(prob)
|
|
}
|