savsgio/atreugo

Can I unify the style of response in atreugo?

imxxiv opened this issue · 2 comments

In the restful api project, i try to unify the style of response.
If the middlewares or filters return err, actx.Error() will response the body, i can't modify to json response.
I want

HTTP/1.1 401 Unauthorized
Server: atreugo
Date: Tue, 27 Aug 2019 03:38:40 GMT
Content-Type: application/json
Content-Length: 28

{"code":401,"msg":"Unauthorized"}

But middlewares or filters return err, the response is

HTTP/1.1 401 Unauthorized
Server: atreugo
Date: Tue, 27 Aug 2019 03:39:37 GMT
Content-Type: text/plain
Content-Length: 12

Unauthorized

utils.go line 38 ctx.Error(err.Error(), fasthttp.StatusInternalServerError)

func viewToHandler(view View) fasthttp.RequestHandler {
	return func(ctx *fasthttp.RequestCtx) {
		actx := acquireRequestCtx(ctx)

		if err := view(actx); err != nil {
			ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
		}

		releaseRequestCtx(actx)
	}
}

router.go line 99 actx.Error(err.Error(), statusCode)

		if err != nil {
			r.log.Error(err)
			actx.Error(err.Error(), statusCode)
		}

Because actx inherits the method of ctx, so can use the ctx.method, Is the effect the same?

Because actx inherits the method of ctx, so can use the ctx.method, Is the effect the same?

Yes, It's explained on README 😄

And I've just added custom error view in configuration, so you could configure it with something like that:

config := &atreugo.Config{
		...
		ErrorView: func(ctx *atreugo.RequestCtx, err error, statusCode int) {
			ctx.JSONResponse(atreugo.JSON{"code": statusCode, "msg": err.Error()}, statusCode)
		},
                ...
	}