package apiv1
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
)
const (
ProblemCodeForbidden ProblemCode = "forbidden"
ProblemCodeInternal ProblemCode = "internal"
ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed"
ProblemCodeNotFound ProblemCode = "not_found"
ProblemCodeUnauthorized ProblemCode = "unauthorized"
ProblemCodeUnavailable ProblemCode = "unavailable"
ProblemCodeValidation ProblemCode = "validation"
)
func (e ProblemCode) Valid() bool {
switch e {
case ProblemCodeForbidden:
return true
case ProblemCodeInternal:
return true
case ProblemCodeMethodNotAllowed:
return true
case ProblemCodeNotFound:
return true
case ProblemCodeUnauthorized:
return true
case ProblemCodeUnavailable:
return true
case ProblemCodeValidation:
return true
default:
return false
}
}
const (
ServerInfoLoginMethodsPassword ServerInfoLoginMethods = "password"
)
func (e ServerInfoLoginMethods) Valid() bool {
switch e {
case ServerInfoLoginMethodsPassword:
return true
default:
return false
}
}
type Problem struct {
Code ProblemCode `json:"code"`
Detail *string `json:"detail,omitempty"`
Errors *[]ValidationError `json:"errors,omitempty"`
Status int `json:"status"`
Title string `json:"title"`
Type *string `json:"type,omitempty"`
}
type ProblemCode string
type ServerInfo struct {
LoginMethods []ServerInfoLoginMethods `json:"loginMethods"`
Name string `json:"name"`
ServerVersion string `json:"serverVersion"`
SetupRequired bool `json:"setupRequired"`
SpecVersion string `json:"specVersion"`
}
type ServerInfoLoginMethods string
type ValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
}
type InternalError = Problem
type ServerInterface interface {
GetServerInfo(w http.ResponseWriter, r *http.Request)
}
type Unimplemented struct{}
func (_ Unimplemented) GetServerInfo(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotImplemented)
}
type ServerInterfaceWrapper struct {
Handler ServerInterface
HandlerMiddlewares []MiddlewareFunc
ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)
}
type MiddlewareFunc func(http.Handler) http.Handler
func (siw *ServerInterfaceWrapper) GetServerInfo(w http.ResponseWriter, r *http.Request) {
handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
siw.Handler.GetServerInfo(w, r)
}))
for _, middleware := range siw.HandlerMiddlewares {
handler = middleware(handler)
}
handler.ServeHTTP(w, r)
}
type UnescapedCookieParamError struct {
ParamName string
Err error
}
func (e *UnescapedCookieParamError) Error() string {
return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName)
}
func (e *UnescapedCookieParamError) Unwrap() error {
return e.Err
}
type UnmarshalingParamError struct {
ParamName string
Err error
}
func (e *UnmarshalingParamError) Error() string {
return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error())
}
func (e *UnmarshalingParamError) Unwrap() error {
return e.Err
}
type RequiredParamError struct {
ParamName string
}
func (e *RequiredParamError) Error() string {
return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName)
}
type RequiredHeaderError struct {
ParamName string
Err error
}
func (e *RequiredHeaderError) Error() string {
return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName)
}
func (e *RequiredHeaderError) Unwrap() error {
return e.Err
}
type InvalidParamFormatError struct {
ParamName string
Err error
}
func (e *InvalidParamFormatError) Error() string {
return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error())
}
func (e *InvalidParamFormatError) Unwrap() error {
return e.Err
}
type TooManyValuesForParamError struct {
ParamName string
Count int
}
func (e *TooManyValuesForParamError) Error() string {
return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count)
}
func Handler(si ServerInterface) http.Handler {
return HandlerWithOptions(si, ChiServerOptions{})
}
type ChiServerOptions struct {
BaseURL string
BaseRouter chi.Router
Middlewares []MiddlewareFunc
ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)
}
func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler {
return HandlerWithOptions(si, ChiServerOptions{
BaseRouter: r,
})
}
func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler {
return HandlerWithOptions(si, ChiServerOptions{
BaseURL: baseURL,
BaseRouter: r,
})
}
func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler {
r := options.BaseRouter
if r == nil {
r = chi.NewRouter()
}
if options.ErrorHandlerFunc == nil {
options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
}
}
wrapper := ServerInterfaceWrapper{
Handler: si,
HandlerMiddlewares: options.Middlewares,
ErrorHandlerFunc: options.ErrorHandlerFunc,
}
r.Group(func(r chi.Router) {
r.Get(options.BaseURL+"/server", wrapper.GetServerInfo)
})
return r
}
type InternalErrorApplicationProblemPlusJSONResponse Problem
type GetServerInfoRequestObject struct {
}
type GetServerInfoResponseObject interface {
VisitGetServerInfoResponse(w http.ResponseWriter) error
}
type GetServerInfo200JSONResponse ServerInfo
func (response GetServerInfo200JSONResponse) VisitGetServerInfoResponse(w http.ResponseWriter) error {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(response); err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, err := buf.WriteTo(w)
return err
}
type GetServerInfo500ApplicationProblemPlusJSONResponse struct {
InternalErrorApplicationProblemPlusJSONResponse
}
func (response GetServerInfo500ApplicationProblemPlusJSONResponse) VisitGetServerInfoResponse(w http.ResponseWriter) error {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(response); err != nil {
return err
}
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(500)
_, err := buf.WriteTo(w)
return err
}
type StrictServerInterface interface {
GetServerInfo(ctx context.Context, request GetServerInfoRequestObject) (GetServerInfoResponseObject, error)
}
type StrictHandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request, request any) (any, error)
type StrictMiddlewareFunc func(f StrictHandlerFunc, operationID string) StrictHandlerFunc
type StrictHTTPServerOptions struct {
RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)
ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)
}
func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface {
return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{
RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
},
ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusInternalServerError)
},
}}
}
func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface {
if options.RequestErrorHandlerFunc == nil {
options.RequestErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
}
}
if options.ResponseErrorHandlerFunc == nil {
options.ResponseErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
return &strictHandler{ssi: ssi, middlewares: middlewares, options: options}
}
type strictHandler struct {
ssi StrictServerInterface
middlewares []StrictMiddlewareFunc
options StrictHTTPServerOptions
}
func (sh *strictHandler) GetServerInfo(w http.ResponseWriter, r *http.Request) {
var request GetServerInfoRequestObject
handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) {
return sh.ssi.GetServerInfo(ctx, request.(GetServerInfoRequestObject))
}
for _, middleware := range sh.middlewares {
handler = middleware(handler, "GetServerInfo")
}
response, err := handler(r.Context(), w, r, request)
if err != nil {
sh.options.ResponseErrorHandlerFunc(w, r, err)
} else if validResponse, ok := response.(GetServerInfoResponseObject); ok {
if err := validResponse.VisitGetServerInfoResponse(w); err != nil {
sh.options.ResponseErrorHandlerFunc(w, r, err)
}
} else if response != nil {
sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response))
}
}