go-mojito / mojito

Code your next Go web project with (a) Mojito! Mojito is a super-modular, fast, opinion-less framework to bootstrap your next Go web project.
https://go-mojito.infinytum.co
MIT License
24 stars 0 forks source link

[Enhancement]: Set the HTTP Status Code with context functions #33

Closed lennard-brinkhaus closed 1 month ago

lennard-brinkhaus commented 1 year ago

Description

It would be great, if you can set status codes with the helper function in the mojito Context. There is often a reason why you don't want to use 200 and it won't look great if ou need to use ctx.Response().WriteHeader(200). An proposal would be this:

ctx.JSON(http.StatusOK, any)

Additional Context

No response

Code Snippet

No response

Checklist:

0SkillAllLuck commented 1 year ago

@nilathedragon Do we want this with a separate method, for example ctx.JSONStatus(http.StatusOK, any) or with a magic method that uses 200 OK as the default? Both would not break backwards compatibility.

0SkillAllLuck commented 1 year ago

@nilathedragon Also we should probably add the variant we choose for every method not only JSON

nilathedragon commented 1 year ago

I always really liked the idea of a ctx.Status(int statusCode) error function. Instead of immediately writing the status code, the final value would be evaluated and written once the last middleware returned. The error is returned in case a stdlib handler/middleware already wrote to the ResponseWriter and we can't set the header anymore.

This way a middleware has the option of overriding the status code after the handler finished. Or set a default one (no idea who would but you could!)

0SkillAllLuck commented 1 year ago

I always really liked the idea of a ctx.Status(int statusCode) error function. Instead of immediately writing the status code, the final value would be evaluated and written once the last middleware returned. The error is returned in case a stdlib handler/middleware already wrote to the ResponseWriter and we can't set the header anymore.

This way a middleware has the option of overriding the status code after the handler finished. Or set a default one (no idea who would but you could!)

I totally agree that ctx.Status(int statusCode) error is the better way, but having ctx.JSON(http.StatusOK, any) might be a good shortcut. So more like an alias for:

ctx.Status(int statusCode)
ctx.JSON(any)
nilathedragon commented 1 year ago

I don't like the idea of making .JSON(...) variadic just to add status code handling. It creates problems and confusion for the user in multiple ways:

Of course you could say JSON only accepts (status, data) and (data) but that's not something one could infer from the method definition.

It also adds redundancy with .Status() which isn't great.

nilathedragon commented 1 month ago

Gonna go ahead and implement a generic .Status(int statusCode) on mojito.Context