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

Proposal: ResponseCode #84

Closed Karitham closed 2 years ago

Karitham commented 2 years ago

Context

For methods such as DELETE, PATCH, PUT and POST, we are often met with the need of just returning a response code.

Having a helper method landing after #80 (returning a *Response) directly means that we are obliged to either return something like

(we will go with openapi as the generated package name)

var r openapi.Response
r.Status(http.StatusNoContent)
return &r

Or to write the status code directly, similarly to this code @diamondburned refactored.

w.WriteHeader(http.StatusNoContent)
return nil

Proposal

Generating a function to help with this

func ResponseCode(code int) *Response {
    return &Response{
        statusCode: code,
    }
}

Which would turn this situation into

return openapi.ResponseCode(http.StatusNoContent)

I think this would make every single return meaningful, such that developers could identify code paths that actually respond to the request simpler, rather than having them search for status code being set, or not, earlier.

diamondburned commented 2 years ago

I think alternatively, we can just export field inside *Response so the user can do return &oapi.Response{StatusCode: http.StatusNoContent}.

Ideally, though, the schema should describe the status code, and the generator should generate something like

func DeletePetJSON204Response() *Response {
    return &Response{statusCode: 204}
}
Karitham commented 2 years ago

I guess exporting responseCode is fine, especially since it's unlikely to really change much later on, and isn't exactly subject to breaking change.