-
Notifications
You must be signed in to change notification settings - Fork 6
/
output.go
239 lines (213 loc) · 5.95 KB
/
output.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package hfw
import (
"compress/gzip"
"html/template"
"io"
"os"
"path/filepath"
"sync"
"github.com/hsyan2008/hfw/common"
"github.com/hsyan2008/hfw/configs"
"github.com/hsyan2008/hfw/encoding"
)
//RenderResponse ..
func (httpCtx *HTTPContext) RenderResponse() {
// httpCtx.Debug("RenderResponse")
if httpCtx.hijacked {
return
}
httpCtx.ResponseWriter.Header().Set("Trace-Id", httpCtx.GetTraceID())
if (configs.Config.EnableSession || configs.Config.Session.IsEnable) && httpCtx.Session != nil {
httpCtx.Session.Close(httpCtx.Request, httpCtx.ResponseWriter)
}
if httpCtx.ResponseWriter.Header().Get("Location") != "" {
return
}
if httpCtx.IsCloseRender {
httpCtx.ResponseWriter.WriteHeader(httpCtx.HTTPStatus)
return
}
if httpCtx.IsJSON {
httpCtx.ReturnJSON()
return
} else if httpCtx.TemplateFile != "" || httpCtx.Template != "" {
httpCtx.Render()
return
}
httpCtx.ReturnJSON()
}
//ReturnFileContent 下载文件服务
func (httpCtx *HTTPContext) ReturnFileContent(contentType, filename string, file interface{}) {
httpCtx.IsJSON = false
httpCtx.Template = ""
httpCtx.TemplateFile = ""
var w io.Writer
var r io.Reader
var err error
if !httpCtx.IsError && httpCtx.IsZip {
httpCtx.ResponseWriter.Header().Del("Content-Length")
httpCtx.ResponseWriter.Header().Set("Content-Encoding", "gzip")
w = gzip.NewWriter(httpCtx.ResponseWriter)
defer w.(io.WriteCloser).Close()
} else {
w = httpCtx.ResponseWriter
}
switch t := file.(type) {
case string: //文件路径,http.ServeFile不自动压缩
f, err := filepath.Abs(file.(string))
httpCtx.ThrowCheck(500, err)
if !common.IsExist(f) {
httpCtx.ThrowCheck(500, "file not exist")
}
r, err = os.Open(t)
defer r.(io.Closer).Close()
httpCtx.ThrowCheck(500, err)
case io.Reader: //io流,如果是文件内容,可以通过bytes.Buffer包装下
r = file.(io.Reader)
if f, ok := file.(io.Closer); ok {
defer f.Close()
}
}
httpCtx.ResponseWriter.Header().Set("Content-Type", contentType)
httpCtx.SetDownloadMode(filename)
httpCtx.ResponseWriter.WriteHeader(httpCtx.HTTPStatus)
_, err = io.Copy(w, r)
// httpCtx.ThrowCheck(500, err)
if err != nil {
httpCtx.Warn(err)
}
}
var templatesCache = struct {
list map[string]*template.Template
l *sync.RWMutex
}{
list: make(map[string]*template.Template),
l: &sync.RWMutex{},
}
//Render ..
func (httpCtx *HTTPContext) Render() {
var (
t *template.Template
err error
)
t = httpCtx.render()
if len(httpCtx.ResponseWriter.Header().Get("Content-Type")) == 0 {
httpCtx.ResponseWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
}
var w io.Writer = httpCtx.ResponseWriter
if !httpCtx.IsError && httpCtx.IsZip {
httpCtx.ResponseWriter.Header().Del("Content-Length")
httpCtx.ResponseWriter.Header().Set("Content-Encoding", "gzip")
writer := gzip.NewWriter(httpCtx.ResponseWriter)
defer writer.Close()
w = writer
}
httpCtx.ResponseWriter.WriteHeader(httpCtx.HTTPStatus)
err = t.Execute(w, httpCtx)
// httpCtx.ThrowCheck(500, err)
if err != nil {
httpCtx.Warn(err)
}
}
func (httpCtx *HTTPContext) render() (t *template.Template) {
var key string
var render func() *template.Template
var ok bool
if httpCtx.Template != "" {
key = httpCtx.Path
render = httpCtx.renderHTML
} else if httpCtx.TemplateFile != "" {
key = httpCtx.TemplateFile
render = httpCtx.renderFile
}
if Config.Template.IsCache {
templatesCache.l.RLock()
if t, ok = templatesCache.list[key]; !ok {
templatesCache.l.RUnlock()
// t = httpCtx.render()
t = render()
templatesCache.l.Lock()
templatesCache.list[key] = t
templatesCache.l.Unlock()
} else {
templatesCache.l.RUnlock()
}
} else {
// t = httpCtx.render()
t = render()
}
return t
}
func (httpCtx *HTTPContext) renderHTML() (t *template.Template) {
if len(httpCtx.FuncMap) == 0 {
t = template.Must(template.New(httpCtx.Path).Parse(httpCtx.Template))
} else {
t = template.Must(template.New(httpCtx.Path).Funcs(httpCtx.FuncMap).Parse(httpCtx.Template))
}
if len(Config.Template.WidgetsPath) > 0 {
t = template.Must(t.ParseGlob(Config.Template.WidgetsPath))
}
return
}
func (httpCtx *HTTPContext) renderFile() (t *template.Template) {
var templateFilePath string
if common.IsExist(httpCtx.TemplateFile) {
templateFilePath = httpCtx.TemplateFile
} else {
templateFilePath = filepath.Join(Config.Template.HTMLPath, httpCtx.TemplateFile)
}
if !common.IsExist(templateFilePath) {
httpCtx.ThrowCheck(500, "template path not exist")
}
if len(httpCtx.FuncMap) == 0 {
t = template.Must(template.ParseFiles(templateFilePath))
} else {
t = template.Must(template.New(filepath.Base(httpCtx.TemplateFile)).Funcs(httpCtx.FuncMap).ParseFiles(templateFilePath))
}
if len(Config.Template.WidgetsPath) > 0 {
t = template.Must(t.ParseGlob(Config.Template.WidgetsPath))
}
return
}
//ReturnJSON ..
func (httpCtx *HTTPContext) ReturnJSON() {
httpCtx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8")
if len(httpCtx.Data) > 0 && httpCtx.Results == nil {
httpCtx.Results = httpCtx.Data
}
var w io.Writer
if !httpCtx.IsError && httpCtx.IsZip {
httpCtx.ResponseWriter.Header().Del("Content-Length")
httpCtx.ResponseWriter.Header().Set("Content-Encoding", "gzip")
w = gzip.NewWriter(httpCtx.ResponseWriter)
defer w.(io.WriteCloser).Close()
} else {
w = httpCtx.ResponseWriter
}
var err error
var results interface{}
if httpCtx.IsOnlyResults {
//results
results = httpCtx.Results
} else if httpCtx.HasHeader {
//header + response(err_no + err_msg + results)
results = httpCtx
} else {
//response(err_no + err_msg + results)
results = httpCtx.Response
}
httpCtx.Debugf("Response: %s", func() string {
var b []byte
b, err = encoding.JSON.Marshal(results)
if err != nil {
return err.Error()
}
return string(b)
}())
httpCtx.ResponseWriter.WriteHeader(httpCtx.HTTPStatus)
err = encoding.JSONIO.Marshal(w, results)
// httpCtx.ThrowCheck(500, err)
if err != nil {
httpCtx.Warn(err)
}
}