• 请求输出
    • 实现允许跨域请求

    请求输出

    数据输出对象定义如下:

    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/gogf/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) ServeFileDownload(path string, name ...string)
    11. func (r *Response) SetAllowCrossDomainRequest(allowOrigin string, allowMethods string, maxAge ...int)
    12. func (r *Response) CORS(options CORSOptions)
    13. func (r *Response) CORSDefault()
    14. func (r *Response) Write(content ...interface{})
    15. func (r *Response) Writef(format string, params ...interface{})
    16. func (r *Response) Writefln(format string, params ...interface{})
    17. func (r *Response) Writeln(content ...interface{})
    18. func (r *Response) WriteXml(content interface{}, rootTag ...string) error
    19. func (r *Response) WriteJson(content interface{}) error
    20. func (r *Response) WriteJsonP(content interface{}) error
    21. func (r *Response) WriteStatus(status int, content ...string)
    22. func (r *Response) WriteTpl(tpl string, params map[string]interface{}, funcmap ...map[string]interface{}) error
    23. func (r *Response) WriteTplContent(content string, params map[string]interface{}, funcmap ...map[string]interface{}) error
    24. func (r *Response) ParseTpl(tpl string, params map[string]interface{}, funcmap ...map[string]interface{}) ([]byte, error)
    25. 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")

    实现允许跨域请求

    我们可以使用CORS或者CORSDefault来实现服务端允许跨域请求。

    SetAllowCrossDomainRequest也是跨域使用的方法,新版本中已废弃。

    1. CORS方法允许开发者自定义跨域请求参数,参数类型为CORSOptions对象;

      CORSOptions定义:

      1. // See https://www.w3.org/TR/cors/ .
      2. // 服务端允许跨域请求选项
      3. type CORSOptions struct {
      4. AllowOrigin string // Access-Control-Allow-Origin
      5. AllowCredentials string // Access-Control-Allow-Credentials
      6. ExposeHeaders string // Access-Control-Expose-Headers
      7. MaxAge int // Access-Control-Max-Age
      8. AllowMethods string // Access-Control-Allow-Methods
      9. AllowHeaders string // Access-Control-Allow-Headers
      10. }
    2. CORSDefault方法使用默认的跨域选项配置来设置跨域,大部分情况下使用该方法即可;

      使用示例:

      1. package main
      2. import (
      3. "github.com/gogf/gf/g"
      4. "github.com/gogf/gf/g/frame/gmvc"
      5. "github.com/gogf/gf/g/net/ghttp"
      6. )
      7. type Order struct {
      8. gmvc.Controller
      9. }
      10. func (o *Order) Get() {
      11. o.Response.Write("GET")
      12. }
      13. func main() {
      14. s := g.Server()
      15. s.BindHookHandlerByMap("/api.v2/*any", map[string]ghttp.HandlerFunc {
      16. "BeforeServe" : func(r *ghttp.Request) {
      17. r.Response.CORSDefault()
      18. },
      19. })
      20. s.BindControllerRest("/api.v2/{.struct}", new(Order))
      21. s.SetPort(8199)
      22. s.Run()
      23. }

      随后随便找个支持jQuery的站点(例如:https://www.baidu.com ),使用F12快捷键打开console窗口,执行以下Javascript指令检测是否跨域请求成功:

      1. $.get("http://localhost:8199/api.v2/order", function(result){
      2. console.log(result)
      3. });

      效果如下: 请求输出 - 图1