This repository has been archived by the owner on Jun 11, 2023. It is now read-only.
/
webapp.go
175 lines (150 loc) · 4.24 KB
/
webapp.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
package webapp
import (
"compress/gzip"
"html/template"
"log"
"net"
"net/http"
"net/http/fcgi"
"regexp"
"strconv"
"strings"
"time"
)
const (
ErrNotFound = "Page Not Found"
ErrAccessDenied = "Access Denied"
ErrInternalServerError = "Internal Server Error"
)
type AbsApp interface {
Run()
AddHandleFunc(string, func(http.ResponseWriter, *http.Request))
SetStaticPath(string, string)
}
type App struct {
Port int
Handler RootHandler
}
type ContextInfo struct {
StartTime time.Time
During int64
URL string
HttpCode int
Message string
UseGZip bool
}
type Context struct {
Writer http.ResponseWriter
Request *http.Request
Application *App
Info ContextInfo
Headers map[string]string
}
var EmailPattern, URLPattern *regexp.Regexp
type RenderHandler func(*App, map[string]string) (string, error)
type RootHandler struct {
HandleFunc func(ctx *Context)
Application *App
}
func (h RootHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
c := new(Context)
c.Writer = w
c.Request = req
c.Application = h.Application
h.HandleFunc(c)
}
func init() {
EmailPattern = regexp.MustCompile("^[0-9a-zA-Z_.\\-+]+@[0-9a-zA-Z_.]+\\.[0-9a-zA-Z_.]+$")
URLPattern = regexp.MustCompile("^[0-9a-zA-Z]+://.*$")
}
func (ctx *Context) Redirect(url string, code int) {
ctx.Info.Message = "Redirect"
ctx.Info.HttpCode = http.StatusFound
ctx.Application.AccessLog(ctx)
http.Redirect(ctx.Writer, ctx.Request, url, code)
}
func (ctx *Context) Error(msg string, code int) {
ctx.Info.Message = msg
ctx.Info.HttpCode = code
ctx.Application.ErrorLog(ctx)
http.Error(ctx.Writer, msg, code)
}
func (ctx *Context) SetHeader(key string, val string) {
if ctx.Headers == nil {
ctx.Headers = make(map[string]string)
}
ctx.Headers[key] = val
}
func (ctx *Context) Execute(tpl *template.Template, data interface{}) error {
var err error
ctx.Info.Message = "OK"
ctx.Info.HttpCode = 200
ctx.Application.AccessLog(ctx)
ctx.Writer.Header().Set("Content-Type", "text/html")
ctx.Writer.Header().Set("Connection", "keep-alive")
ctx.Writer.Header().Set("Cache-Control", "must-revalidate, max-age=300")
// overlay headers
if ctx.Headers != nil {
for k, v := range ctx.Headers {
ctx.Writer.Header().Set(k, v)
}
}
// compress ?
if ctx.Info.UseGZip {
gw := gzip.NewWriter(ctx.Writer)
ctx.Writer.Header().Set("Content-Encoding", "gzip")
err = tpl.Execute(gw, data)
gw.Close()
} else {
err = tpl.Execute(ctx.Writer, data)
}
return err
}
func (app *App) Run(port int) {
app.Port = port
err := http.ListenAndServe(":"+strconv.Itoa(app.Port), nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func (app *App) RunCGI(port int) {
app.Port = port
l, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(port))
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
fcgi.Serve(l, app.Handler)
}
func (app *App) SetHandler(url string, handleFunc func(*Context)) {
app.Handler.HandleFunc = handleFunc
app.Handler.Application = app
http.Handle(url, app.Handler)
return
}
func (app *App) SetStaticPath(url string, path string) {
http.Handle(url+"/", http.StripPrefix(url, http.FileServer(http.Dir(path))))
return
}
func (app *App) ErrorLog(ctx *Context) {
log.Printf("[ERR] host: '%s', request: '%s %s', proto: '%s', ua: '%s', code: %d, remote: '%s', message: '%s'\n", ctx.Request.Host, ctx.Request.Method, ctx.Request.URL.Path, ctx.Request.Proto, ctx.Request.UserAgent(), ctx.Info.HttpCode, ctx.Request.RemoteAddr, ctx.Info.Message)
}
func (app *App) AccessLog(ctx *Context) {
log.Printf("[ACC] host: '%s', request: '%s %s', proto: '%s', ua: %s'', code: %d, remote: '%s', message: '%s'\n", ctx.Request.Host, ctx.Request.Method, ctx.Request.URL.Path, ctx.Request.Proto, ctx.Request.UserAgent(), ctx.Info.HttpCode, ctx.Request.RemoteAddr, ctx.Info.Message)
}
func (app *App) Log(tag string, msg string) {
log.Printf("[%s] %s\n", tag, msg)
}
func CheckForm(re *regexp.Regexp, in string) bool {
return re.Match([]byte(in))
}
func CheckEmailForm(in string) bool {
return EmailPattern.Match([]byte(in))
}
func TransformTags(in string) string {
in = strings.Replace(in, "<", "<", -1)
in = strings.Replace(in, ">", ">", -1)
return in
}
func CheckURLForm(in string) bool {
return URLPattern.Match([]byte(in))
}