Source file doc/progs/error3.go

     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  
     5  // This file contains the code snippets included in "Error Handling and Go."
     6  
     7  package main
     8  
     9  import (
    10  	"net/http"
    11  	"text/template"
    12  )
    13  
    14  func init() {
    15  	http.Handle("/view", appHandler(viewRecord))
    16  }
    17  
    18  // STOP OMIT
    19  
    20  func viewRecord(w http.ResponseWriter, r *http.Request) error {
    21  	c := appengine.NewContext(r)
    22  	key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil)
    23  	record := new(Record)
    24  	if err := datastore.Get(c, key, record); err != nil {
    25  		return err
    26  	}
    27  	return viewTemplate.Execute(w, record)
    28  }
    29  
    30  // STOP OMIT
    31  
    32  type appHandler func(http.ResponseWriter, *http.Request) error
    33  
    34  func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    35  	if err := fn(w, r); err != nil {
    36  		http.Error(w, err.Error(), http.StatusInternalServerError)
    37  	}
    38  }
    39  
    40  // STOP OMIT
    41  
    42  type ap struct{}
    43  
    44  func (ap) NewContext(*http.Request) *ctx { return nil }
    45  
    46  type ctx struct{}
    47  
    48  func (*ctx) Errorf(string, ...interface{}) {}
    49  
    50  var appengine ap
    51  
    52  type ds struct{}
    53  
    54  func (ds) NewKey(*ctx, string, string, int, *int) string { return "" }
    55  func (ds) Get(*ctx, string, *Record) error               { return nil }
    56  
    57  var datastore ds
    58  
    59  type Record struct{}
    60  
    61  var viewTemplate *template.Template
    62  
    63  func main() {}
    64  

View as plain text