github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2013/go4python/decoex.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"bytes"
     7  	"fmt"
     8  	"io"
     9  	"log"
    10  	"net/http"
    11  )
    12  
    13  type errorHandler func(http.ResponseWriter, *http.Request) error
    14  
    15  func handleError(f errorHandler) http.HandlerFunc {
    16  	return func(w http.ResponseWriter, r *http.Request) {
    17  		err := f(w, r)
    18  		if err != nil {
    19  			log.Printf("%v", err)
    20  			http.Error(w, "Oops!", http.StatusInternalServerError)
    21  		}
    22  	}
    23  }
    24  
    25  func handler(w http.ResponseWriter, r *http.Request) error {
    26  	name := r.FormValue("name")
    27  	if name == "" {
    28  		return fmt.Errorf("empty name")
    29  	}
    30  	fmt.Fprintln(w, "Hi,", name)
    31  	return nil
    32  }
    33  
    34  // resp implements http.ResponseWriter writing
    35  type dummyResp struct {
    36  	io.Writer
    37  	h int
    38  }
    39  
    40  func newDummyResp() http.ResponseWriter {
    41  	return &dummyResp{Writer: &bytes.Buffer{}}
    42  }
    43  
    44  func (w *dummyResp) Header() http.Header { return make(http.Header) }
    45  func (w *dummyResp) WriteHeader(h int)   { w.h = h }
    46  func (w *dummyResp) String() string      { return fmt.Sprintf("[%v] %q", w.h, w.Writer) }
    47  
    48  func main() {
    49  	http.HandleFunc("/hi", handleError(handler))
    50  
    51  	// ListenAndServe is not allowed on the playground.
    52  	// http.ListenAndServe(":8080", nil)
    53  
    54  	// In the playground we call the handler manually with dummy requests.
    55  
    56  	// Fake request without 'name' parameter.
    57  	r := &http.Request{}
    58  	w := newDummyResp()
    59  	handleError(handler)(w, r)
    60  	fmt.Println("resp a:", w)
    61  
    62  	// Fake request with 'name' parameter 'john'.
    63  	r.Form["name"] = []string{"john"}
    64  	w = newDummyResp()
    65  	handleError(handler)(w, r)
    66  	fmt.Println("resp b:", w)
    67  
    68  }