github.com/btccom/go-micro/v2@v2.9.3/api/resolver/vpath/vpath.go (about)

     1  // Package vpath resolves using http path and recognised versioned urls
     2  package vpath
     3  
     4  import (
     5  	"errors"
     6  	"net/http"
     7  	"regexp"
     8  	"strings"
     9  
    10  	"github.com/btccom/go-micro/v2/api/resolver"
    11  )
    12  
    13  func NewResolver(opts ...resolver.Option) resolver.Resolver {
    14  	return &Resolver{opts: resolver.NewOptions(opts...)}
    15  }
    16  
    17  type Resolver struct {
    18  	opts resolver.Options
    19  }
    20  
    21  var (
    22  	re = regexp.MustCompile("^v[0-9]+$")
    23  )
    24  
    25  func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
    26  	if req.URL.Path == "/" {
    27  		return nil, errors.New("unknown name")
    28  	}
    29  
    30  	parts := strings.Split(req.URL.Path[1:], "/")
    31  	if len(parts) == 1 {
    32  		return &resolver.Endpoint{
    33  			Name:   r.withNamespace(req, parts...),
    34  			Host:   req.Host,
    35  			Method: req.Method,
    36  			Path:   req.URL.Path,
    37  		}, nil
    38  	}
    39  
    40  	// /v1/foo
    41  	if re.MatchString(parts[0]) {
    42  		return &resolver.Endpoint{
    43  			Name:   r.withNamespace(req, parts[0:2]...),
    44  			Host:   req.Host,
    45  			Method: req.Method,
    46  			Path:   req.URL.Path,
    47  		}, nil
    48  	}
    49  
    50  	return &resolver.Endpoint{
    51  		Name:   r.withNamespace(req, parts[0]),
    52  		Host:   req.Host,
    53  		Method: req.Method,
    54  		Path:   req.URL.Path,
    55  	}, nil
    56  }
    57  
    58  func (r *Resolver) String() string {
    59  	return "path"
    60  }
    61  
    62  func (r *Resolver) withNamespace(req *http.Request, parts ...string) string {
    63  	ns := r.opts.Namespace(req)
    64  	if len(ns) == 0 {
    65  		return strings.Join(parts, ".")
    66  	}
    67  
    68  	return strings.Join(append([]string{ns}, parts...), ".")
    69  }