Skip to content

Commit 4166509

Browse files
committed
Support []byte return value from handler
1 parent 013d0f9 commit 4166509

File tree

2 files changed

+19
-10
lines changed

2 files changed

+19
-10
lines changed

web.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -353,25 +353,28 @@ func (s *Server) routeHandler(req *Request, c conn) {
353353

354354
ret, err := s.safelyCall(route.handler, args)
355355
if err != nil {
356-
//fmt.Printf("%v\n", err)
357356
//there was an error or panic while calling the handler
358357
ctx.Abort(500, "Server Error")
359358
}
360-
359+
if ctx.responseStarted {
360+
return
361+
}
361362
if len(ret) == 0 {
362363
return
363364
}
364365

365366
sval := ret[0]
366367

367-
if sval.Kind() == reflect.String &&
368-
!ctx.responseStarted {
369-
content := []byte(sval.String())
370-
ctx.SetHeader("Content-Length", strconv.Itoa(len(content)), true)
371-
ctx.StartResponse(200)
372-
ctx.Write(content)
373-
}
368+
var content []byte
374369

370+
if sval.Kind() == reflect.String {
371+
content = []byte(sval.String())
372+
} else if sval.Kind() == reflect.Slice && sval.Type().Elem().Kind() == reflect.Uint8 {
373+
content = sval.Interface().([]byte)
374+
}
375+
ctx.SetHeader("Content-Length", strconv.Itoa(len(content)), true)
376+
ctx.StartResponse(200)
377+
ctx.Write(content)
375378
return
376379
}
377380

web_test.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ func buildTestResponse(buf *bytes.Buffer) *testResponse {
4646

4747
response := testResponse{headers: make(map[string][]string), cookies: make(map[string]string)}
4848
s := buf.String()
49-
5049
contents := strings.SplitN(s, "\r\n\r\n", 2)
5150

5251
header := contents[0]
@@ -171,6 +170,12 @@ func init() {
171170
return string(data)
172171
})
173172

173+
Get("/jsonbytes", func(ctx *Context) []byte {
174+
ctx.ContentType("json")
175+
data, _ := json.Marshal(ctx.Params)
176+
return data
177+
})
178+
174179
Post("/parsejson", func(ctx *Context) string {
175180
var tmp = struct{ A string; B string }{}
176181
json.NewDecoder(ctx.Request.Body).Decode(&tmp)
@@ -207,6 +212,7 @@ var tests = []Test{
207212
{"GET", "/fullparams?a=1&a=2&a=3", "", 200, "1,2,3"},
208213
{"GET", "/panic", "", 500, "Server Error"},
209214
{"GET", "/json?a=1&b=2", "", 200, `{"a":"1","b":"2"}`},
215+
{"GET", "/jsonbytes?a=1&b=2", "", 200, `{"a":"1","b":"2"}`},
210216
//{"GET", "/methodhandler", "", 200, `a`},
211217
//{"GET", "/methodhandler2?b=b", "", 200, `ab`},
212218
//{"GET", "/methodhandler3/b", "", 200, `ab`},

0 commit comments

Comments
 (0)