Why HandlerFunc function only returns the error interface?


#1

Go noob here, and i have a question:

I’m following a simple tutorial from here:

And i don’t understand something about the return values of HandlerFunc.

The method echo.GET has the signature: func (e *Echo) GET(path string, h HandlerFunc, m …MiddlewareFunc) *Route, which means that it receives as second parameter a HandlerFunc.

My question is why HandlerFunc function only returns an error?

For example here:

e.GET("/htmlResponse", func(c echo.Context) error {
    var resp error = c.HTML(
        http.StatusOK,
        "<h2>TheBestPessimist</h2>")
    return resp
})

the type of resp is go’s builtin error type interface, so c.String, c.HTML, c.JSON, etc. return an error.

As a Java/Kotlin dev i’d expect that at least an interface{} would be returned along with the error, if not a custom struct.

Is my understanding wrong, and actually something else is returned as well? in that case what is that something else, and where is the declaration showing that something else is returned?

If my understanding is correct, then why do you use error as a normal and valid return type? For me this seems really really weird.


Note that i’ve searched around this forum a little and only found this related topic: Echo return function, which doesn’t quite explain it.


#2

Hopefully you got that cleared out by now, but just in case, I’ll take a stab at it: if you look at https://golang.org/pkg/net/http/#HandleFunc (that is, the HandlerFunc from net/http), you’ll see it returns even less, it returns nothing at all :slight_smile:

Echo is a minimalistic framework, and that also means adding as little as possible on top of what we already have. It actually works identical to how the stdlib works with respect to this, and that is: you get access to both request and response in your handler. You read the request and produce the response and that way everything is nicely self contained.

Returning an error should actually be used rarely, only when there are exceptional errors. 4xx, 5xx, that is the errors that are supposed to be returned to end users, must be set appropriately on the response, NOT returned as an error. The error should be used only when the handler func cannot perform its intended function (which is to read a request and prepare a response).

In practice, most often you don’t need to handle the response yourself, but can use the helpers provided, such as c.String(), c.JSON(), etc. based on what you want to output. They will set the appropriate headers (incl. content type, the status code you provide, etc.) and write the response body that you also provide. But under the hood, all they do is write to c.Response() to which you also have access to, that’s how it all works. Just a tiny sprinkle of syntactic sugar :slight_smile:

Hope this helps!
Alex