Skip to content

Commit

Permalink
✨ feat: znet support custom renderer
Browse files Browse the repository at this point in the history
  • Loading branch information
sohaha committed Nov 15, 2024
1 parent 9194c7e commit 22c6f74
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 3 deletions.
2 changes: 2 additions & 0 deletions znet/inject.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ func invokeHandler(c *Context, v []reflect.Value) (err error) {
c.render = &renderString{Format: vv}
case error:
err = vv
case Renderer:
c.render = vv
case []byte:
c.render = &renderByte{Data: vv}
case ApiData:
Expand Down
31 changes: 31 additions & 0 deletions znet/inject_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,37 @@ func TestInjectMiddleware(t *testing.T) {
tt.Equal("middleware", w.Body.String())
}

type customRenderer struct {
Text string
Err error
}

func (c *customRenderer) Content(ctx *Context) (content []byte) {
if c.Err != nil {
ctx.SetStatus(500)
return []byte(c.Err.Error())
}
ctx.SetStatus(200)
return []byte(c.Text)
}

func TestCustomRenderer(t *testing.T) {
tt := zlsgo.NewTest(t)
r := newServer()

w := newRequest(r, "GET", "/TestCustomRenderer", "/TestCustomRenderer", func(c *Context) *customRenderer {
return &customRenderer{Text: "test custom renderer"}
})
tt.Equal(200, w.Code)
tt.Equal("test custom renderer", w.Body.String())

w = newRequest(r, "GET", "/TestCustomRendererError", "/TestCustomRendererError", func(c *Context) *customRenderer {
return &customRenderer{Err: errors.New("test custom renderer error")}
})
tt.Equal(500, w.Code)
tt.Equal("test custom renderer error", w.Body.String())
}

func BenchmarkInjectNo(b *testing.B) {
r := newServer()
path := "/BenchmarkInjectNo"
Expand Down
4 changes: 2 additions & 2 deletions znet/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
)

type (
render interface {
Renderer interface {
Content(c *Context) (content []byte)
}
renderByte struct {
Expand Down Expand Up @@ -71,7 +71,7 @@ var (
ContentTypeJSON = "application/json; charset=utf-8"
)

func (c *Context) renderProcessing(code int32, r render) {
func (c *Context) renderProcessing(code int32, r Renderer) {
// if c.stopHandle.Load() && c.prevData.Code.Load() != 0 {
// return
// }
Expand Down
2 changes: 1 addition & 1 deletion znet/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ type (
// Context context
Context struct {
startTime time.Time
render render
render Renderer
Writer http.ResponseWriter
injector zdi.Injector
stopHandle *zutil.Bool
Expand Down

0 comments on commit 22c6f74

Please sign in to comment.