-
Notifications
You must be signed in to change notification settings - Fork 0
/
results.go
executable file
·780 lines (655 loc) · 20.7 KB
/
results.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
package gweb
import (
"encoding/json"
"errors"
"fmt"
"github.com/nbvghost/gweb/cache"
"github.com/nbvghost/tool/encryption"
"html/template"
"net/http/httptest"
"github.com/nbvghost/glog"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/nbvghost/gweb/conf"
)
var _ Result = (*ErrorResult)(nil)
var _ Result = (*SingleHostReverseProxyResult)(nil)
var _ Result = (*SingleHostForwardProxyResult)(nil)
var _ Result = (*ViewActionMappingResult)(nil)
var _ Result = (*ViewResult)(nil)
var _ Result = (*EmptyResult)(nil)
var _ Result = (*cacheHTMLResult)(nil)
var _ Result = (*HTMLResult)(nil)
var _ Result = (*JsonResult)(nil)
var _ Result = (*FileServerResult)(nil)
var _ Result = (*HtmlPlainResult)(nil)
var _ Result = (*TextResult)(nil)
var _ Result = (*JavaScriptResult)(nil)
var _ Result = (*XMLResult)(nil)
var _ Result = (*RedirectToUrlResult)(nil)
var _ Result = (*ImageResult)(nil)
var _ Result = (*ImageBytesResult)(nil)
type Result interface {
Apply(context *Context)
}
type ErrorResult struct {
Error error
}
func NewErrorResult(err error) *ErrorResult {
return &ErrorResult{Error: err}
}
func (r *ErrorResult) Apply(context *Context) {
if r.Error != nil {
http.Error(context.Response, r.Error.Error(), http.StatusNotFound)
} else {
http.Error(context.Response, "error", http.StatusNotFound)
}
}
type SingleHostReverseProxyResult struct {
Target *url.URL
}
func (r *SingleHostReverseProxyResult) Apply(context *Context) {
rp := httputil.NewSingleHostReverseProxy(r.Target)
rp.ServeHTTP(context.Response, context.Request)
}
type SingleHostForwardProxyResult struct {
Target *url.URL
}
func (r *SingleHostForwardProxyResult) Apply(context *Context) {
transport := http.DefaultTransport
// step 1Forward Proxy
//outReq := new(http.Request)
//*outReq = *context.Request // this only does shallow copies of maps
//fmt.Printf("Received request %s %s %s\n", context.Request.Method, context.Request.URL.String(), r.Target.String())
outReq, _ := http.NewRequest(context.Request.Method, r.Target.String(), context.Request.Body)
if clientIP, _, err := net.SplitHostPort(context.Request.RemoteAddr); err == nil {
if prior, ok := outReq.Header["X-Forwarded-For"]; ok {
clientIP = strings.Join(prior, ", ") + ", " + clientIP
}
outReq.Header.Set("X-Forwarded-For", clientIP)
}
// step 2
res, err := transport.RoundTrip(outReq)
if err != nil {
context.Response.WriteHeader(http.StatusBadGateway)
} else {
// step 3
for key, value := range res.Header {
for _, v := range value {
context.Response.Header().Add(key, v)
}
}
context.Response.WriteHeader(res.StatusCode)
io.Copy(context.Response, res.Body)
res.Body.Close()
}
}
type MIME string
const (
MultipartByteranges MIME = "multipart/byteranges"
MultipartFormData MIME = "multipart/form-data"
AudioWave MIME = "audio/wave"
AudioWav MIME = "audio/wav"
AudioXWav MIME = "audio/x-wav"
AudioWPnWav MIME = "audio/x-pn-wav"
AudioWebm MIME = "audio/webm"
AudioOgg MIME = "audio/ogg"
AudioMpeg MIME = "audio/mpeg"
VideoWebm MIME = "video/webm"
VideoOgg MIME = "video/ogg"
VideoMp4 MIME = "video/mp4"
ApplicationOgg MIME = "application/ogg"
ApplicationJson MIME = "application/json"
ApplicationJavascript MIME = "application/javascript"
ApplicationEcmascript MIME = "application/ecmascript"
ApplicationOctetStream MIME = "application/octet-stream"
ImageGif MIME = "image/gif"
ImageJpeg MIME = "image/jpeg"
ImagePng MIME = "image/png"
ImageSvgXml MIME = "image/svg+xml"
TextCss MIME = "text/css"
TextHtml MIME = "text/html"
TextPlain MIME = "text/plain"
)
/**
类型/子类型 扩展名
application/json json
application/envoy evy
application/fractals fif
application/futuresplash spl
application/hta hta
application/internet-property-stream acx
application/mac-binhex40 hqx
application/msword doc
application/msword dot
application/octet-stream *
application/octet-stream bin
application/octet-stream class
application/octet-stream dms
application/octet-stream exe
application/octet-stream lha
application/octet-stream lzh
application/oda oda
application/olescript axs
application/pdf pdf
application/pics-rules prf
application/pkcs10 p10
application/pkix-crl crl
application/postscript ai
application/postscript eps
application/postscript ps
application/rtf rtf
application/set-payment-initiation setpay
application/set-registration-initiation setreg
application/vnd.ms-excel xla
application/vnd.ms-excel xlc
application/vnd.ms-excel xlm
application/vnd.ms-excel xls
application/vnd.ms-excel xlt
application/vnd.ms-excel xlw
application/vnd.ms-outlook msg
application/vnd.ms-pkicertstore sst
application/vnd.ms-pkiseccat cat
application/vnd.ms-pkistl stl
application/vnd.ms-powerpoint pot
application/vnd.ms-powerpoint pps
application/vnd.ms-powerpoint ppt
application/vnd.ms-project mpp
application/vnd.ms-works wcm
application/vnd.ms-works wdb
application/vnd.ms-works wks
application/vnd.ms-works wps
application/winhlp hlp
application/x-bcpio bcpio
application/x-cdf cdf
application/x-compress z
application/x-compressed tgz
application/x-cpio cpio
application/x-csh csh
application/x-director dcr
application/x-director dir
application/x-director dxr
application/x-dvi dvi
application/x-gtar gtar
application/x-gzip gz
application/x-hdf hdf
application/x-internet-signup ins
application/x-internet-signup isp
application/x-iphone iii
application/x-javascript js
application/x-latex latex
application/x-msaccess mdb
application/x-mscardfile crd
application/x-msclip clp
application/x-msdownload dll
application/x-msmediaview m13
application/x-msmediaview m14
application/x-msmediaview mvb
application/x-msmetafile wmf
application/x-msmoney mny
application/x-mspublisher pub
application/x-msschedule scd
application/x-msterminal trm
application/x-mswrite wri
application/x-netcdf cdf
application/x-netcdf nc
application/x-perfmon pma
application/x-perfmon pmc
application/x-perfmon pml
application/x-perfmon pmr
application/x-perfmon pmw
application/x-pkcs12 p12
application/x-pkcs12 pfx
application/x-pkcs7-certificates p7b
application/x-pkcs7-certificates spc
application/x-pkcs7-certreqresp p7r
application/x-pkcs7-mime p7c
application/x-pkcs7-mime p7m
application/x-pkcs7-signature p7s
application/x-sh sh
application/x-shar shar
application/x-shockwave-flash swf
application/x-stuffit sit
application/x-sv4cpio sv4cpio
application/x-sv4crc sv4crc
application/x-tar tar
application/x-tcl tcl
application/x-tex tex
application/x-texinfo texi
application/x-texinfo texinfo
application/x-troff roff
application/x-troff t
application/x-troff tr
application/x-troff-man man
application/x-troff-me me
application/x-troff-ms ms
application/x-ustar ustar
application/x-wais-source src
application/x-x509-ca-cert cer
application/x-x509-ca-cert crt
application/x-x509-ca-cert der
application/ynd.ms-pkipko pko
application/zip zip
audio/basic au
audio/basic snd
audio/mid mid
audio/mid rmi
audio/mpeg mp3
audio/x-aiff aif
audio/x-aiff aifc
audio/x-aiff aiff
audio/x-mpegurl m3u
audio/x-pn-realaudio ra
audio/x-pn-realaudio ram
audio/x-wav wav
image/bmp bmp
image/cis-cod cod
image/gif gif
image/ief ief
image/jpeg jpe
image/jpeg jpeg
image/jpeg jpg
image/pipeg jfif
image/svg+xml svg
image/tiff tif
image/tiff tiff
image/x-cmu-raster ras
image/x-cmx cmx
image/x-icon ico
image/x-portable-anymap pnm
image/x-portable-bitmap pbm
image/x-portable-graymap pgm
image/x-portable-pixmap ppm
image/x-rgb rgb
image/x-xbitmap xbm
image/x-xpixmap xpm
image/x-xwindowdump xwd
message/rfc822 mht
message/rfc822 mhtml
message/rfc822 nws
text/css css
text/h323 323
text/html htm
text/html html
text/html stm
text/iuls uls
text/plain bas
text/plain c
text/plain h
text/plain txt
text/richtext rtx
text/scriptlet sct
text/tab-separated-values tsv
text/webviewhtml htt
text/x-component htc
text/x-setext etx
text/x-vcard vcf
video/mpeg mp2
video/mpeg mpa
video/mpeg mpe
video/mpeg mpeg
video/mpeg mpg
video/mpeg mpv2
video/quicktime mov
video/quicktime qt
video/x-la-asf lsf
video/x-la-asf lsx
video/x-ms-asf asf
video/x-ms-asf asr
video/x-ms-asf asx
video/x-msvideo avi
video/x-sgi-movie movie
x-world/x-vrml flr
x-world/x-vrml vrml
x-world/x-vrml wrl
x-world/x-vrml wrz
x-world/x-vrml xaf
x-world/x-vrml xof
*/
type ViewActionMappingResult struct {
}
var fileNameRegexp = regexp.MustCompile("\\/([0-9a-zA-Z_]+)\\.([0-9a-zA-Z]+)$")
func (r *ViewActionMappingResult) Apply(context *Context) {
path := context.Request.URL.Path
viewSubDir := context.Function.controller.ViewSubDir
if strings.EqualFold(viewSubDir, "") == false {
viewSubDir = viewSubDir + "/"
}
if strings.EqualFold(path, "/") {
if strings.EqualFold(conf.Config.DefaultPage, "") == false {
path = path + conf.Config.DefaultPage
var redirectToUrlResult = &RedirectToUrlResult{Url: path}
redirectToUrlResult.Apply(context)
return
}
}
path = strings.TrimRight(path, "/")
//b, err := ioutil.ReadFile(conf.Config.ViewDir + path + conf.Config.ViewSuffix)
b, err := cache.Read(fixPath(conf.Config.ViewDir + "/" + viewSubDir + "/" + path + conf.Config.ViewSuffix))
if err != nil {
//不存在
//fmt.Println(context.Request.Header)
var haveMIME = false
//b, err := ioutil.ReadFile(conf.Config.ViewDir + path)
b, err := cache.Read(fixPath(conf.Config.ViewDir + "/" + viewSubDir + "/" + path))
if err == nil {
glog.Error(err)
if fileNameRegexp.MatchString(path) {
Groups := fileNameRegexp.FindAllStringSubmatch(path, -1)
//[[/fgsd_gffdgdf.txt fgsd_gffdgdf txt]]
//{"ContentType": "text/html","Extension":"html"}
Extension := Groups[0][2]
for index := range conf.Config.ViewActionMapping {
ce := conf.Config.ViewActionMapping[index]
if strings.EqualFold(ce.Extension, Extension) {
context.Response.Header().Set("Content-Type", ce.ContentType+"; charset=utf-8")
//w.Header().Set("X-Content-Type-Options", "nosniff")
context.Response.WriteHeader(http.StatusOK)
context.Response.Write(b.Byte)
haveMIME = true
break
}
}
}
}
if haveMIME == false {
fi, err := os.Stat(conf.Config.ViewDir + path)
//log.Println(err)
if err == nil && fi.IsDir() {
path = path + "/" + conf.Config.DefaultPage
var redirectToUrlResult = &RedirectToUrlResult{Url: path}
redirectToUrlResult.Apply(context)
} else {
//没有找到路由,
http.NotFound(context.Response, context.Request)
}
}
} else {
context.Response.Header().Set("Content-Type", "text/html; charset=utf-8")
context.Response.WriteHeader(http.StatusOK)
t, err := template.New("default").Funcs(NewFuncMap(context)).Parse(string(b.Byte))
glog.Error(err)
data := make(map[string]interface{})
data["session"] = context.Session.Attributes.GetMap()
data["query"] = QueryParams(context.Request.URL.Query())
glog.Error(t.Execute(context.Response, data))
}
}
/*type NotFindResult struct {
}
func (r *NotFindResult) Apply(context *Context) {
path := context.Request.URL.Path
b, err := ioutil.ReadFile(fixPath(conf.Config.ViewDir + "/" + path))
if err != nil {
//没有找到路由,
http.NotFound(context.Response, context.Request)
} else {
t, err := template.New("default").Funcs(tool.FuncMap()).Parse(string(b))
tool.CheckError(err)
t.Execute(context.Response, nil)
}
}*/
//不做处理,返回原 Response
type ViewResult struct {
}
func (r *ViewResult) Apply(context *Context) {
}
type EmptyResult struct {
}
func (r *EmptyResult) Apply(context *Context) {
}
//只映射已经定义的后缀模板文件,并生成html缓存文件
type cacheHTMLResult struct {
*HTMLResult
ServiceName string
}
func (r *cacheHTMLResult) Apply(context *Context) {
if r.ServiceName == "" {
NewErrorResult(errors.New("CacheHTMLResult 结果,必须指定ServiceName值")).Apply(context)
return
}
responseRecorder := httptest.NewRecorder()
copyContext := context.Clone()
copyContext.Response = responseRecorder
r.HTMLResult.Apply(©Context)
context.Response.WriteHeader(responseRecorder.Code)
for key := range responseRecorder.Header() {
context.Response.Header().Set(key, responseRecorder.Header().Get(key))
}
dataByte, err := ioutil.ReadAll(responseRecorder.Body)
if glog.Error(err) {
NewErrorResult(err).Apply(context)
return
}
//path, filename := filepath.Split(context.Request.URL.Path)
//path := context.Request.URL.Path
var fullPath = context.Request.URL.Path
if strings.EqualFold(context.Request.URL.RawQuery, "") == false {
fullPath = fullPath + "?" + context.Request.URL.RawQuery
}
fullPathMd5 := encryption.Md5ByString(fullPath)
cacheDir := fmt.Sprintf("cache/%v", r.ServiceName)
cacheFile := cacheDir + "/" + fullPathMd5
if IsFileExist(cacheDir) == false {
glog.Error(os.MkdirAll(cacheDir, os.ModePerm))
}
dataByte = emptyTextRegexp.ReplaceAll(dataByte, []byte(" "))
dataByte = wrapTextRegexp.ReplaceAll(dataByte, []byte{})
glog.Error(ioutil.WriteFile(cacheFile, dataByte, os.ModePerm))
context.Response.Write(dataByte)
}
var emptyTextRegexp = regexp.MustCompile(`\s{2,}`)
var wrapTextRegexp = regexp.MustCompile(`[\r\n]`)
// HTMLResult 只映射已经定义的后缀模板文件
type HTMLResult struct {
Name string
StatusCode int
Params map[string]interface{}
Template []string //读取当前目录下 template 文件夹下的模板
}
func (r *HTMLResult) Apply(context *Context) {
path, filename := filepath.Split(context.Request.URL.Path)
var b *cache.CacheFileItem
var err error
viewSubDir := context.Function.controller.ViewSubDir
if strings.EqualFold(viewSubDir, "") == false {
viewSubDir = viewSubDir + "/"
}
if strings.EqualFold(r.Name, "") {
//html 只处理,已经定义后缀名的文件
//b, err = ioutil.ReadFile(fixPath(conf.Config.ViewDir + "/" + path + conf.Config.ViewSuffix))
b, err = cache.Read(fixPath(conf.Config.ViewDir + "/" + viewSubDir + path + "/" + filename + conf.Config.ViewSuffix))
} else {
//b, err = ioutil.ReadFile(fixPath(conf.Config.ViewDir + "/" + r.Name + conf.Config.ViewSuffix))
b, err = cache.Read(fixPath(conf.Config.ViewDir + "/" + viewSubDir + context.RoutePath + "/" + r.Name + conf.Config.ViewSuffix))
}
if err != nil {
//判断是否有默认页面
//fmt.Println(fixPath(Config.ViewDir + "/" + path +"/"+ Config.DefaultPage))
//b, err = ioutil.ReadFile(fixPath(conf.Config.ViewDir + "/" + path + "/" + conf.Config.DefaultPage + conf.Config.ViewSuffix))
b, err = cache.Read(fixPath(conf.Config.ViewDir + "/" + viewSubDir + path + "/" + conf.Config.DefaultPage + conf.Config.ViewSuffix))
if err != nil {
(&ViewActionMappingResult{}).Apply(context)
return
}
}
//t, err := template.New("default").Funcs(FuncMap).Parse(string(b))
t := template.New("HTMLResult").Funcs(NewFuncMap(context))
for index := range r.Template {
tpath := r.Template[index]
var err error
var tt *template.Template
if strings.Contains(tpath, "*") {
tt, err = t.ParseGlob(conf.Config.ViewDir + "/" + viewSubDir + tpath)
} else {
tt, err = t.ParseFiles(conf.Config.ViewDir + "/" + viewSubDir + tpath)
}
if err != nil {
glog.Trace(err)
} else {
t = tt
}
}
t, err = t.Parse(string(b.Byte))
//template.Must(t.Parse(string(b)))
if glog.Error(err) {
t, err = template.New("HTMLResult").Parse(err.Error())
}
data := createPageParams(context, r.Params)
context.Response.Header().Set("Content-Type", "text/html; charset=utf-8")
if r.StatusCode == 0 {
context.Response.WriteHeader(http.StatusOK)
} else {
context.Response.WriteHeader(r.StatusCode)
}
glog.Error(t.Execute(context.Response, data))
}
func createPageParams(context *Context, Params map[string]interface{}) map[string]interface{} {
data := make(map[string]interface{})
data["session"] = context.Session.Attributes.GetMap()
data["query"] = QueryParams(context.Request.URL.Query())
data["params"] = Params
data["debug"] = conf.Config.Debug
data["host"] = context.Request.Host
data["time"] = time.Now().Unix() * 1000
data["rootPath"] = context.RoutePath
data["data"] = conf.JsonData.Copy()
return data
//context.Response.Header().Set("Content-Type", "text/html; charset=utf-8")
//context.Response.WriteHeader(http.StatusOK)
//t.Execute(context.Response, data)
}
type JsonResult struct {
error
Data interface{}
///sync.RWMutex
}
/*func (r *JsonResult)encodeJson() (error,[]byte) {
r.Lock()
defer r.Unlock()
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(r.Data)
return err,buffer.Bytes()
}*/
func (r *JsonResult) Apply(context *Context) {
var b []byte
var err error
b, err = json.Marshal(r.Data)
if err != nil {
(&ErrorResult{Error: err}).Apply(context)
return
}
//return buffer.Bytes(), err
//b, err = json.Marshal(r.Data)
//b = buffer.Bytes()
context.Response.Header().Set("Content-Type", "application/json; charset=utf-8")
context.Response.WriteHeader(http.StatusOK)
//context.Response.Header().Add("Content-Type", "application/json")
context.Response.Write(b)
}
type FileServerResult struct {
Prefix string
Dir string
}
// http.StripPrefix
func (fs *FileServerResult) Apply(context *Context) {
//dir, _ := filepath.Split(context.Request.URL.Path)
//log.Println(dir, fileName)
//http.FileServer(http.Dir(conf.Config.ViewDir)+"/"+fs.Dir).ServeHTTP(context.Response, context.Request)
//http.StripPrefix(conf.Config.ResourcesDir, http.FileServer(http.Dir(fs.Dir))).ServeHTTP(context.Response, context.Request)
//http.StripPrefix(fs.StripPrefix, http.FileServer(http.Dir(dir))).ServeHTTP(context.Response, context.Request)
//http.StripPrefix(fs.StripPrefix, http.FileServer(http.Dir(context.Request.URL.Path))).ServeHTTP(context.Response, context.Request)
//http.StripPrefix(dir, http.FileServer(http.Dir("resources"))).ServeHTTP(context.Response, context.Request)
//http.StripPrefix(dir, http.FileServer(fs.Dir+"/"+http.Dir(dir))).ServeHTTP(context.Response, context.Request)
//http.StripPrefix("/resources/", http.FileServer(http.Dir(conf.Config.ResourcesDir+"/resources"))).ServeHTTP(context.Response, context.Request)
//http.StripPrefix("/web/", http.FileServer(http.Dir(conf.Config.ViewDir+"/web/"))).ServeHTTP(context.Response, context.Request)
//http.StripPrefix(fs.StripPrefix, http.FileServer(http.Dir(fs.Dir+fs.StripPrefix))).ServeHTTP(context.Response, context.Request)
http.StripPrefix(fs.Prefix, http.FileServer(http.Dir(fs.Dir))).ServeHTTP(context.Response, context.Request)
}
type HtmlPlainResult struct {
Data string
Params map[string]interface{}
}
func (r *HtmlPlainResult) Apply(context *Context) {
t := template.New("HtmlPlainResult").Funcs(NewFuncMap(context))
t, err := t.Parse(r.Data)
//template.Must(t.Parse(string(b)))
if err != nil {
log.Println(err)
t, err = template.New("HtmlPlainResult").Parse(err.Error())
}
data := createPageParams(context, r.Params)
context.Response.Header().Set("Content-Type", "text/html; charset=utf-8")
context.Response.WriteHeader(http.StatusOK)
glog.Error(t.Execute(context.Response, data))
//context.Response.Header().Set("Content-Type", "text/xml; charset=utf-8")
//context.Response.WriteHeader(http.StatusOK)
//context.Response.Write([]byte(r.Data))
}
type TextResult struct {
Data string
}
func (r *TextResult) Apply(context *Context) {
context.Response.Header().Set("Content-Type", "text/plain; charset=utf-8")
context.Response.WriteHeader(http.StatusOK)
context.Response.Write([]byte(r.Data))
}
type JavaScriptResult struct {
Data string
}
func (r *JavaScriptResult) Apply(context *Context) {
context.Response.Header().Add("Content-Type", "application/javascript; charset=utf-8")
context.Response.WriteHeader(http.StatusOK)
context.Response.Write([]byte(r.Data))
}
type XMLResult struct {
Data string
}
func (r *XMLResult) Apply(context *Context) {
context.Response.Header().Set("Content-Type", "text/xml; charset=utf-8")
context.Response.WriteHeader(http.StatusOK)
context.Response.Write([]byte(r.Data))
}
type RedirectToUrlResult struct {
Url string
}
func (r *RedirectToUrlResult) Apply(context *Context) {
//context.Response.Header().Set("Location", r.Url)
//context.Response.WriteHeader(http.StatusFound)
//context.Response.Header().Set("Content-Type", "")
http.Redirect(context.Response, context.Request, fmt.Sprintf("%s/%s", context.Request.URL.Path, r.Url), http.StatusFound)
}
type ImageResult struct {
FilePath string
}
func (r *ImageResult) Apply(context *Context) {
file, err := cache.Read(r.FilePath)
if err != nil {
return
}
context.Response.Write(file.Byte)
//context.Response.Header().Set("Location", r.Url)
//context.Response.WriteHeader(http.StatusFound)
//context.Response.Header().Set("Content-Type", "")
}
type ImageBytesResult struct {
Data []byte
ContentType string //: image/png
}
func (r *ImageBytesResult) Apply(context *Context) {
//context.Response.Header().Add()
context.Response.Header().Set("Content-Type", r.ContentType)
context.Response.Write(r.Data)
}