github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/plugins/prefix/prefix.go (about)

     1  // Package prefix is a micro plugin for stripping a path prefix
     2  package prefix
     3  
     4  import (
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/micro/cli/v2"
     9  	"github.com/micro/micro/v2/plugin"
    10  )
    11  
    12  type prefix struct {
    13  	p []string
    14  }
    15  
    16  func (p *prefix) Flags() []cli.Flag {
    17  	return []cli.Flag{
    18  		&cli.StringFlag{
    19  			Name:    "path_prefix",
    20  			Usage:   "Comma separated list of path prefixes to strip before continuing with request e.g /api,/foo,/bar",
    21  			EnvVars: []string{"PATH_PREFIX"},
    22  		},
    23  	}
    24  }
    25  
    26  func (p *prefix) Commands() []*cli.Command {
    27  	return nil
    28  }
    29  
    30  func (p *prefix) Handler() plugin.Handler {
    31  	return func(h http.Handler) http.Handler {
    32  		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    33  			// strip prefix if we have a match
    34  			for _, prefix := range p.p {
    35  				if strings.HasPrefix(r.URL.Path, prefix) {
    36  					r.URL.Path = strings.TrimPrefix(r.URL.Path, prefix)
    37  					break
    38  				}
    39  			}
    40  			// serve request
    41  			h.ServeHTTP(w, r)
    42  		})
    43  	}
    44  }
    45  
    46  func (p *prefix) Init(ctx *cli.Context) error {
    47  	if prefix := ctx.String("path_prefix"); len(prefix) > 0 {
    48  		p.p = append(p.p, strings.Split(prefix, ",")...)
    49  	}
    50  	return nil
    51  }
    52  
    53  func (p *prefix) String() string {
    54  	return "prefix"
    55  }
    56  
    57  func NewPlugin(prefixes ...string) plugin.Plugin {
    58  	return &prefix{prefixes}
    59  }