github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/api/resolver/vpath/vpath.go (about) 1 // Copyright 2020 Asim Aslam 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // Original source: github.com/micro/go-micro/v3/api/resolver/vpath/vpath.go 16 17 // Package vpath resolves using http path and recognised versioned urls 18 package vpath 19 20 import ( 21 "errors" 22 "net/http" 23 "regexp" 24 "strings" 25 26 "github.com/tickoalcantara12/micro/v3/service/api/resolver" 27 ) 28 29 func NewResolver(opts ...resolver.Option) resolver.Resolver { 30 return &Resolver{opts: resolver.NewOptions(opts...)} 31 } 32 33 type Resolver struct { 34 opts resolver.Options 35 } 36 37 var ( 38 re = regexp.MustCompile("^v[0-9]+$") 39 ) 40 41 func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { 42 if req.URL.Path == "/" { 43 return nil, errors.New("unknown name") 44 } 45 46 options := resolver.NewResolveOptions(opts...) 47 48 parts := strings.Split(req.URL.Path[1:], "/") 49 if len(parts) == 1 { 50 return &resolver.Endpoint{ 51 Name: r.withPrefix(parts...), 52 Host: req.Host, 53 Method: req.Method, 54 Path: req.URL.Path, 55 Domain: options.Domain, 56 }, nil 57 } 58 59 // /v1/foo 60 if re.MatchString(parts[0]) { 61 return &resolver.Endpoint{ 62 Name: r.withPrefix(parts[0:2]...), 63 Host: req.Host, 64 Method: req.Method, 65 Path: req.URL.Path, 66 Domain: options.Domain, 67 }, nil 68 } 69 70 return &resolver.Endpoint{ 71 Name: r.withPrefix(parts[0]), 72 Host: req.Host, 73 Method: req.Method, 74 Path: req.URL.Path, 75 Domain: options.Domain, 76 }, nil 77 } 78 79 func (r *Resolver) String() string { 80 return "path" 81 } 82 83 // withPrefix transforms "foo" into "go.micro.api.foo" 84 func (r *Resolver) withPrefix(parts ...string) string { 85 p := r.opts.ServicePrefix 86 if len(p) > 0 { 87 parts = append([]string{p}, parts...) 88 } 89 90 return strings.Join(parts, ".") 91 }