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

View file

@ -11,6 +11,7 @@ import (
"net/url"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/osbuild/osbuild-composer/internal/blueprint"
"github.com/osbuild/osbuild-composer/internal/common"
"github.com/osbuild/osbuild-composer/internal/distro"
@ -23,6 +24,7 @@ import (
// Server represents the state of the koji Server
type Server struct {
echo *echo.Echo
workers *worker.Server
rpmMetadata rpmmd.RPMMD
distros *distro.Registry
@ -30,21 +32,28 @@ type Server struct {
}
// NewServer creates a new koji server
func NewServer(workers *worker.Server, rpmMetadata rpmmd.RPMMD, distros *distro.Registry, kojiServers map[string]koji.GSSAPICredentials) *Server {
server := &Server{
func NewServer(logger *log.Logger, workers *worker.Server, rpmMetadata rpmmd.RPMMD, distros *distro.Registry, kojiServers map[string]koji.GSSAPICredentials) *Server {
s := &Server{
workers: workers,
rpmMetadata: rpmMetadata,
distros: distros,
kojiServers: kojiServers,
}
return server
s.echo = echo.New()
s.echo.Binder = binder{}
s.echo.StdLogger = logger
api.RegisterHandlers(s.echo, &apiHandlers{s})
return s
}
// Serve serves the koji API over the provided listener socket
func (server *Server) Serve(listener net.Listener) error {
s := http.Server{Handler: api.Handler(server)}
func (s *Server) Serve(listener net.Listener) error {
s.echo.Listener = listener
err := s.Serve(listener)
err := s.echo.Start("")
if err != nil && err != http.ErrServerClosed {
return err
}
@ -52,37 +61,33 @@ func (server *Server) Serve(listener net.Listener) error {
return nil
}
// apiHandlers implements api.ServerInterface - the http api route handlers
// generated from api/openapi.yml. This is a separate object, because these
// handlers should not be exposed on the `Server` object.
type apiHandlers struct {
server *Server
}
// PostCompose handles a new /compose POST request
func (server *Server) PostCompose(w http.ResponseWriter, r *http.Request) {
contentType := r.Header["Content-Type"]
if len(contentType) != 1 || contentType[0] != "application/json" {
http.Error(w, "Only 'application/json' content type is supported", http.StatusUnsupportedMediaType)
return
}
func (h *apiHandlers) PostCompose(ctx echo.Context) error {
var request api.ComposeRequest
err := json.NewDecoder(r.Body).Decode(&request)
err := ctx.Bind(&request)
if err != nil {
http.Error(w, "Could not parse JSON body", http.StatusBadRequest)
return
return err
}
d := server.distros.GetDistro(request.Distribution)
d := h.server.distros.GetDistro(request.Distribution)
if d == nil {
http.Error(w, fmt.Sprintf("Unsupported distribution: %s", request.Distribution), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unsupported distribution: %s", request.Distribution))
}
kojiServer, err := url.Parse(request.Koji.Server)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid Koji server: %s", request.Koji.Server), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid Koji server: %s", request.Koji.Server))
}
creds, exists := server.kojiServers[kojiServer.Hostname()]
creds, exists := h.server.kojiServers[kojiServer.Hostname()]
if !exists {
http.Error(w, fmt.Sprintf("Koji server has not been configured: %s", kojiServer.Hostname()), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Koji server has not been configured: %s", kojiServer.Hostname()))
}
type imageRequest struct {
@ -94,13 +99,11 @@ func (server *Server) PostCompose(w http.ResponseWriter, r *http.Request) {
for i, ir := range request.ImageRequests {
arch, err := d.GetArch(ir.Architecture)
if err != nil {
http.Error(w, fmt.Sprintf("Unsupported architecture '%s' for distribution '%s'", ir.Architecture, request.Distribution), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unsupported architecture '%s' for distribution '%s'", ir.Architecture, request.Distribution))
}
imageType, err := arch.GetImageType(ir.ImageType)
if err != nil {
http.Error(w, fmt.Sprintf("Unsupported image type '%s' for %s/%s", ir.ImageType, ir.Architecture, request.Distribution), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unsupported image type '%s' for %s/%s", ir.ImageType, ir.Architecture, request.Distribution))
}
repositories := make([]rpmmd.RepoConfig, len(ir.Repositories))
for j, repo := range ir.Repositories {
@ -113,22 +116,19 @@ func (server *Server) PostCompose(w http.ResponseWriter, r *http.Request) {
panic("Could not initialize empty blueprint.")
}
packageSpecs, _ := imageType.Packages(*bp)
packages, _, err := server.rpmMetadata.Depsolve(packageSpecs, nil, repositories, d.ModulePlatformID(), arch.Name())
packages, _, err := h.server.rpmMetadata.Depsolve(packageSpecs, nil, repositories, d.ModulePlatformID(), arch.Name())
if err != nil {
http.Error(w, fmt.Sprintf("Failed to depsolve base base packages for %s/%s/%s: %s", ir.ImageType, ir.Architecture, request.Distribution, err), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to depsolve base base packages for %s/%s/%s: %s", ir.ImageType, ir.Architecture, request.Distribution, err))
}
buildPackageSpecs := imageType.BuildPackages()
buildPackages, _, err := server.rpmMetadata.Depsolve(buildPackageSpecs, nil, repositories, d.ModulePlatformID(), arch.Name())
buildPackages, _, err := h.server.rpmMetadata.Depsolve(buildPackageSpecs, nil, repositories, d.ModulePlatformID(), arch.Name())
if err != nil {
http.Error(w, fmt.Sprintf("Failed to depsolve build packages for %s/%s/%s: %s", ir.ImageType, ir.Architecture, request.Distribution, err), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to depsolve build packages for %s/%s/%s: %s", ir.ImageType, ir.Architecture, request.Distribution, err))
}
manifest, err := imageType.Manifest(nil, distro.ImageOptions{Size: imageType.Size(0)}, repositories, packages, buildPackages)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to get manifest for for %s/%s/%s: %s", ir.ImageType, ir.Architecture, request.Distribution, err), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("Failed to get manifest for for %s/%s/%s: %s", ir.ImageType, ir.Architecture, request.Distribution, err))
}
imageRequests[i].manifest = manifest
@ -140,8 +140,7 @@ func (server *Server) PostCompose(w http.ResponseWriter, r *http.Request) {
// NOTE: the store currently does not support multi-image composes
ir = imageRequests[0]
} else {
http.Error(w, "Only single-image composes are currently supported", http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, "Only single-image composes are currently supported")
}
// Koji for some reason needs TLS renegotiation enabled.
@ -153,8 +152,7 @@ func (server *Server) PostCompose(w http.ResponseWriter, r *http.Request) {
k, err := koji.NewFromGSSAPI(request.Koji.Server, &creds, transport)
if err != nil {
http.Error(w, fmt.Sprintf("Could not log into Koji: %v", err), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Could not log into Koji: %v", err))
}
defer func() {
@ -166,11 +164,10 @@ func (server *Server) PostCompose(w http.ResponseWriter, r *http.Request) {
buildInfo, err := k.CGInitBuild(request.Name, request.Version, request.Release)
if err != nil {
http.Error(w, fmt.Sprintf("Could not initialize build with koji: %v", err), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Could not initialize build with koji: %v", err))
}
id, err := server.workers.Enqueue(ir.manifest, []*target.Target{
id, err := h.server.workers.Enqueue(ir.manifest, []*target.Target{
target.NewKojiTarget(&target.KojiTargetOptions{
BuildID: uint64(buildInfo.BuildID),
TaskID: uint64(request.Koji.TaskId),
@ -188,15 +185,10 @@ func (server *Server) PostCompose(w http.ResponseWriter, r *http.Request) {
panic(err)
}
var response api.ComposeResponse
response.Id = id.String()
response.KojiBuildId = buildInfo.BuildID
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusCreated)
err = json.NewEncoder(w).Encode(response)
if err != nil {
panic("Failed to write response")
}
return ctx.JSON(http.StatusCreated, &api.ComposeResponse{
Id: id.String(),
KojiBuildId: buildInfo.BuildID,
})
}
func composeStateToStatus(state common.ComposeState) string {
@ -230,17 +222,15 @@ func composeStateToImageStatus(state common.ComposeState) string {
}
// GetComposeId handles a /compose/{id} GET request
func (server *Server) GetComposeId(w http.ResponseWriter, r *http.Request, id string) {
parsedID, err := uuid.Parse(id)
func (h *apiHandlers) GetComposeId(ctx echo.Context, idstr string) error {
id, err := uuid.Parse(idstr)
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))
}
status, err := server.workers.JobStatus(parsedID)
status, err := h.server.workers.JobStatus(id)
if err != nil {
http.Error(w, fmt.Sprintf("Job %s not found: %s", id, err), http.StatusBadRequest)
return
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Job %s not found: %s", idstr, err))
}
response := api.ComposeStatus{
@ -251,9 +241,26 @@ func (server *Server) GetComposeId(w http.ResponseWriter, r *http.Request, id st
},
},
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
err = json.NewEncoder(w).Encode(response)
if err != nil {
panic("Failed to write response")
}
return ctx.JSON(http.StatusOK, response)
}
// A simple echo.Binder(), which only accepts application/json, but is more
// strict than echo's DefaultBinder. It does not handle binding query
// parameters either.
type binder struct{}
func (b binder) Bind(i interface{}, ctx echo.Context) error {
request := ctx.Request()
contentType := request.Header["Content-Type"]
if len(contentType) != 1 || contentType[0] != "application/json" {
return echo.NewHTTPError(http.StatusUnsupportedMediaType, "request must be json-encoded")
}
err := json.NewDecoder(request.Body).Decode(i)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("cannot parse request body: %v", err))
}
return nil
}