Skip to content

🔥 Support returning response from handler #218

@alinnert

Description

@alinnert

Is your feature request related to a problem?

It's a very common pattern while building an API to call a function, check the err and send a response to the client. At this point the handler should also end executing. Normally this looks like following:

user, err := getUser()
if err != nil {
  c.JSON(someErrorStruct)
  return
}

For demonstration: in this example this pattern repeats 29 times in ~210 LOC.

The problem is: it's super super easy to forget one of these returns. This leads to hard to detect bugs that can't be caught by the language.

Describe the solution you'd like

One solution would be to make it possible to return results instead of calling a function to send them. Like:

user, err := getUser()
if err != nil {
  return someErrorStruct
}

(plus: this would also reduce the linked example code by 29 LOC)

There are multiple ways to implement this. Some alternatives are:

if err != nil {
  return &fiber.JSONResponse{
    Status: 403,
    Body: someErrorStruct
  }
  // or
  return c.JSONResponse(someErrorStruct, 403)
  // or
  return c.JSONResponse(someErrorStruct).withStatus(403)
}

This feature would be purely additive. It should not be necessary to use this over c.Send() or c.Write(). Therefore it also shouldn't break any existing code.

Describe alternatives you've considered

What I could do is write a wrapper function that calls the real handler, accepts anything the handler returns and takes care of sending the response. But I would need to wrap every single handler (possibly also middleware) with this wrapper. That would look like this:

app.Get('/', wrapper(indexHandler))

I want to avoid that if that's possible.

Additional context

I found a few frameworks that actually support this way of sending a response, for Go and other languages. One example for Go would be Atreugo.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions