-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathportal_client.go
More file actions
88 lines (77 loc) · 2.04 KB
/
Copy pathportal_client.go
File metadata and controls
88 lines (77 loc) · 2.04 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"sync"
"time"
)
type LeaseMetadata struct {
Description string `json:"description,omitempty"`
Owner string `json:"owner,omitempty"`
Thumbnail string `json:"thumbnail,omitempty"`
Tags []string `json:"tags,omitempty"`
Hide bool `json:"hide,omitempty"`
}
type Lease struct {
Name string `json:"name,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
FirstSeenAt time.Time `json:"first_seen_at"`
LastSeenAt time.Time `json:"last_seen_at"`
Hostname string `json:"hostname"`
UDPEnabled bool `json:"udp_enabled"`
TCPEnabled bool `json:"tcp_enabled"`
TCPAddr string `json:"tcp_addr"`
Metadata LeaseMetadata `json:"metadata"`
Ready int `json:"ready"`
}
type PortalClient struct {
baseURL string
httpClient *http.Client
cache []Lease
cacheMu sync.RWMutex
cacheTime time.Time
cacheTTL time.Duration
}
func NewPortalClient(baseURL string) *PortalClient {
if baseURL == "" {
baseURL = os.Getenv("PORTAL_API_URL")
}
if baseURL == "" {
baseURL = "http://localhost:4017"
}
return &PortalClient{
baseURL: baseURL,
httpClient: &http.Client{Timeout: 10 * time.Second},
cacheTTL: 15 * time.Second,
}
}
func (c *PortalClient) GetLeases() ([]Lease, error) {
c.cacheMu.RLock()
if time.Since(c.cacheTime) < c.cacheTTL && c.cache != nil {
leases := make([]Lease, len(c.cache))
copy(leases, c.cache)
c.cacheMu.RUnlock()
return leases, nil
}
c.cacheMu.RUnlock()
resp, err := c.httpClient.Get(c.baseURL + "/api/leases")
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)
}
var leases []Lease
if err := json.NewDecoder(resp.Body).Decode(&leases); err != nil {
return nil, err
}
c.cacheMu.Lock()
c.cache = make([]Lease, len(leases))
copy(c.cache, leases)
c.cacheTime = time.Now()
c.cacheMu.Unlock()
return leases, nil
}