请求输出

数据输出对象定义如下:

  1. // 服务端请求返回对象。
  2. // 注意该对象并没有实现http.ResponseWriter接口,而是依靠ghttp.ResponseWriter实现。
  3. type Response struct {
  4. ResponseWriter
  5. length int // 请求返回的内容长度(byte)
  6. Server *Server // 所属Web Server
  7. Writer *ResponseWriter // ResponseWriter的别名
  8. request *Request // 关联的Request请求对象
  9. }

可以看到ghttp.Response对象继承了标准库的http.ResponseWriter对象,因此完全可以使用标准库的方法来进行输出控制。

当然,建议使用ghttp.Response封装的方法来控制输出,ghttp.Response的数据输出使用Write*相关方法实现,并且数据输出采用了Buffer机制,数据的处理效率比较高,任何时候可以通过OutputBuffer方法输出缓冲区数据到客户端,并清空缓冲区数据。

相关方法(API详见: godoc.org/github.com/johng-cn/gf/g/net/ghttp#Response):

  1. func (r *Response) Buffer() []byte
  2. func (r *Response) BufferLength() int
  3. func (r *Response) ClearBuffer()
  4. func (r *Response) ContentSize() int
  5. func (r *Response) OutputBuffer()
  6. func (r *Response) SetBuffer(buffer []byte)
  7. func (r *Response) RedirectBack()
  8. func (r *Response) RedirectTo(location string)
  9. func (r *Response) ServeFile(path string)
  10. func (r *Response) SetAllowCrossDomainRequest(allowOrigin string, allowMethods string, maxAge ...int)
  11. func (r *Response) Write(content ...interface{})
  12. func (r *Response) Writef(format string, params ...interface{})
  13. func (r *Response) Writefln(format string, params ...interface{})
  14. func (r *Response) Writeln(content ...interface{})
  15. func (r *Response) WriteXml(content interface{}, rootTag ...string) error
  16. func (r *Response) WriteJson(content interface{}) error
  17. func (r *Response) WriteJsonP(content interface{}) error
  18. func (r *Response) WriteStatus(status int, content ...string)
  19. func (r *Response) WriteTpl(tpl string, params map[string]interface{}, funcmap ...map[string]interface{}) error
  20. func (r *Response) WriteTplContent(content string, params map[string]interface{}, funcmap ...map[string]interface{}) error
  21. func (r *Response) ParseTpl(tpl string, params map[string]interface{}, funcmap ...map[string]interface{}) ([]byte, error)
  22. func (r *Response) ParseTplContent(content string, params map[string]interface{}, funcmap ...map[string]interface{}) ([]byte, error)

此外,需要提一下,Header的操作可以通过标准库的方法来实现,例如:

  1. r.Header().Set("Content-Type", "text/plain; charset=utf-8")