error3.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // This file contains the code snippets included in "Error Handling and Go."
  5. package main
  6. import (
  7. "net/http"
  8. "text/template"
  9. )
  10. func init() {
  11. http.Handle("/view", appHandler(viewRecord))
  12. }
  13. // STOP OMIT
  14. func viewRecord(w http.ResponseWriter, r *http.Request) error {
  15. c := appengine.NewContext(r)
  16. key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil)
  17. record := new(Record)
  18. if err := datastore.Get(c, key, record); err != nil {
  19. return err
  20. }
  21. return viewTemplate.Execute(w, record)
  22. }
  23. // STOP OMIT
  24. type appHandler func(http.ResponseWriter, *http.Request) error
  25. func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  26. if err := fn(w, r); err != nil {
  27. http.Error(w, err.Error(), http.StatusInternalServerError)
  28. }
  29. }
  30. // STOP OMIT
  31. type ap struct{}
  32. func (ap) NewContext(*http.Request) *ctx { return nil }
  33. type ctx struct{}
  34. func (*ctx) Errorf(string, ...interface{}) {}
  35. var appengine ap
  36. type ds struct{}
  37. func (ds) NewKey(*ctx, string, string, int, *int) string { return "" }
  38. func (ds) Get(*ctx, string, *Record) error { return nil }
  39. var datastore ds
  40. type Record struct{}
  41. var viewTemplate *template.Template
  42. func main() {}