gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/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  	"gitee.com/liuxuezhan/go-micro-v1.18.0/api/resolver"
    11  )
    12  
    13  type Resolver struct{}
    14  
    15  var (
    16  	re = regexp.MustCompile("^v[0-9]+$")
    17  )
    18  
    19  func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
    20  	if req.URL.Path == "/" {
    21  		return nil, errors.New("unknown name")
    22  	}
    23  
    24  	parts := strings.Split(req.URL.Path[1:], "/")
    25  
    26  	if len(parts) == 1 {
    27  		return &resolver.Endpoint{
    28  			Name:   parts[0],
    29  			Host:   req.Host,
    30  			Method: req.Method,
    31  			Path:   req.URL.Path,
    32  		}, nil
    33  	}
    34  
    35  	// /v1/foo
    36  	if re.MatchString(parts[0]) {
    37  		return &resolver.Endpoint{
    38  			Name:   parts[1],
    39  			Host:   req.Host,
    40  			Method: req.Method,
    41  			Path:   req.URL.Path,
    42  		}, nil
    43  	}
    44  
    45  	return &resolver.Endpoint{
    46  		Name:   parts[0],
    47  		Host:   req.Host,
    48  		Method: req.Method,
    49  		Path:   req.URL.Path,
    50  	}, nil
    51  }
    52  
    53  func (r *Resolver) String() string {
    54  	return "path"
    55  }
    56  
    57  func NewResolver(opts ...resolver.Option) resolver.Resolver {
    58  	return &Resolver{}
    59  }