Source file
doc/progs/error4.go
1
2
3
4
5
6
7 package main
8
9 import (
10 "net/http"
11 "text/template"
12 )
13
14 type appError struct {
15 Error error
16 Message string
17 Code int
18 }
19
20
21
22 type appHandler func(http.ResponseWriter, *http.Request) *appError
23
24 func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
25 if e := fn(w, r); e != nil {
26 c := appengine.NewContext(r)
27 c.Errorf("%v", e.Error)
28 http.Error(w, e.Message, e.Code)
29 }
30 }
31
32
33
34 func viewRecord(w http.ResponseWriter, r *http.Request) *appError {
35 c := appengine.NewContext(r)
36 key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil)
37 record := new(Record)
38 if err := datastore.Get(c, key, record); err != nil {
39 return &appError{err, "Record not found", 404}
40 }
41 if err := viewTemplate.Execute(w, record); err != nil {
42 return &appError{err, "Can't display record", 500}
43 }
44 return nil
45 }
46
47
48
49 func init() {
50 http.Handle("/view", appHandler(viewRecord))
51 }
52
53 type ap struct{}
54
55 func (ap) NewContext(*http.Request) *ctx { return nil }
56
57 type ctx struct{}
58
59 func (*ctx) Errorf(string, ...interface{}) {}
60
61 var appengine ap
62
63 type ds struct{}
64
65 func (ds) NewKey(*ctx, string, string, int, *int) string { return "" }
66 func (ds) Get(*ctx, string, *Record) error { return nil }
67
68 var datastore ds
69
70 type Record struct{}
71
72 var viewTemplate *template.Template
73
74 func main() {}
75
View as plain text