Skip to content

Commit 95906b9

Browse files
committed
Simplified the testing harness. There are new convenience methods that make testing slightly easier. Also, there are new tests which test error conditions.
1 parent 507ef47 commit 95906b9

File tree

4 files changed

+187
-152
lines changed

4 files changed

+187
-152
lines changed

Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,5 @@ format:
2323
${GOFMT} -w servefile.go
2424
${GOFMT} -w web.go
2525
${GOFMT} -w web_test.go
26+
${GOFMT} -w examples/hello.go
27+
${GOFMT} -w examples/arcchallenge.go

examples/arcchallenge.go

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,11 @@ import (
77
var form = `<form action="say" method="POST"><input name="said"><input type="submit"></form>`
88

99
func main() {
10-
web.Get("/said", func() string {
11-
return form
12-
})
10+
web.Get("/said", func() string { return form })
1311
web.Post("/say", func(ctx *web.Context) string {
14-
ctx.Session.Data["said"] = ctx.Request.Params["said"][0]
12+
ctx.Session.Data["said"] = ctx.Request.Params["said"][0]
1513
return `<a href="/final">Click Here</a>`
1614
})
17-
web.Get("/final", func(ctx *web.Context) string {
18-
return "You said " + ctx.Session.Data["said"].(string)
19-
})
15+
web.Get("/final", func(ctx *web.Context) string { return "You said " + ctx.Session.Data["said"].(string) })
2016
web.Run("0.0.0.0:9999")
2117
}

web.go

Lines changed: 51 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,13 @@ type Context struct {
2626
*Request
2727
Session *session
2828
Conn
29+
responseStarted bool
2930
}
3031

3132
func (ctx *Context) Abort(status int, body string) {
32-
//send an error
33+
ctx.Conn.StartResponse(status)
34+
ctx.Conn.WriteString(body)
35+
ctx.responseStarted = true
3336
}
3437

3538
//Sets a cookie -- duration is the amount of time in seconds. 0 = forever
@@ -49,7 +52,7 @@ func (ctx *Context) SetCookie(name string, value string, duration int64) {
4952
var sessionMap = make(map[string]*session)
5053

5154
func randomString(length int) string {
52-
pop := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw"
55+
pop := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
5356
var res bytes.Buffer
5457

5558
for i := 0; i < length; i++ {
@@ -65,19 +68,17 @@ type session struct {
6568
Id string
6669
}
6770

68-
func newSession () *session {
69-
s := session {
70-
Data : make(map[string]interface{}),
71-
Id: randomString(10),
72-
}
73-
74-
return &s
75-
}
71+
func newSession() *session {
72+
s := session{
73+
Data: make(map[string]interface{}),
74+
Id: randomString(10),
75+
}
7676

77-
func (s *session) save() {
78-
sessionMap[s.Id] = s;
77+
return &s
7978
}
8079

80+
func (s *session) save() { sessionMap[s.Id] = s }
81+
8182
var contextType reflect.Type
8283
var staticDir string
8384

@@ -147,11 +148,6 @@ func httpHandler(c *http.Conn, req *http.Request) {
147148
routeHandler(wreq, &conn)
148149
}
149150

150-
func error(conn Conn, code int, body string) {
151-
conn.StartResponse(code)
152-
conn.WriteString(body)
153-
}
154-
155151
func routeHandler(req *Request, conn Conn) {
156152
requestPath := req.URL.Path
157153

@@ -168,23 +164,23 @@ func routeHandler(req *Request, conn Conn) {
168164
log.Stderrf("Failed to parse form data %q", perr.String())
169165
}
170166

171-
//check the cookies for a session id
167+
//check the cookies for a session id
172168
perr = req.ParseCookies()
173169
if perr != nil {
174170
log.Stderrf("Failed to parse cookies %q", perr.String())
175171
}
176172

177-
s := newSession()
178-
179-
for k,v := range( req.Cookies ) {
180-
if k == sessionKey {
181-
if sess,ok := sessionMap[ v ]; ok {
182-
s = sess
183-
}
184-
}
185-
}
186-
187-
ctx := Context{req, s, conn}
173+
s := newSession()
174+
175+
for k, v := range (req.Cookies) {
176+
if k == sessionKey {
177+
if sess, ok := sessionMap[v]; ok {
178+
s = sess
179+
}
180+
}
181+
}
182+
183+
ctx := Context{req, s, conn, false}
188184

189185
//try to serve a static file
190186
staticFile := path.Join(staticDir, requestPath)
@@ -212,49 +208,54 @@ func routeHandler(req *Request, conn Conn) {
212208
continue
213209
}
214210

215-
var args vector.Vector;
211+
var args vector.Vector
216212

217213
handlerType := route.handler.Type().(*reflect.FuncType)
218-
219-
//check if the first arg in the handler is a context type
214+
215+
//check if the first arg in the handler is a context type
220216
if handlerType.NumIn() > 0 {
221-
if a0,ok := handlerType.In(0).(*reflect.PtrType); ok {
217+
if a0, ok := handlerType.In(0).(*reflect.PtrType); ok {
222218
typ := a0.Elem()
223219
if typ == contextType {
224-
args.Push( reflect.NewValue(&ctx) )
220+
args.Push(reflect.NewValue(&ctx))
225221
}
226222
}
227223
}
228224

229225
for _, arg := range match[1:] {
230-
args.Push( reflect.NewValue(arg) )
226+
args.Push(reflect.NewValue(arg))
231227
}
232228

233229
if len(args) != handlerType.NumIn() {
234230
log.Stderrf("Incorrect number of arguments for %s\n", requestPath)
235-
error(conn, 500, "Server Error")
231+
ctx.Abort(500, "Server Error")
236232
return
237233
}
238234

239-
valArgs := make( []reflect.Value, len(args) );
240-
for i,j := range(args) { valArgs[i] = j.(reflect.Value) };
235+
valArgs := make([]reflect.Value, len(args))
236+
for i, j := range (args) {
237+
valArgs[i] = j.(reflect.Value)
238+
}
241239
ret := route.handler.Call(valArgs)[0].(*reflect.StringValue).Get()
242-
243-
//check if session data is stored
244-
if len(s.Data) > 0 {
245-
s.save()
246-
//set the session for half an hour
247-
ctx.SetCookie(sessionKey, s.Id, 1800);
248-
}
249-
250-
conn.StartResponse(200)
251-
252-
conn.WriteString(ret)
240+
241+
if !ctx.responseStarted {
242+
//check if session data is stored
243+
if len(s.Data) > 0 {
244+
s.save()
245+
//set the session for half an hour
246+
ctx.SetCookie(sessionKey, s.Id, 1800)
247+
}
248+
249+
conn.StartResponse(200)
250+
ctx.responseStarted = true
251+
conn.WriteString(ret)
252+
}
253+
253254
return
254255
}
255256
}
256257

257-
error(conn, 404, "Page not found")
258+
ctx.Abort(404, "Page not found")
258259
}
259260

260261
//runs the web application and serves http requests

0 commit comments

Comments
 (0)