HTTP Server的数据返回通过ghttp.Response对象实现,ghttp.Response对象实现了标准库的http.ResponseWriter接口。数据输出使用Write*相关方法实现,并且数据输出采用了Buffer机制,因此数据的处理效率比较高。任何时候可以通过OutputBuffer方法输出缓冲区数据到客户端,并清空缓冲区数据。

常用方法:更详细的接口列表请参考 https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#Response

func (r *Response) Write(content ...interface{})
func (r *Response) WriteExit(content ...interface{})
func (r *Response) WriteJson(content interface{}) error
func (r *Response) WriteJsonExit(content interface{}) error
func (r *Response) WriteJsonP(content interface{}) error
func (r *Response) WriteJsonPExit(content interface{}) error
func (r *Response) WriteOver(content ...interface{})
func (r *Response) WriteOverExit(content ...interface{})
func (r *Response) WriteStatus(status int, content ...interface{})
func (r *Response) WriteStatusExit(status int, content ...interface{})
func (r *Response) WriteTpl(tpl string, params ...gview.Params) error
func (r *Response) WriteTplContent(content string, params ...gview.Params) error
func (r *Response) WriteTplDefault(params ...gview.Params) error
func (r *Response) WriteXml(content interface{}, rootTag ...string) error
func (r *Response) WriteXmlExit(content interface{}, rootTag ...string) error
func (r *Response) Writef(format string, params ...interface{})
func (r *Response) WritefExit(format string, params ...interface{})
func (r *Response) Writefln(format string, params ...interface{})
func (r *Response) WriteflnExit(format string, params ...interface{})
func (r *Response) Writeln(content ...interface{})
func (r *Response) WritelnExit(content ...interface{})

简要说明:

  1. Write*方法用于往返回的数据缓冲区追加写入数据,参数可为任意的数据格式,内部通过断言对参数做自动分析。
  2. Write*Exit方法用于往返回的数据缓冲区追加写入数据后退出当前执行的HTTP Handler方法,可用于替代return返回方法。
  3. WriteOver*方法用于覆盖缓冲区写入,原有缓冲区的数据将会被覆盖为新写入的数据。
  4. WriteStatus*方法用于设置当前请求执行返回的状态码。
  5. WriteJson*/WriteXml方法用于特定数据格式的输出,这是为开发者提供的简便方法。
  6. WriteTpl*方法用于模板输出,解析并输出模板文件,也可以直接解析并输出给定的模板内容。
  7. 其他方法详见接口文档;

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

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


继续了解: