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

     1  // +build ignore,OMIT
     2  
     3  package bestpractices
     4  
     5  import (
     6  	"fmt"
     7  	"log"
     8  	"net/http"
     9  )
    10  
    11  func doThis() error { return nil }
    12  func doThat() error { return nil }
    13  
    14  // HANDLER1 OMIT
    15  func init() {
    16  	http.HandleFunc("/", handler)
    17  }
    18  
    19  func handler(w http.ResponseWriter, r *http.Request) {
    20  	err := doThis()
    21  	if err != nil {
    22  		http.Error(w, err.Error(), http.StatusInternalServerError)
    23  		log.Printf("handling %q: %v", r.RequestURI, err)
    24  		return
    25  	}
    26  
    27  	err = doThat()
    28  	if err != nil {
    29  		http.Error(w, err.Error(), http.StatusInternalServerError)
    30  		log.Printf("handling %q: %v", r.RequestURI, err)
    31  		return
    32  	}
    33  }
    34  
    35  // HANDLER2 OMIT
    36  func init() {
    37  	http.HandleFunc("/", errorHandler(betterHandler))
    38  }
    39  
    40  func errorHandler(f func(http.ResponseWriter, *http.Request) error) http.HandlerFunc {
    41  	return func(w http.ResponseWriter, r *http.Request) {
    42  		err := f(w, r)
    43  		if err != nil {
    44  			http.Error(w, err.Error(), http.StatusInternalServerError)
    45  			log.Printf("handling %q: %v", r.RequestURI, err)
    46  		}
    47  	}
    48  }
    49  
    50  func betterHandler(w http.ResponseWriter, r *http.Request) error {
    51  	if err := doThis(); err != nil {
    52  		return fmt.Errorf("doing this: %v", err)
    53  	}
    54  
    55  	if err := doThat(); err != nil {
    56  		return fmt.Errorf("doing that: %v", err)
    57  	}
    58  	return nil
    59  }
    60  
    61  // END OMIT