kojiapi: move from chi to echo

Follow the worker API so we standardise on one library. This simplifies
the code quite a bit.

No functional change.

Signed-off-by: Tom Gundersen <teg@jklm.no>
This commit is contained in:
Tom Gundersen 2020-09-17 13:14:02 +01:00
parent 504a5890d9
commit 6bab73f378
19 changed files with 111 additions and 2836 deletions

View file

@ -4,17 +4,10 @@
package api
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/deepmap/oapi-codegen/pkg/runtime"
"github.com/go-chi/chi"
"io"
"io/ioutil"
"github.com/labstack/echo/v4"
"net/http"
"net/url"
"strings"
)
// ComposeRequest defines model for ComposeRequest.
@ -70,421 +63,69 @@ type PostComposeJSONBody ComposeRequest
// PostComposeRequestBody defines body for PostCompose for application/json ContentType.
type PostComposeJSONRequestBody PostComposeJSONBody
// RequestEditorFn is the function signature for the RequestEditor callback function
type RequestEditorFn func(ctx context.Context, req *http.Request) error
// Doer performs HTTP requests.
//
// The standard http.Client implements this interface.
type HttpRequestDoer interface {
Do(req *http.Request) (*http.Response, error)
}
// Client which conforms to the OpenAPI3 specification for this service.
type Client struct {
// The endpoint of the server conforming to this interface, with scheme,
// https://api.deepmap.com for example.
Server string
// Doer for performing requests, typically a *http.Client with any
// customized settings, such as certificate chains.
Client HttpRequestDoer
// A callback for modifying requests which are generated before sending over
// the network.
RequestEditor RequestEditorFn
}
// ClientOption allows setting custom parameters during construction
type ClientOption func(*Client) error
// Creates a new Client, with reasonable defaults
func NewClient(server string, opts ...ClientOption) (*Client, error) {
// create a client with sane default values
client := Client{
Server: server,
}
// mutate client and add all optional params
for _, o := range opts {
if err := o(&client); err != nil {
return nil, err
}
}
// ensure the server URL always has a trailing slash
if !strings.HasSuffix(client.Server, "/") {
client.Server += "/"
}
// create httpClient, if not already present
if client.Client == nil {
client.Client = http.DefaultClient
}
return &client, nil
}
// WithHTTPClient allows overriding the default Doer, which is
// automatically created using http.Client. This is useful for tests.
func WithHTTPClient(doer HttpRequestDoer) ClientOption {
return func(c *Client) error {
c.Client = doer
return nil
}
}
// WithRequestEditorFn allows setting up a callback function, which will be
// called right before sending the request. This can be used to mutate the request.
func WithRequestEditorFn(fn RequestEditorFn) ClientOption {
return func(c *Client) error {
c.RequestEditor = fn
return nil
}
}
// The interface specification for the client above.
type ClientInterface interface {
// PostCompose request with any body
PostComposeWithBody(ctx context.Context, contentType string, body io.Reader) (*http.Response, error)
PostCompose(ctx context.Context, body PostComposeJSONRequestBody) (*http.Response, error)
// GetComposeId request
GetComposeId(ctx context.Context, id string) (*http.Response, error)
}
func (c *Client) PostComposeWithBody(ctx context.Context, contentType string, body io.Reader) (*http.Response, error) {
req, err := NewPostComposeRequestWithBody(c.Server, contentType, body)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
if c.RequestEditor != nil {
err = c.RequestEditor(ctx, req)
if err != nil {
return nil, err
}
}
return c.Client.Do(req)
}
func (c *Client) PostCompose(ctx context.Context, body PostComposeJSONRequestBody) (*http.Response, error) {
req, err := NewPostComposeRequest(c.Server, body)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
if c.RequestEditor != nil {
err = c.RequestEditor(ctx, req)
if err != nil {
return nil, err
}
}
return c.Client.Do(req)
}
func (c *Client) GetComposeId(ctx context.Context, id string) (*http.Response, error) {
req, err := NewGetComposeIdRequest(c.Server, id)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
if c.RequestEditor != nil {
err = c.RequestEditor(ctx, req)
if err != nil {
return nil, err
}
}
return c.Client.Do(req)
}
// NewPostComposeRequest calls the generic PostCompose builder with application/json body
func NewPostComposeRequest(server string, body PostComposeJSONRequestBody) (*http.Request, error) {
var bodyReader io.Reader
buf, err := json.Marshal(body)
if err != nil {
return nil, err
}
bodyReader = bytes.NewReader(buf)
return NewPostComposeRequestWithBody(server, "application/json", bodyReader)
}
// NewPostComposeRequestWithBody generates requests for PostCompose with any type of body
func NewPostComposeRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {
var err error
queryUrl, err := url.Parse(server)
if err != nil {
return nil, err
}
basePath := fmt.Sprintf("/compose")
if basePath[0] == '/' {
basePath = basePath[1:]
}
queryUrl, err = queryUrl.Parse(basePath)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", queryUrl.String(), body)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", contentType)
return req, nil
}
// NewGetComposeIdRequest generates requests for GetComposeId
func NewGetComposeIdRequest(server string, id string) (*http.Request, error) {
var err error
var pathParam0 string
pathParam0, err = runtime.StyleParam("simple", false, "id", id)
if err != nil {
return nil, err
}
queryUrl, err := url.Parse(server)
if err != nil {
return nil, err
}
basePath := fmt.Sprintf("/compose/%s", pathParam0)
if basePath[0] == '/' {
basePath = basePath[1:]
}
queryUrl, err = queryUrl.Parse(basePath)
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", queryUrl.String(), nil)
if err != nil {
return nil, err
}
return req, nil
}
// ClientWithResponses builds on ClientInterface to offer response payloads
type ClientWithResponses struct {
ClientInterface
}
// NewClientWithResponses creates a new ClientWithResponses, which wraps
// Client with return type handling
func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) {
client, err := NewClient(server, opts...)
if err != nil {
return nil, err
}
return &ClientWithResponses{client}, nil
}
// WithBaseURL overrides the baseURL.
func WithBaseURL(baseURL string) ClientOption {
return func(c *Client) error {
newBaseURL, err := url.Parse(baseURL)
if err != nil {
return err
}
c.Server = newBaseURL.String()
return nil
}
}
// ClientWithResponsesInterface is the interface specification for the client with responses above.
type ClientWithResponsesInterface interface {
// PostCompose request with any body
PostComposeWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader) (*PostComposeResponse, error)
PostComposeWithResponse(ctx context.Context, body PostComposeJSONRequestBody) (*PostComposeResponse, error)
// GetComposeId request
GetComposeIdWithResponse(ctx context.Context, id string) (*GetComposeIdResponse, error)
}
type PostComposeResponse struct {
Body []byte
HTTPResponse *http.Response
JSON201 *ComposeResponse
}
// Status returns HTTPResponse.Status
func (r PostComposeResponse) Status() string {
if r.HTTPResponse != nil {
return r.HTTPResponse.Status
}
return http.StatusText(0)
}
// StatusCode returns HTTPResponse.StatusCode
func (r PostComposeResponse) StatusCode() int {
if r.HTTPResponse != nil {
return r.HTTPResponse.StatusCode
}
return 0
}
type GetComposeIdResponse struct {
Body []byte
HTTPResponse *http.Response
JSON200 *ComposeStatus
}
// Status returns HTTPResponse.Status
func (r GetComposeIdResponse) Status() string {
if r.HTTPResponse != nil {
return r.HTTPResponse.Status
}
return http.StatusText(0)
}
// StatusCode returns HTTPResponse.StatusCode
func (r GetComposeIdResponse) StatusCode() int {
if r.HTTPResponse != nil {
return r.HTTPResponse.StatusCode
}
return 0
}
// PostComposeWithBodyWithResponse request with arbitrary body returning *PostComposeResponse
func (c *ClientWithResponses) PostComposeWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader) (*PostComposeResponse, error) {
rsp, err := c.PostComposeWithBody(ctx, contentType, body)
if err != nil {
return nil, err
}
return ParsePostComposeResponse(rsp)
}
func (c *ClientWithResponses) PostComposeWithResponse(ctx context.Context, body PostComposeJSONRequestBody) (*PostComposeResponse, error) {
rsp, err := c.PostCompose(ctx, body)
if err != nil {
return nil, err
}
return ParsePostComposeResponse(rsp)
}
// GetComposeIdWithResponse request returning *GetComposeIdResponse
func (c *ClientWithResponses) GetComposeIdWithResponse(ctx context.Context, id string) (*GetComposeIdResponse, error) {
rsp, err := c.GetComposeId(ctx, id)
if err != nil {
return nil, err
}
return ParseGetComposeIdResponse(rsp)
}
// ParsePostComposeResponse parses an HTTP response from a PostComposeWithResponse call
func ParsePostComposeResponse(rsp *http.Response) (*PostComposeResponse, error) {
bodyBytes, err := ioutil.ReadAll(rsp.Body)
defer rsp.Body.Close()
if err != nil {
return nil, err
}
response := &PostComposeResponse{
Body: bodyBytes,
HTTPResponse: rsp,
}
switch {
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201:
var dest ComposeResponse
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON201 = &dest
}
return response, nil
}
// ParseGetComposeIdResponse parses an HTTP response from a GetComposeIdWithResponse call
func ParseGetComposeIdResponse(rsp *http.Response) (*GetComposeIdResponse, error) {
bodyBytes, err := ioutil.ReadAll(rsp.Body)
defer rsp.Body.Close()
if err != nil {
return nil, err
}
response := &GetComposeIdResponse{
Body: bodyBytes,
HTTPResponse: rsp,
}
switch {
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
var dest ComposeStatus
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON200 = &dest
}
return response, nil
}
// ServerInterface represents all server handlers.
type ServerInterface interface {
// Create compose
// (POST /compose)
PostCompose(w http.ResponseWriter, r *http.Request)
PostCompose(ctx echo.Context) error
// The status of a compose
// (GET /compose/{id})
GetComposeId(w http.ResponseWriter, r *http.Request, id string)
GetComposeId(ctx echo.Context, id string) error
}
// ServerInterfaceWrapper converts contexts to parameters.
// ServerInterfaceWrapper converts echo contexts to parameters.
type ServerInterfaceWrapper struct {
Handler ServerInterface
}
// PostCompose operation middleware
func (siw *ServerInterfaceWrapper) PostCompose(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
siw.Handler.PostCompose(w, r.WithContext(ctx))
}
// GetComposeId operation middleware
func (siw *ServerInterfaceWrapper) GetComposeId(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// PostCompose converts echo context to params.
func (w *ServerInterfaceWrapper) PostCompose(ctx echo.Context) error {
var err error
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.PostCompose(ctx)
return err
}
// GetComposeId converts echo context to params.
func (w *ServerInterfaceWrapper) GetComposeId(ctx echo.Context) error {
var err error
// ------------- Path parameter "id" -------------
var id string
err = runtime.BindStyledParameter("simple", false, "id", chi.URLParam(r, "id"), &id)
err = runtime.BindStyledParameter("simple", false, "id", ctx.Param("id"), &id)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid format for parameter id: %s", err), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter id: %s", err))
}
siw.Handler.GetComposeId(w, r.WithContext(ctx), id)
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.GetComposeId(ctx, id)
return err
}
// Handler creates http.Handler with routing matching OpenAPI spec.
func Handler(si ServerInterface) http.Handler {
return HandlerFromMux(si, chi.NewRouter())
// This is a simple interface which specifies echo.Route addition functions which
// are present on both echo.Echo and echo.Group, since we want to allow using
// either of them for path registration
type EchoRouter interface {
CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
}
// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux.
func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler {
// RegisterHandlers adds each server route to the EchoRouter.
func RegisterHandlers(router EchoRouter, si ServerInterface) {
wrapper := ServerInterfaceWrapper{
Handler: si,
}
r.Group(func(r chi.Router) {
r.Post("/compose", wrapper.PostCompose)
})
r.Group(func(r chi.Router) {
r.Get("/compose/{id}", wrapper.GetComposeId)
})
router.POST("/compose", wrapper.PostCompose)
router.GET("/compose/:id", wrapper.GetComposeId)
return r
}

View file

@ -1,3 +1,3 @@
//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen --package=api --generate types,chi-server,client -o api.gen.go openapi.yml
//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen -package=api -generate types,server -o api.gen.go openapi.yml
package api