-
Notifications
You must be signed in to change notification settings - Fork 704
/
web.go
211 lines (179 loc) · 6.05 KB
/
web.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
// Package web is a lightweight web framework for Go. It's ideal for
// writing simple, performant backend web services.
package web
import (
"crypto/tls"
"golang.org/x/net/websocket"
"log"
"mime"
"net/http"
"os"
"path"
"reflect"
"strings"
)
// A Context object is created for every incoming HTTP request, and is
// passed to handlers as an optional first argument. It provides information
// about the request, including the http.Request object, the GET and POST params,
// and acts as a Writer for the response.
type Context struct {
Request *http.Request
Params map[string]string
Server *Server
http.ResponseWriter
}
// WriteString writes string data into the response object.
func (ctx *Context) WriteString(content string) {
ctx.ResponseWriter.Write([]byte(content))
}
// Abort is a helper method that sends an HTTP header and an optional
// body. It is useful for returning 4xx or 5xx errors.
// Once it has been called, any return value from the handler will
// not be written to the response.
func (ctx *Context) Abort(status int, body string) {
ctx.SetHeader("Content-Type", "text/html; charset=utf-8", true)
ctx.ResponseWriter.WriteHeader(status)
ctx.ResponseWriter.Write([]byte(body))
}
// Redirect is a helper method for 3xx redirects.
func (ctx *Context) Redirect(status int, url_ string) {
ctx.ResponseWriter.Header().Set("Location", url_)
ctx.ResponseWriter.WriteHeader(status)
ctx.ResponseWriter.Write([]byte("Redirecting to: " + url_))
}
//BadRequest writes a 400 HTTP response
func (ctx *Context) BadRequest() {
ctx.ResponseWriter.WriteHeader(400)
}
// Notmodified writes a 304 HTTP response
func (ctx *Context) NotModified() {
ctx.ResponseWriter.WriteHeader(304)
}
//Unauthorized writes a 401 HTTP response
func (ctx *Context) Unauthorized() {
ctx.ResponseWriter.WriteHeader(401)
}
//Forbidden writes a 403 HTTP response
func (ctx *Context) Forbidden() {
ctx.ResponseWriter.WriteHeader(403)
}
// NotFound writes a 404 HTTP response
func (ctx *Context) NotFound(message string) {
ctx.ResponseWriter.WriteHeader(404)
ctx.ResponseWriter.Write([]byte(message))
}
// ContentType sets the Content-Type header for an HTTP response.
// For example, ctx.ContentType("json") sets the content-type to "application/json"
// If the supplied value contains a slash (/) it is set as the Content-Type
// verbatim. The return value is the content type as it was
// set, or an empty string if none was found.
func (ctx *Context) ContentType(val string) string {
var ctype string
if strings.ContainsRune(val, '/') {
ctype = val
} else {
if !strings.HasPrefix(val, ".") {
val = "." + val
}
ctype = mime.TypeByExtension(val)
}
if ctype != "" {
ctx.Header().Set("Content-Type", ctype)
}
return ctype
}
// SetHeader sets a response header. If `unique` is true, the current value
// of that header will be overwritten . If false, it will be appended.
func (ctx *Context) SetHeader(hdr string, val string, unique bool) {
if unique {
ctx.Header().Set(hdr, val)
} else {
ctx.Header().Add(hdr, val)
}
}
// SetCookie adds a cookie header to the response.
func (ctx *Context) SetCookie(cookie *http.Cookie) {
ctx.SetHeader("Set-Cookie", cookie.String(), false)
}
// small optimization: cache the context type instead of repeteadly calling reflect.Typeof
var contextType reflect.Type
var defaultStaticDirs []string
func init() {
contextType = reflect.TypeOf(Context{})
//find the location of the exe file
wd, _ := os.Getwd()
arg0 := path.Clean(os.Args[0])
var exeFile string
if strings.HasPrefix(arg0, "/") {
exeFile = arg0
} else {
//TODO for robustness, search each directory in $PATH
exeFile = path.Join(wd, arg0)
}
parent, _ := path.Split(exeFile)
defaultStaticDirs = append(defaultStaticDirs, path.Join(parent, "static"))
defaultStaticDirs = append(defaultStaticDirs, path.Join(wd, "static"))
return
}
// Process invokes the main server's routing system.
func Process(c http.ResponseWriter, req *http.Request) {
mainServer.Process(c, req)
}
// Run starts the web application and serves HTTP requests for the main server.
func Run(addr string) {
mainServer.Run(addr)
}
// RunTLS starts the web application and serves HTTPS requests for the main server.
func RunTLS(addr string, config *tls.Config) {
mainServer.RunTLS(addr, config)
}
// RunScgi starts the web application and serves SCGI requests for the main server.
func RunScgi(addr string) {
mainServer.RunScgi(addr)
}
// RunFcgi starts the web application and serves FastCGI requests for the main server.
func RunFcgi(addr string) {
mainServer.RunFcgi(addr)
}
// Close stops the main server.
func Close() {
mainServer.Close()
}
// Get adds a handler for the 'GET' http method in the main server.
func Get(route string, handler interface{}) {
mainServer.Get(route, handler)
}
// Post adds a handler for the 'POST' http method in the main server.
func Post(route string, handler interface{}) {
mainServer.addRoute(route, "POST", handler)
}
// Put adds a handler for the 'PUT' http method in the main server.
func Put(route string, handler interface{}) {
mainServer.addRoute(route, "PUT", handler)
}
// Delete adds a handler for the 'DELETE' http method in the main server.
func Delete(route string, handler interface{}) {
mainServer.addRoute(route, "DELETE", handler)
}
// Match adds a handler for an arbitrary http method in the main server.
func Match(method string, route string, handler interface{}) {
mainServer.addRoute(route, method, handler)
}
// Add a custom http.Handler. Will have no effect when running as FCGI or SCGI.
func Handle(route string, method string, httpHandler http.Handler) {
mainServer.Handle(route, method, httpHandler)
}
//Adds a handler for websockets. Only for webserver mode. Will have no effect when running as FCGI or SCGI.
func Websocket(route string, httpHandler websocket.Handler) {
mainServer.Websocket(route, httpHandler)
}
// SetLogger sets the logger for the main server.
func SetLogger(logger *log.Logger) {
mainServer.Logger = logger
}
// Config is the configuration of the main server.
var Config = &ServerConfig{
RecoverPanic: true,
ColorOutput: true,
}
var mainServer = NewServer()