-
Notifications
You must be signed in to change notification settings - Fork 0
/
serverHandlerDynamic.go
256 lines (228 loc) · 6.23 KB
/
serverHandlerDynamic.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package vweb
import (
"path/filepath"
"io/ioutil"
"net/http"
"net/url"
"bytes"
"strings"
"fmt"
"time"
"os"
"errors"
"context"
"runtime"
"github.com/456vv/verror"
"io"
"log"
)
type DynamicTemplater interface{
SetPath(rootPath, pagePath string) // 设置路径
Parse(r io.Reader) (err error) // 解析
Execute(out io.Writer, dot interface{}) error // 执行
}
type DynamicTemplateFunc func(*ServerHandlerDynamic) DynamicTemplater
//web错误调用
func webError(rw http.ResponseWriter, v ...interface{}) {
//500 服务器遇到了意料不到的情况,不能完成客户的请求。
http.Error(rw, fmt.Sprint(v...), http.StatusInternalServerError)
}
//ServerHandlerDynamic 处理动态页面文件
type ServerHandlerDynamic struct {
//必须的
RootPath string // 根目录
PagePath string // 主模板文件路径
//可选的
BuffSize int // 缓冲块大小
Site *Site // 网站配置
Context context.Context // 上下文
Plus map[string]DynamicTemplateFunc // 支持更动态文件类型
StaticAt func(u *url.URL, r io.Reader, l int) (int, error) // 静态结果。仅在 .ServeHTTP 方法中使用
ReadFile func(u *url.URL, filePath string) (io.Reader, time.Time, error) // 读取文件。仅在 .ServeHTTP 方法中使用
ReplaceParse func(name string, p []byte) []byte
exec DynamicTemplater
modeTime time.Time
}
//ServeHTTP 服务HTTP
// rw http.ResponseWriter 响应
// req *http.Request 请求
func (T *ServerHandlerDynamic) ServeHTTP(rw http.ResponseWriter, req *http.Request){
if T.PagePath == "" {
T.PagePath = req.URL.Path
}
var filePath = filepath.Join(T.RootPath, T.PagePath)
var (
tmplread io.Reader
modeTime time.Time
err error
)
if T.ReadFile != nil {
tmplread, modeTime, err = T.ReadFile(req.URL, filePath)
if err != nil {
webError(rw, fmt.Sprintf("Failed to read the ReadFile! Error: %s", err.Error()))
return
}
if !modeTime.Equal(T.modeTime) {
T.exec = nil
}
T.modeTime = modeTime
}else{
osFile, err := os.Open(filePath)
if err != nil {
webError(rw, fmt.Sprintf("Failed to read the Open! Error: %s", err.Error()))
return
}
defer osFile.Close()
tmplread = osFile
//记录文件修改时间,用于缓存文件
osFileInfo, err := osFile.Stat()
if err != nil {
T.exec = nil
}else{
modeTime = osFileInfo.ModTime()
if !modeTime.Equal(T.modeTime) {
T.exec = nil
}
T.modeTime = modeTime
}
}
if T.exec == nil {
//解析模板内容
err = T.Parse(tmplread)
if err != nil {
webError(rw, err.Error())
return
}
}
//模板点
var dock = &TemplateDot{
R : req,
W : rw,
BuffSize : T.BuffSize,
Site : T.Site,
}
ctx := T.Context
if ctx == nil {
ctx = req.Context()
}
dock.WithContext(ctx)
var body = new(bytes.Buffer)
defer func(){
dock.Free()
if err != nil {
if !dock.Writed {
webError(rw, err.Error())
return
}
io.WriteString(rw, err.Error())
log.Println(err.Error())
return
}
if !dock.Writed {
if T.StaticAt != nil {
br := io.TeeReader(body, rw)
_, err = T.StaticAt(req.URL, br, body.Len())
if err != nil {
io.WriteString(rw, err.Error())
log.Println(err.Error())
return
}
}
if body.Len() != 0 {
body.WriteTo(rw)
}
}
}()
//执行模板内容
err = T.Execute(body, (TemplateDoter)(dock))
}
//ParseText 解析模板
// name, content string 模板名称, 模板内容
// error 错误
func (T *ServerHandlerDynamic) ParseText(name, content string) error {
T.PagePath = name
r := strings.NewReader(content)
return T.Parse(r)
}
//ParseFile 解析模板
// path string 模板文件路径,如果为空,默认使用RootPath,PagePath字段
// error 错误
func (T *ServerHandlerDynamic) ParseFile(path string) error {
if path == "" {
path = filepath.Join(T.RootPath, T.PagePath)
}else if !filepath.IsAbs(path) {
T.PagePath = path
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
return T.Parse(file)
}
//Parse 解析模板
// r io.Reader 模板内容
// error 错误
func (T *ServerHandlerDynamic) Parse(r io.Reader) (err error) {
if T.PagePath == "" {
return verror.TrackError("vweb: ServerHandlerDynamic.PagePath is not a valid path")
}
bufr, ok := r.(*bytes.Buffer)
if T.ReplaceParse != nil {
allb, err := ioutil.ReadAll(r)
if err != nil {
return verror.TrackErrorf("vweb: ServerHandlerDynamic.ReplaceParse failed to read data: %s", err.Error())
}
allb = T.ReplaceParse(T.PagePath, allb)
bufr = bytes.NewBuffer(allb)
}else if !ok {
bufr = bytes.NewBuffer(nil)
bufr.Grow(4096)
bufr.ReadFrom(r)
}
//文件首行
firstLine, err := bufr.ReadBytes('\n')
if err != nil || len(firstLine) == 0 {
return verror.TrackErrorf("vweb: Dynamic content is empty! Error: %s", err.Error())
}
drop := 0
if firstLine[len(firstLine)-1] == '\n' {
drop = 1
if len(firstLine) > 1 && firstLine[len(firstLine)-2] == '\r' {
drop = 2
}
firstLine = firstLine[:len(firstLine)-drop]
}
dynmicType := string(firstLine)
if T.Plus == nil || len(dynmicType) < 3 {
return errors.New("vweb: The file type of the first line of the file is not recognized")
}
if plus, ok := T.Plus[dynmicType[2:]]; ok {
shdt := plus(T)
shdt.SetPath(T.RootPath, T.PagePath)
err = shdt.Parse(bufr)
if err != nil {
return
}
T.exec = shdt
}
return
}
//Execute 执行模板
// bufw *bytes.Buffer 模板返回数据
// dock interface{} 与模板对接接口
// error 错误
func (T *ServerHandlerDynamic) Execute(bufw io.Writer, dock interface{}) (err error) {
if T.exec == nil {
return errors.New("vweb: Parse the template content first and then call the Execute")
}
defer func (){
if e := recover(); e != nil{
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
err = fmt.Errorf("vweb: Dynamic code execute error。%v\n%s", e, buf)
}
}()
return T.exec.Execute(bufw, dock)
}