github.com/kaydxh/golang@v0.0.131/tutorial/programming_paradigm/decorator_test.go (about)

     1  package tutorial
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  	"testing"
     8  )
     9  
    10  //http 中间件采用修饰器编程规范
    11  type HttpHandlerDecorator func(http.HandlerFunc) http.HandlerFunc
    12  
    13  func Handler(h http.HandlerFunc, decors ...HttpHandlerDecorator) http.HandlerFunc {
    14  	for i := range decors {
    15  		d := decors[len(decors)-1-i] // iterate in reverse
    16  		h = d(h)
    17  	}
    18  	return h
    19  }
    20  
    21  func WithServerHeader(h http.HandlerFunc) http.HandlerFunc {
    22  	return func(w http.ResponseWriter, r *http.Request) {
    23  		log.Println("--->WithServerHeader()")
    24  		w.Header().Set("Server", "HelloServer v0.0.1")
    25  		h(w, r)
    26  	}
    27  }
    28  
    29  func WithAuthCookie(h http.HandlerFunc) http.HandlerFunc {
    30  	return func(w http.ResponseWriter, r *http.Request) {
    31  		log.Println("--->WithAuthCookie()")
    32  		cookie := &http.Cookie{Name: "Auth", Value: "Pass", Path: "/"}
    33  		http.SetCookie(w, cookie)
    34  		h(w, r)
    35  	}
    36  }
    37  
    38  func WithBasicAuth(h http.HandlerFunc) http.HandlerFunc {
    39  	return func(w http.ResponseWriter, r *http.Request) {
    40  		log.Println("--->WithBasicAuth()")
    41  		//cookie, _ := r.Cookie("Auth")
    42  
    43  		/*
    44  			if err != nil || cookie.Value != "Pass" {
    45  				w.WriteHeader(http.StatusForbidden)
    46  				return
    47  			}
    48  		*/
    49  		h(w, r)
    50  	}
    51  }
    52  
    53  func WithDebugLog(h http.HandlerFunc) http.HandlerFunc {
    54  	return func(w http.ResponseWriter, r *http.Request) {
    55  		log.Println("--->WithDebugLog")
    56  		r.ParseForm()
    57  		/*
    58  					log.Println(r.Form)
    59  			//		log.Println("path", r.URL.Path)
    60  			//		log.Println("scheme", r.URL.Scheme)
    61  			//		log.Println(r.Form["url_long"])
    62  					for k, v := range r.Form {
    63  						log.Println("key:", k)
    64  						log.Println("val:", strings.Join(v, ""))
    65  					}
    66  		*/
    67  		h(w, r)
    68  	}
    69  }
    70  
    71  //handler function
    72  func hello(w http.ResponseWriter, r *http.Request) {
    73  	log.Printf("Recieved Request %s from %s\n", r.URL.Path, r.RemoteAddr)
    74  	fmt.Fprintf(w, "Hello, World! "+r.URL.Path)
    75  }
    76  
    77  func TestHttpMiddleware(t *testing.T) {
    78  	http.HandleFunc("/v4/hello", Handler(hello,
    79  		WithServerHeader, WithBasicAuth, WithDebugLog))
    80  	err := http.ListenAndServe(":8080", nil)
    81  	if err != nil {
    82  		log.Fatal("ListenAndServe: ", err)
    83  	}
    84  
    85  }