diff --git a/cmd/server/main.go b/cmd/server/main.go index 715dad4..8d514cd 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -52,6 +52,7 @@ func main() { r.HandleFunc("/retries", retries.HandleRetries).Methods(http.MethodGet, http.MethodPost) r.HandleFunc("/retries/after", retries.HandleRetries).Methods(http.MethodGet) r.HandleFunc("/errors/{status_code}", errors.HandleErrors).Methods(http.MethodGet, http.MethodPost) + r.HandleFunc("/errors/union/{tag}", errors.HandleErrorsUnion).Methods(http.MethodGet) r.HandleFunc("/optional", acceptHeaders.HandleAcceptHeaderMultiplexing).Methods(http.MethodGet) r.HandleFunc("/readonlyorwriteonly", readonlywriteonly.HandleReadOrWrite).Methods(http.MethodPost) r.HandleFunc("/readonlyandwriteonly", readonlywriteonly.HandleReadAndWrite).Methods(http.MethodPost) diff --git a/internal/errors/service.go b/internal/errors/service.go index 85bbd08..8f6df5d 100644 --- a/internal/errors/service.go +++ b/internal/errors/service.go @@ -1,6 +1,7 @@ package errors import ( + "bytes" "encoding/json" "fmt" "io" @@ -55,3 +56,84 @@ func HandleErrors(w http.ResponseWriter, r *http.Request) { return } } + +// Returns one of an errors union with a 400 Bad Request status, based on the +// provided tag name in the path parameters with these response schemas: +// +// taggedError1: +// type: object +// properties: +// tag: +// type: string +// enum: [tag1] +// error: +// type: string +// required: +// - tag +// - error +// taggedError2: +// type: object +// properties: +// tag: +// type: string +// const: tag2 +// error: +// type: object +// properties: +// message: +// type: string +// required: +// - message +// required: +// - tag +// - error +func HandleErrorsUnion(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + tag, ok := vars["tag"] + + if !ok { + utils.HandleError(w, fmt.Errorf("tag path parameter is required")) + return + } + + if tag != "tag1" && tag != "tag2" { + utils.HandleError(w, fmt.Errorf("tag path parameter must be either tag1 or tag2")) + return + } + + var errorRes any + var responseBody bytes.Buffer + + if tag == "tag1" { + errorRes = struct { + Tag string `json:"tag"` + Error string `json:"error"` + }{ + Tag: "tag1", + Error: "intentional tag1 error", + } + } else { + errorRes = struct { + Tag string `json:"tag"` + Error struct { + Message string `json:"message"` + } `json:"error"` + }{ + Tag: "tag2", + Error: struct { + Message string `json:"message"` + }{ + Message: "intentional tag2 error", + }, + } + } + + if err := json.NewEncoder(&responseBody).Encode(errorRes); err != nil { + utils.HandleError(w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write(responseBody.Bytes()) +}