github.com/zach-klippenstein/go@v0.0.0-20150108044943-fcfbeb3adf58/doc/progs/error3.go (about) 1 // compile 2 3 // Copyright 2011 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 // This file contains the code snippets included in "Error Handling and Go." 8 9 package main 10 11 import ( 12 "net/http" 13 "text/template" 14 ) 15 16 func init() { 17 http.Handle("/view", appHandler(viewRecord)) 18 } 19 20 // STOP OMIT 21 22 func viewRecord(w http.ResponseWriter, r *http.Request) error { 23 c := appengine.NewContext(r) 24 key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil) 25 record := new(Record) 26 if err := datastore.Get(c, key, record); err != nil { 27 return err 28 } 29 return viewTemplate.Execute(w, record) 30 } 31 32 // STOP OMIT 33 34 type appHandler func(http.ResponseWriter, *http.Request) error 35 36 func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 37 if err := fn(w, r); err != nil { 38 http.Error(w, err.Error(), 500) 39 } 40 } 41 42 // STOP OMIT 43 44 type ap struct{} 45 46 func (ap) NewContext(*http.Request) *ctx { return nil } 47 48 type ctx struct{} 49 50 func (*ctx) Errorf(string, ...interface{}) {} 51 52 var appengine ap 53 54 type ds struct{} 55 56 func (ds) NewKey(*ctx, string, string, int, *int) string { return "" } 57 func (ds) Get(*ctx, string, *Record) error { return nil } 58 59 var datastore ds 60 61 type Record struct{} 62 63 var viewTemplate *template.Template 64 65 func main() {}