DEV Community

Tutorial: Developing a RESTful API with Go, JSON Schema validation and OpenAPI docs

Viacheslav Poturaev on February 08, 2022

This tutorial continues Developing a RESTful API with Go and Gin featured in Go documentation. Please check it first. TL;DR We're going to replace...
Collapse
 
servernoj profile image
servernoj

Is it possible to return a JSON object for error? For example, on the client side, we need to differentiate various kinds of 400(bad request errors), but we don't want to parse the returned string. So we created a simple struct type

type ErrorResponse struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
}
Enter fullscreen mode Exit fullscreen mode

which, in the case of Gin, would be returned by using c.JSON(HTTP.StatusBadRequest, errorResponse). I cannot wrap my head completely into using usecase interactions, so that's the only thing that stops me to migrate away from using Gin (which I don't like for their approach to validation)

Thanks

PS: Great tutorial

Collapse
 
vearutop profile image
Viacheslav Poturaev

This can be done on a handler processor level, with MakeErrResp configuration.

Please check an example:

github.com/swaggest/rest/blob/v0.2...

    r := openapi31.NewReflector()
    s := web.NewService(r)
.........
    s.Wrap(
        // Example middleware to set up custom error responses and disable response validation for particular handlers.
        func(handler http.Handler) http.Handler {
            var h *nethttp.Handler
            if nethttp.HandlerAs(handler, &h) {
                h.MakeErrResp = func(ctx context.Context, err error) (int, interface{}) {
                    code, er := rest.Err(err)

                    var ae anotherErr

                    if errors.As(err, &ae) {
                        return http.StatusBadRequest, ae
                    }

                    return code, customErr{
                        Message: er.ErrorText,
                        Details: er.Context,
                    }
                }
            }

            return handler
        },
Enter fullscreen mode Exit fullscreen mode

Probably it would be good to have a special interface that could be implemented on a custom error instance to simplify the configuration. 🤔

Collapse
 
servernoj profile image
servernoj

Thank you for your reply. I saw this example and even (before seeing it) came up with a solution to add a handler (for error logic response generation) as an extra argument to service.Post(). But after doing all that, I started thinking of this problem in terms of supporting multiple kinds of 400 (and other) errors such that my implemented "use cases" would embed all needed details into the returned error.

In this case, the responsibility of the service-wise wrapper would be to identify if the error is of a special kind, and if so, then return the aforementioned struct with 2 fields directly taken from the prepared error object

I think this behavior partially matches the implemented one, but I need to update it to exactly meet the expectation, and here is my main issue:

I find it challenging that the need to build a custom logic requires extensively studying the internals of the library implementation. Not only the examples but the sense of how these examples work. The http.Handler and nethttp.Handler are often confused after a brief look through the sources and require a few extra moments to adjust the thinking.

Lastly, the tight incorporation of the chi router into the implementation in the sense that many internal structs have chi structs embedded, leaves no option but to get rid of the currently used router (gin in my case) and adopt chi instead. I have no objection to using chi, but the lack of flexibility in the early phase of the library adoption doesn't make it an easy walk.

Thread Thread
 
vearutop profile image
Viacheslav Poturaev

Interesting, now I'm a bit puzzled about your current setup. Could you make a small example app that matches your current approach (with a "misbehaving" error structure)?

The library is built around chi, because router is an essential part of a web application. But I'd be happy to make it easier to use with other cases. As far as I understood, you use gin with response encoder from swaggest/rest. There is an example of integration with gin, but it only focuses on documentation, leaving request decoding and response writing to gin's standard facilities.

Thread Thread
 
servernoj profile image
servernoj

We first define a bunch of constants like this

const (
    Err404_UnknownError ErrorCode = Err404_Shift + iota + 1
    Err404_ChatGroupNotFound
    Err404_ChannelNotFound
)
Enter fullscreen mode Exit fullscreen mode

to address various scenarios of 404 (and other kinds of) errors. Each constant is of type ErrorCode int (used to generate separate documentation for all errors as illustrated in app.poc.quible.tech/api/v1/docs/er... to be used by the client). The big goal is to introduce "numbers" instead of "strings" for the client to identify the error reason.

We then define a map to associate numerical codes and short descriptions (as shown in the page above) and use that map when a certain gin handler needs to respond with a specific error. For example, SendError(c, http.StatusBadRequest, Err400_InvalidRequestBody)

I am looking for a plug&play replacement of SendError that can be fed with const like Err400_InvalidRequestBody to produce an error returned from the usecase, such that, that error would be handled elsewhere to result in responding with JSON objects

type ErrorResponse struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
}
Enter fullscreen mode Exit fullscreen mode

to clients, given that code and message are those, linked in the error map.

Collapse
 
tonyhsuclrous profile image
Tepisu Cloroc

Great work!
One of a kind.

Collapse
 
reyesdiego profile image
Diego Reyes

I don't want to abuse, you helped me the past week. I need to set a cookie in a NewIterator implementation, but I don't get how to use the responseWriter to do

http.setCookie(w, cookie)

Could you please tell me some tips.

u := usecase.NewIOI(models.LoginInput{}, models.LoginOutput{}, func(ctx context.Context, input, output interface{}) error {
        in := input.(models.LoginInput)
        out := output.(*models.LoginOutput)

    cookie := http.Cookie{Domain: "http://local.io:4321", Name: "token", Value: token, Path: "/", Expires: time.Now().Add(1 * time.Hour), MaxAge: 86400}

 http.SetCookie(w, cookie)
 // I don't know from where I get the w

        *out = models.LoginOutput{
            Token: cookie.Value,
        }
        return err
    })
Enter fullscreen mode Exit fullscreen mode
Collapse
 
reyesdiego profile image
Diego Reyes

Ok.. I've done this solution, but I don't get proper documentation on swagger using .mount :(
By the way, as much I use your your repo I could say it is very very complete...

service.Mount("/login", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        var loginInput models.LoginInput

        err := json.NewDecoder(r.Body).Decode(&loginInput)

        cookie, err := auth.SetCookie(loginInput)
        if err != nil {
            fmt.Println(err)
        }
        http.SetCookie(w, &cookie)
    }))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
reyesdiego profile image
Diego Reyes • Edited

Very nice work!!.. I would like to be able to return (when paginating) an array in the response body and the total count of the query in a header response X-Total-Count.
But If I set a struct for the response like for instance
// Declare output port type.
type helloOutput struct {
TotalCount int64 header:"X-Total-Count" json:"-"
Data []Vehicles json:"vehicles"
}
I need the response to be
[{
vehicle:1
},{
vehicle:2}
]
and NOT
{
data: [{
vehicle:1
},{
vehicle:2}
]
}

Is there any suggestion to make it possible with the usecase callback function?

Collapse
 
vearutop profile image
Viacheslav Poturaev
Collapse
 
alexkapustin profile image
Oleksandr

Well done! Nice and clean! :)
I would recommend to support openapi.yaml as well.

Collapse
 
vearutop profile image
Viacheslav Poturaev

Thank you!

Serving openapi.yaml is relatively simple, you just need to marshal spec as YAML and attach http handler to service.

    service.Method(http.MethodGet, "/docs/openapi.yaml", http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
        document, err := service.OpenAPICollector.Reflector().Spec.MarshalYAML()
        if err != nil {
            http.Error(rw, err.Error(), http.StatusInternalServerError)
        }

        rw.Header().Set("Content-Type", "text/yaml; charset=utf8")

        _, err = rw.Write(document)
        if err != nil {
            http.Error(rw, err.Error(), http.StatusInternalServerError)
        }
    }))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bethmage profile image
bethmage • Edited

Very Nice, I have done this solution and Works. Thank you.