-
Notifications
You must be signed in to change notification settings - Fork 61
/
main.go
311 lines (230 loc) · 6.8 KB
/
main.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
package main
import (
"errors"
"fmt"
"github.com/stretchr/goweb"
"github.com/stretchr/goweb/context"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"time"
)
const (
Address string = ":9090"
)
// mapRoutes contains lots of examples of how to map things in
// Goweb. It is in its own function so that test code can call it
// without having to run main().
func mapRoutes() {
/*
Add a pre-handler to save the referrer
*/
goweb.MapBefore(func(c context.Context) error {
// add a custom header
c.HttpResponseWriter().Header().Set("X-Custom-Header", "Goweb")
return nil
})
/*
Add a post-handler to log something
*/
goweb.MapAfter(func(c context.Context) error {
// TODO: log this
return nil
})
/*
Map the homepage...
*/
goweb.Map("/", func(c context.Context) error {
return goweb.Respond.With(c, 200, []byte("Welcome to the Goweb example app - see the terminal for instructions."))
})
/*
Map a specific route that will redirect
*/
goweb.Map("GET", "people/me", func(c context.Context) error {
hostname, _ := os.Hostname()
return goweb.Respond.WithRedirect(c, fmt.Sprintf("/people/%s", hostname))
})
/*
/people (with optional ID)
*/
goweb.Map("GET", "people/[id]", func(c context.Context) error {
if c.PathParams().Has("id") {
return goweb.API.Respond(c, 200, fmt.Sprintf("Yes, this worked and your ID is %s", c.PathParams().Get("id")), nil)
} else {
return goweb.API.Respond(c, 200, "Yes, this worked but you didn't specify an ID", nil)
}
})
/*
/status-code/xxx
Where xxx is any HTTP status code.
*/
goweb.Map("/status-code/{code}", func(c context.Context) error {
// get the path value as an integer
statusCodeInt, statusCodeIntErr := strconv.Atoi(c.PathValue("code"))
if statusCodeIntErr != nil {
return goweb.Respond.With(c, http.StatusInternalServerError, []byte("Failed to convert 'code' into a real status code number."))
}
// respond with the status
return goweb.Respond.WithStatusText(c, statusCodeInt)
})
// /errortest should throw a system error and be handled by the
// DefaultHttpHandler().ErrorHandler() Handler.
goweb.Map("/errortest", func(c context.Context) error {
return errors.New("This is a test error!")
})
/*
Map a RESTful controller
(see the ThingsController for all the methods that will get
mapped)
*/
thingsController := new(ThingsController)
goweb.MapController(thingsController)
/*
Map a handler for if they hit just numbers using the goweb.RegexPath
function.
e.g. GET /2468
NOTE: The goweb.RegexPath is a MatcherFunc, and so comes _after_ the
handler.
*/
goweb.Map(func(c context.Context) error {
return goweb.API.RespondWithData(c, "Just a number!")
}, goweb.RegexPath(`^[0-9]+$`))
/*
Map the static-files directory so it's exposed as /static
*/
goweb.MapStatic("/static", "static-files")
/*
Map the a favicon
*/
goweb.MapStaticFile("/favicon.ico", "static-files/favicon.ico")
/*
Catch-all handler for everything that we don't understand
*/
goweb.Map(func(c context.Context) error {
// just return a 404 message
return goweb.API.Respond(c, 404, nil, []string{"File not found"})
})
}
func main() {
// map the routes
mapRoutes()
/*
START OF WEB SERVER CODE
*/
log.Print("Goweb 2")
log.Print("by Mat Ryer and Tyler Bunnell")
log.Print(" ")
log.Print("Starting Goweb powered server...")
// make a http server using the goweb.DefaultHttpHandler()
s := &http.Server{
Addr: Address,
Handler: goweb.DefaultHttpHandler(),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
listener, listenErr := net.Listen("tcp", Address)
log.Printf(" visit: %s", Address)
if listenErr != nil {
log.Fatalf("Could not listen: %s", listenErr)
}
log.Println("")
log.Print("Some things to try in your browser:")
log.Printf("\t http://localhost%s", Address)
log.Printf("\t http://localhost%s/status-code/404", Address)
log.Printf("\t http://localhost%s/people", Address)
log.Printf("\t http://localhost%s/people/123", Address)
log.Printf("\t http://localhost%s/people/anything", Address)
log.Printf("\t http://localhost%s/people/me (will redirect)", Address)
log.Printf("\t http://localhost%s/errortest", Address)
log.Printf("\t http://localhost%s/things (try RESTful actions)", Address)
log.Printf("\t http://localhost%s/123", Address)
log.Printf("\t http://localhost%s/static/simple.html", Address)
log.Println("")
log.Println("Also try some of these routes:")
log.Printf("%s", goweb.DefaultHttpHandler())
go func() {
for _ = range c {
// sig is a ^C, handle it
// stop the HTTP server
log.Print("Stopping the server...")
listener.Close()
/*
Tidy up and tear down
*/
log.Print("Tearing down...")
// TODO: tidy code up here
log.Fatal("Finished - bye bye. ;-)")
}
}()
// begin the server
log.Fatalf("Error in Serve: %s", s.Serve(listener))
/*
END OF WEB SERVER CODE
*/
}
/*
RESTful example
*/
// Thing is just a thing
type Thing struct {
Id string
Text string
}
// ThingsController is the RESTful MVC controller for Things.
type ThingsController struct {
// Things holds the things... obviously, you would never do this
// in the real world - you'd be reading from some kind of datastore.
Things []*Thing
}
// Before gets called before any other method.
func (r *ThingsController) Before(ctx context.Context) error {
// set a Things specific header
ctx.HttpResponseWriter().Header().Set("X-Things-Controller", "true")
return nil
}
func (r *ThingsController) Create(ctx context.Context) error {
data, dataErr := ctx.RequestData()
if dataErr != nil {
return goweb.API.RespondWithError(ctx, http.StatusInternalServerError, dataErr.Error())
}
dataMap := data.(map[string]interface{})
thing := new(Thing)
thing.Id = dataMap["Id"].(string)
thing.Text = dataMap["Text"].(string)
r.Things = append(r.Things, thing)
return goweb.Respond.WithStatus(ctx, http.StatusCreated)
}
func (r *ThingsController) ReadMany(ctx context.Context) error {
if r.Things == nil {
r.Things = make([]*Thing, 0)
}
return goweb.API.RespondWithData(ctx, r.Things)
}
func (r *ThingsController) Read(id string, ctx context.Context) error {
for _, thing := range r.Things {
if thing.Id == id {
return goweb.API.RespondWithData(ctx, thing)
}
}
return goweb.Respond.WithStatus(ctx, http.StatusNotFound)
}
func (r *ThingsController) DeleteMany(ctx context.Context) error {
r.Things = make([]*Thing, 0)
return goweb.Respond.WithOK(ctx)
}
func (r *ThingsController) Delete(id string, ctx context.Context) error {
newThings := make([]*Thing, 0)
for _, thing := range r.Things {
if thing.Id != id {
newThings = append(newThings, thing)
}
}
r.Things = newThings
return goweb.Respond.WithOK(ctx)
}