github.com/huandu/go@v0.0.0-20151114150818-04e615e41150/doc/progs/error2.go (about)

     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.HandleFunc("/view", viewRecord)
    16  }
    17  
    18  func viewRecord(w http.ResponseWriter, r *http.Request) {
    19  	c := appengine.NewContext(r)
    20  	key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil)
    21  	record := new(Record)
    22  	if err := datastore.Get(c, key, record); err != nil {
    23  		http.Error(w, err.Error(), 500)
    24  		return
    25  	}
    26  	if err := viewTemplate.Execute(w, record); err != nil {
    27  		http.Error(w, err.Error(), 500)
    28  	}
    29  }
    30  
    31  // STOP OMIT
    32  
    33  type ap struct{}
    34  
    35  func (ap) NewContext(*http.Request) *ctx { return nil }
    36  
    37  type ctx struct{}
    38  
    39  func (*ctx) Errorf(string, ...interface{}) {}
    40  
    41  var appengine ap
    42  
    43  type ds struct{}
    44  
    45  func (ds) NewKey(*ctx, string, string, int, *int) string { return "" }
    46  func (ds) Get(*ctx, string, *Record) error               { return nil }
    47  
    48  var datastore ds
    49  
    50  type Record struct{}
    51  
    52  var viewTemplate *template.Template
    53  
    54  func main() {}