/
ghttp_response.go
166 lines (149 loc) · 4.58 KB
/
ghttp_response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// 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.
//
package ghttp
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/gogf/gf/v2/net/ghttp/internal/response"
"github.com/gogf/gf/v2/net/gtrace"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gres"
)
// Response is the http response manager.
// Note that it implements the http.ResponseWriter interface with buffering feature.
type Response struct {
*ResponseWriter // Underlying ResponseWriter.
Server *Server // Parent server.
Writer *ResponseWriter // Alias of ResponseWriter.
Request *Request // According request.
}
// newResponse creates and returns a new Response object.
func newResponse(s *Server, w http.ResponseWriter) *Response {
r := &Response{
Server: s,
ResponseWriter: &ResponseWriter{
writer: response.NewWriter(w),
buffer: bytes.NewBuffer(nil),
},
}
r.Writer = r.ResponseWriter
return r
}
// ServeFile serves the file to the response.
func (r *Response) ServeFile(path string, allowIndex ...bool) {
var (
serveFile *staticFile
)
if file := gres.Get(path); file != nil {
serveFile = &staticFile{
File: file,
IsDir: file.FileInfo().IsDir(),
}
} else {
path, _ = gfile.Search(path)
if path == "" {
r.WriteStatus(http.StatusNotFound)
return
}
serveFile = &staticFile{Path: path}
}
r.Server.serveFile(r.Request, serveFile, allowIndex...)
}
// ServeFileDownload serves file downloading to the response.
func (r *Response) ServeFileDownload(path string, name ...string) {
var (
serveFile *staticFile
downloadName = ""
)
if len(name) > 0 {
downloadName = name[0]
}
if file := gres.Get(path); file != nil {
serveFile = &staticFile{
File: file,
IsDir: file.FileInfo().IsDir(),
}
if downloadName == "" {
downloadName = gfile.Basename(file.Name())
}
} else {
path, _ = gfile.Search(path)
if path == "" {
r.WriteStatus(http.StatusNotFound)
return
}
serveFile = &staticFile{Path: path}
if downloadName == "" {
downloadName = gfile.Basename(path)
}
}
r.Header().Set("Content-Type", "application/force-download")
r.Header().Set("Accept-Ranges", "bytes")
r.Header().Set("Content-Disposition", fmt.Sprintf(`attachment;filename=%s`, url.QueryEscape(downloadName)))
r.Server.serveFile(r.Request, serveFile)
}
// RedirectTo redirects the client to another location.
// The optional parameter `code` specifies the http status code for redirecting,
// which commonly can be 301 or 302. It's 302 in default.
func (r *Response) RedirectTo(location string, code ...int) {
r.Header().Set("Location", location)
if len(code) > 0 {
r.WriteHeader(code[0])
} else {
r.WriteHeader(http.StatusFound)
}
r.Request.Exit()
}
// RedirectBack redirects the client back to referer.
// The optional parameter `code` specifies the http status code for redirecting,
// which commonly can be 301 or 302. It's 302 in default.
func (r *Response) RedirectBack(code ...int) {
r.RedirectTo(r.Request.GetReferer(), code...)
}
// Buffer returns the buffered content as []byte.
func (r *Response) Buffer() []byte {
return r.buffer.Bytes()
}
// BufferString returns the buffered content as string.
func (r *Response) BufferString() string {
return r.buffer.String()
}
// BufferLength returns the length of the buffered content.
func (r *Response) BufferLength() int {
return r.buffer.Len()
}
// SetBuffer overwrites the buffer with `data`.
func (r *Response) SetBuffer(data []byte) {
r.buffer.Reset()
r.buffer.Write(data)
}
// ClearBuffer clears the response buffer.
func (r *Response) ClearBuffer() {
r.buffer.Reset()
}
// ServeContent replies to the request using the content in the
// provided ReadSeeker. The main benefit of ServeContent over io.Copy
// is that it handles Range requests properly, sets the MIME type, and
// handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
// and If-Range requests.
//
// See http.ServeContent
func (r *Response) ServeContent(name string, modTime time.Time, content io.ReadSeeker) {
http.ServeContent(r.Writer.RawWriter(), r.Request.Request, name, modTime, content)
}
// Flush outputs the buffer content to the client and clears the buffer.
func (r *Response) Flush() {
r.Header().Set(responseHeaderTraceID, gtrace.GetTraceID(r.Request.Context()))
if r.Server.config.ServerAgent != "" {
r.Header().Set("Server", r.Server.config.ServerAgent)
}
r.Writer.Flush()
}