github.com/cortesi/devd@v0.0.0-20200427000907-c1a3bfba27d8/httpctx/httpctx.go (about)

     1  // Package httpctx provides a context-aware HTTP handler adaptor
     2  package httpctx
     3  
     4  import (
     5  	"net/http"
     6  	"strings"
     7  
     8  	"golang.org/x/net/context"
     9  )
    10  
    11  // Handler is a request handler with an added context
    12  type Handler interface {
    13  	ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request)
    14  }
    15  
    16  // A HandlerFunc is an adaptor to turn a function in to a Handler
    17  type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request)
    18  
    19  // ServeHTTPContext calls the underlying handler function
    20  func (h HandlerFunc) ServeHTTPContext(
    21  	ctx context.Context, rw http.ResponseWriter, req *http.Request,
    22  ) {
    23  	h(ctx, rw, req)
    24  }
    25  
    26  // Adapter turns a context.Handler to an http.Handler
    27  type Adapter struct {
    28  	Ctx     context.Context
    29  	Handler Handler
    30  }
    31  
    32  func (ca *Adapter) ServeHTTP(
    33  	rw http.ResponseWriter, req *http.Request,
    34  ) {
    35  	ca.Handler.ServeHTTPContext(ca.Ctx, rw, req)
    36  }
    37  
    38  // StripPrefix strips a prefix from the request URL
    39  func StripPrefix(prefix string, h Handler) Handler {
    40  	if prefix == "" {
    41  		return h
    42  	}
    43  	return HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
    44  		if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
    45  			r.URL.Path = p
    46  			h.ServeHTTPContext(ctx, w, r)
    47  		}
    48  	})
    49  }