Introduction

The Response output employs buffer control, where the output content is pre-written to a buffer and only truly outputted to the client after the service method execution is completed. This feature not only improves execution efficiency but also provides greater flexibility in controlling output content.

Relevant methods:

  1. func (r *Response) Buffer() []byte
  2. func (r *Response) BufferLength() int
  3. func (r *Response) BufferString() string
  4. func (r *Response) Flush()
  5. func (r *Response) SetBuffer(data []byte)

Usage Example

We handle the returned data uniformly through a post middleware. If a service method generates an exception, sensitive error information should not be pushed to the client; instead, a standard error message should be set.

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. "net/http"
  6. )
  7. func MiddlewareErrorHandler(r *ghttp.Request) {
  8. r.Middleware.Next()
  9. if r.Response.Status >= http.StatusInternalServerError {
  10. r.Response.ClearBuffer()
  11. r.Response.Writeln("The server is currently experiencing issues, please try again later!")
  12. }
  13. }
  14. func main() {
  15. s := g.Server()
  16. s.Group("/api.v2", func(group *ghttp.RouterGroup) {
  17. group.Middleware(MiddlewareErrorHandler)
  18. group.ALL("/user/list", func(r *ghttp.Request) {
  19. panic("db error: sql is xxxxxxx")
  20. })
  21. })
  22. s.SetPort(8199)
  23. s.Run()
  24. }

Visiting http://127.0.0.1:8199/api.v2/user/list, you will see the page outputs:

  1. The server is currently experiencing issues, please try again later!