Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to handle non-JSON responses based on Handler? #18

Open
xeoncross opened this issue Feb 4, 2018 · 2 comments
Open

How to handle non-JSON responses based on Handler? #18

xeoncross opened this issue Feb 4, 2018 · 2 comments

Comments

@xeoncross
Copy link

xeoncross commented Feb 4, 2018

For some of my http.Handlers I would like to have validation (or other errors) sent back inside a html/template (instead of simply output as JSON).

The Context struct is passed to the error handler.

var defaultErrorHandler = func(err error, c *gongular.Context) {`

My first thought was to figure out how to use the Context as a middleman so that I could look for a flag set by the controller/handler. Then I could write an ErrorHandler that would return JSON or another format depending on if a flag was set. However, c *gongular.Context does not seem to provide such a flagging mechanism.

What is the correct way to support outputs other than JSON? Is there a way for a middleware to handle this?

Update: it looks like a middleware can call .StopChain() to avoid the ErrorHandler. However, you can't seem to access other handlers/middlewares from a middleware.

type multiParam struct {
	Param struct {
		UserID string
		Page   int
	}
}

func (m *multiParam) Handle(c *gongular.Context) error {
	fmt.Println("multiparam")
	c.SetBody(fmt.Sprintf("%s:%d", m.Param.UserID, m.Param.Page))
	return nil
}

// The middleware to intercept validation errors
type middlewareHandler struct {}

func (m *middlewareHandler) Handle(c *gongular.Context) error {
	fmt.Println("middleware")
	return nil
}

func main() {
	e := newEngineTest()
	g := e.GetRouter().Group("/user/:UserID/page", &middlewareHandler{})
	g.GET("/:Page", &multiParam{})
}
@xeoncross xeoncross changed the title How to handle altering ErrorHandler based on Handler? How to handle non-JSON responses based on Handler? Feb 4, 2018
@mustafaakin
Copy link
Owner

Exposing a regular context.Context through gongular.Context might be a good idea, what do you think?

@xeoncross
Copy link
Author

Yes, that is one solution. context.Context would provide even more features than simply a shared request param map attached to gongular.Context.

Either would provide a way for downstream middleware to be notified of something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants