-
Notifications
You must be signed in to change notification settings - Fork 59
/
service.go
67 lines (56 loc) · 1.88 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package proxy
import (
"errors"
"fmt"
"net/url"
"strings"
)
// Service holds the details of the service (Name and URL)
type Service struct {
Name string
URL *url.URL
}
// NewService creates a new service from a name and a URL
func NewService(name string, rawURL string) (Service, error) {
if name == "" || rawURL == "" {
return Service{}, errors.New("Name and URL are required")
}
if strings.Contains(name, "://") || strings.Contains(name, ":") {
return Service{}, fmt.Errorf("Name '%v' is invalid, it can't be an URL", name)
}
url, err := url.ParseRequestURI(rawURL)
isInvalidHostname := len(url.Hostname()) == 0 || strings.Contains(url.Hostname(), ":")
if err != nil || isInvalidHostname {
return Service{}, fmt.Errorf("URL '%v' is invalid, example of valid URL 'http://example.com:8080'", rawURL)
}
return Service{Name: name, URL: url}, nil
}
// Empty service means no name or no url
func (s Service) Empty() bool {
return s.Name == "" || s.URL == nil
}
// String returns a string representation of the service
// Example:
// Service{Name: "test", URL: "http://localhost:8080"}
// produces the string "test http://localhost:8080"
func (s Service) String() string {
return s.Name + " " + s.URL.String()
}
// GetOriginalURL returns the original URL of the service
func (s Service) GetOriginalURL() *url.URL {
return s.URL
}
// GetServiceURL returns the local URL to be used
// by the proxy server to redirect all request to the service
func (s Service) GetServiceURL(localTLD string) string {
return fmt.Sprintf("%s://%s%s", s.URL.Scheme, s.Name, localTLD)
}
// UnsafeNewService creates a new service from a name and a URL
// without checking if the URL is valid. Must only be used in tests
func UnsafeNewService(name string, rawURL string) Service {
url, err := url.Parse(rawURL)
if err != nil {
fmt.Printf("Invalid URL %s", rawURL)
}
return Service{Name: name, URL: url}
}