gf/g/net/ghttp/ghttp_response.go

230 lines
6.5 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
2017-12-29 16:03:30 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2017-12-29 16:03:30 +08:00
//
2017-12-31 18:19:58 +08:00
2017-12-07 14:57:16 +08:00
package ghttp
import (
2018-11-17 11:17:02 +08:00
"bytes"
"fmt"
"github.com/gogf/gf/g/encoding/gparser"
"github.com/gogf/gf/g/os/gfile"
"github.com/gogf/gf/g/util/gconv"
"net/http"
"strconv"
2017-12-07 14:57:16 +08:00
)
2018-08-21 21:18:56 +08:00
// 服务端请求返回对象。
// 注意该对象并没有实现http.ResponseWriter接口而是依靠ghttp.ResponseWriter实现。
2018-01-02 16:35:13 +08:00
type Response struct {
2018-04-20 15:43:02 +08:00
ResponseWriter
Server *Server // 所属Web Server
2018-08-21 21:18:56 +08:00
Writer *ResponseWriter // ResponseWriter的别名
request *Request // 关联的Request请求对象
2018-04-20 15:43:02 +08:00
}
// 创建一个ghttp.Response对象指针
func newResponse(s *Server, w http.ResponseWriter) *Response {
r := &Response {
Server : s,
2018-11-16 18:20:09 +08:00
ResponseWriter : ResponseWriter {
2018-08-21 21:18:56 +08:00
ResponseWriter : w,
2018-11-17 11:17:02 +08:00
buffer : bytes.NewBuffer(nil),
2018-08-21 21:18:56 +08:00
},
}
r.Writer = &r.ResponseWriter
return r
}
// 返回信息任何变量自动转换为bytes
func (r *Response) Write(content ... interface{}) {
if len(content) == 0 {
return
}
for _, v := range content {
switch v.(type) {
case []byte:
// 如果是二进制数据,那么返回二进制数据
2018-11-17 11:17:02 +08:00
r.buffer.Write(gconv.Bytes(v))
default:
// 否则一律按照可显示的字符串进行转换
2018-11-17 11:17:02 +08:00
r.buffer.WriteString(gconv.String(v))
}
}
2017-12-07 14:57:16 +08:00
}
// 返回信息支持自定义format格式
func (r *Response) Writef(format string, params ... interface{}) {
r.Write(fmt.Sprintf(format, params...))
}
// 返回信息,末尾增加换行标识符"\n"
func (r *Response) Writeln(content ... interface{}) {
if len(content) == 0 {
r.Write("\n")
return
}
content = append(content, "\n")
r.Write(content...)
}
// 返回信息,末尾增加换行标识符"\n"
func (r *Response) Writefln(format string, params ... interface{}) {
r.Writeln(fmt.Sprintf(format, params...))
}
// 返回JSON
func (r *Response) WriteJson(content interface{}) error {
if b, err := gparser.VarToJson(content); err != nil {
return err
} else {
r.Header().Set("Content-Type", "application/json")
r.Write(b)
}
return nil
2017-12-08 09:50:11 +08:00
}
// 返回JSONP
func (r *Response) WriteJsonP(content interface{}) error {
if b, err := gparser.VarToJson(content); err != nil {
return err
} else {
//r.Header().Set("Content-Type", "application/json")
if callback := r.request.Get("callback"); callback != "" {
buffer := []byte(callback)
buffer = append(buffer, byte('('))
buffer = append(buffer, b...)
buffer = append(buffer, byte(')'))
r.Write(buffer)
} else {
r.Write(b)
}
}
return nil
}
// 返回XML
func (r *Response) WriteXml(content interface{}, rootTag...string) error {
if b, err := gparser.VarToXml(content, rootTag...); err != nil {
return err
} else {
r.Header().Set("Content-Type", "application/xml")
r.Write(b)
}
return nil
}
// Deprecated, please use CORSDefault instead.
//
// (已废弃请使用CORSDefault)允许AJAX跨域访问.
func (r *Response) SetAllowCrossDomainRequest(allowOrigin string, allowMethods string, maxAge...int) {
age := 3628800
if len(maxAge) > 0 {
age = maxAge[0]
}
r.Header().Set("Access-Control-Allow-Origin", allowOrigin)
r.Header().Set("Access-Control-Allow-Methods", allowMethods)
r.Header().Set("Access-Control-Max-Age", strconv.Itoa(age))
}
// 返回HTTP Code状态码
func (r *Response) WriteStatus(status int, content...string) {
2018-11-17 11:17:02 +08:00
if r.buffer.Len() == 0 {
// 状态码注册回调函数处理
if status != http.StatusOK {
if f := r.request.Server.getStatusHandler(status, r.request); f != nil {
f(r.request)
// 防止多次设置(http: multiple response.WriteHeader calls)
if r.Status == 0 {
r.WriteHeader(status)
}
return
}
}
r.Header().Set("Content-Type", "text/plain; charset=utf-8")
r.Header().Set("X-Content-Type-Options", "nosniff")
if len(content) > 0 {
r.Write(content[0])
} else {
r.Write(http.StatusText(status))
}
}
r.WriteHeader(status)
}
2018-08-19 13:48:56 +08:00
// 静态文件处理
func (r *Response) ServeFile(path string) {
2018-11-16 18:20:09 +08:00
// 首先判断是否给定的path已经是一个绝对路径
path = gfile.RealPath(path)
2018-11-16 18:20:09 +08:00
if path == "" {
r.WriteStatus(http.StatusNotFound)
return
}
2018-08-19 13:48:56 +08:00
r.Server.serveFile(r.request, path)
}
2018-11-23 09:20:45 +08:00
// 静态文件下载处理
func (r *Response) ServeFileDownload(path string, name...string) {
// 首先判断是否给定的path已经是一个绝对路径
path = gfile.RealPath(path)
2018-11-23 09:20:45 +08:00
if path == "" {
r.WriteStatus(http.StatusNotFound)
return
}
2018-11-23 16:45:30 +08:00
downloadName := ""
if len(name) > 0 {
downloadName = name[0]
} else {
downloadName = gfile.Basename(path)
}
2018-11-23 09:20:45 +08:00
r.Header().Set("Content-Type", "application/force-download")
r.Header().Set("Accept-Ranges", "bytes")
2018-11-23 16:45:30 +08:00
r.Header().Set("Content-Disposition", fmt.Sprintf(`attachment;filename="%s"`, downloadName))
2018-11-23 09:20:45 +08:00
r.Server.serveFile(r.request, path)
}
// 返回location标识引导客户端跳转
func (r *Response) RedirectTo(location string) {
r.Header().Set("Location", location)
r.WriteHeader(http.StatusFound)
2018-11-28 20:19:28 +08:00
r.request.Exit()
}
2017-12-07 14:57:16 +08:00
// 返回location标识引导客户端跳转到来源页面
func (r *Response) RedirectBack() {
r.RedirectTo(r.request.GetReferer())
}
// 获取当前缓冲区中的数据
2018-01-02 16:35:13 +08:00
func (r *Response) Buffer() []byte {
2018-11-17 11:17:02 +08:00
return r.buffer.Bytes()
2017-12-26 10:13:49 +08:00
}
// 获取当前缓冲区中的数据大小
func (r *Response) BufferLength() int {
2018-11-17 11:17:02 +08:00
return r.buffer.Len()
}
// 手动设置缓冲区内容
2018-11-17 11:17:02 +08:00
func (r *Response) SetBuffer(data []byte) {
r.buffer.Reset()
r.buffer.Write(data)
}
2017-12-28 15:21:25 +08:00
// 清空缓冲区内容
2018-01-02 16:35:13 +08:00
func (r *Response) ClearBuffer() {
2018-11-17 11:17:02 +08:00
r.buffer.Reset()
2017-12-28 15:21:25 +08:00
}
2017-12-13 11:36:29 +08:00
// 输出缓冲区数据到客户端
2018-01-02 16:35:13 +08:00
func (r *Response) OutputBuffer() {
r.Header().Set("Server", r.Server.config.ServerAgent)
2018-08-22 19:56:01 +08:00
//r.handleGzip()
2018-08-21 21:18:56 +08:00
r.Writer.OutputBuffer()
2017-12-13 11:36:29 +08:00
}