responder

用于将Body转换为对应的字节数据,并设置响应头。默认的处理为将struct(map)转换为json,对于不同的应用可以指定Marshal与ContentType来实现自定义响应。

  • ResponderConfig.Marshal 自定义的Marshal函数,默认为json.Marshal
  • ResponderConfig.ContentType 自定义的ContentType,默认为application/json; charset=utf-8

Example

  1. package main
  2. import (
  3. "github.com/vicanso/elton"
  4. "github.com/vicanso/elton/middleware"
  5. )
  6. func main() {
  7. e := elton.New()
  8. e.Use(middleware.NewDefaultResponder())
  9. // {"name":"tree.xie","id":123}
  10. e.GET("/", func(c *elton.Context) (err error) {
  11. c.Body = &struct {
  12. Name string `json:"name"`
  13. ID int `json:"id"`
  14. }{
  15. "tree.xie",
  16. 123,
  17. }
  18. return
  19. })
  20. err := e.ListenAndServe(":3000")
  21. if err != nil {
  22. panic(err)
  23. }
  24. }