Skip to content
This repository has been archived by the owner on Apr 11, 2020. It is now read-only.

Commit

Permalink
refactor: auto detect response type
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Sep 3, 2019
1 parent d6f05ab commit a8a516b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 13 deletions.
12 changes: 3 additions & 9 deletions recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package recover
import (
"fmt"
"net/http"
"strings"

"github.com/vicanso/hes"

Expand All @@ -28,15 +29,8 @@ const (
ErrCategory = "elton-recover"
)

type (
// Config json parser config
Config struct {
ResponseType string
}
)

// New new recover
func New(config Config) elton.Handler {
func New() elton.Handler {
return func(c *elton.Context) error {
defer func() {
// 可针对实际需求调整,如对于每个recover增加邮件通知等
Expand Down Expand Up @@ -64,7 +58,7 @@ func New(config Config) elton.Handler {
c.Committed = true
resp := c.Response
buf := []byte(err.Error())
if config.ResponseType == "json" {
if strings.Contains(c.GetRequestHeader("Accept"), "application/json") {
c.SetHeader(elton.HeaderContentType, elton.MIMEApplicationJSON)
buf = he.ToJSON()
}
Expand Down
7 changes: 3 additions & 4 deletions recover_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func TestRecover(t *testing.T) {
assert := assert.New(t)
var ctx *elton.Context
d := elton.New()
d.Use(New(Config{}))
d.Use(New())
d.GET("/", func(c *elton.Context) error {
ctx = c
panic("abc")
Expand Down Expand Up @@ -51,13 +51,12 @@ func TestRecover(t *testing.T) {
t.Run("response json", func(t *testing.T) {
assert := assert.New(t)
d := elton.New()
d.Use(New(Config{
ResponseType: "json",
}))
d.Use(New())
d.GET("/", func(c *elton.Context) error {
panic("abc")
})
req := httptest.NewRequest("GET", "https://aslant.site/", nil)
req.Header.Set("Accept", "application/json, text/plain, */*")
resp := httptest.NewRecorder()
d.ServeHTTP(resp, req)
assert.Equal(500, resp.Code)
Expand Down

0 comments on commit a8a516b

Please sign in to comment.