github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume3/section5/gopherface/middleware/contextexample.go (about)

     1  package middleware
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  )
     7  
     8  func newExampleContext(ctx context.Context, r *http.Request) context.Context {
     9  
    10  	fooID := r.Header.Get("X-Foo-ID")
    11  	if fooID == "" {
    12  		fooID = "bar"
    13  	}
    14  
    15  	return context.WithValue(ctx, "fooID", fooID)
    16  
    17  }
    18  
    19  func ContextExampleHandler(next http.Handler) http.Handler {
    20  
    21  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    22  
    23  		defer func() {
    24  
    25  			ctx := newExampleContext(r.Context(), r)
    26  			next.ServeHTTP(w, r.WithContext(ctx))
    27  
    28  		}()
    29  
    30  	})
    31  
    32  }