discord-gophers / goapi-gen

This package contains a set of utilities for generating Go boilerplate code for services based on OpenAPI 3.0 API definitions
Apache License 2.0
132 stars 12 forks source link

Require handlers to return *Response directly #80

Closed diamondburned closed 2 years ago

diamondburned commented 2 years ago

This commit changes the generated handler methods inside ServerInterface to directly return a *Response value instead of requiring it to call render.Render manually. This results in much cleaner handler code.

While this change breaks all existing code, it is not a significant change by any means, so most changes can be regexed away to work.

As an example, petstore's FindPetByID is now

func (p *PetStore) FindPetByID(w http.ResponseWriter, r *http.Request, id int64) *Response {
    p.Lock.Lock()
    defer p.Lock.Unlock()

    pet, found := p.Pets[id]
    if !found {
        return FindPetByIDJSONDefaultResponse(Error{fmt.Sprintf(petNotFoundMsg, id)}).Status(http.StatusNotFound)
    }

    return FindPetByIDJSON200Response(pet)
}

compared to before

func (p *PetStore) FindPetByID(w http.ResponseWriter, r *http.Request, id int64) {
    p.Lock.Lock()
    defer p.Lock.Unlock()

    pet, found := p.Pets[id]
    if !found {
        render.Render(
            w, r,
            FindPetByIDJSONDefaultResponse(Error{fmt.Sprintf(petNotFoundMsg, id)}).Status(http.StatusNotFound),
        )
        return
    }

    render.Render(w, r, FindPetByIDJSON200Response(pet))
}

Ideally, the above piece of code would look something like

func (p *PetStore) FindPetByID(w http.ResponseWriter, r *http.Request, id int64) *Response {
    p.Lock.Lock()
    defer p.Lock.Unlock()

    pet, found := p.Pets[id]
    if !found {
        return FindPetByIDJSON404Response(Error{fmt.Sprintf(petNotFoundMsg, id)})
    }

    return FindPetByIDJSON200Response(pet)
}

where a FindPetByIDJSON404Response is properly generated by the OpenAPI schema having the 404 status code documented, but it isn't in the example schema for some reason.