-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
64 lines (58 loc) · 1.34 KB
/
main.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
package main
import (
"context"
"fmt"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/gojekfarm/iap_auth/config"
"github.com/gojekfarm/iap_auth/pkg/iap"
"github.com/gojekfarm/iap_auth/pkg/logger"
"github.com/gojekfarm/iap_auth/pkg/proxy"
"golang.org/x/oauth2"
)
func main() {
cfg, err := config.Load()
logger.SetupLogger(cfg.LoggerLevel)
logger.Debugf("refresh time is %s", cfg.RefreshTimeSeconds)
tickPeriod, err := time.ParseDuration(cfg.RefreshTimeSeconds)
if err != nil {
logger.Errorf("Error parsing refresh time duration %s", err.Error())
return
}
ticker := time.NewTicker(tickPeriod)
var mu sync.Mutex
var atomictoken atomic.Value
hc := oauth2.NewClient(context.Background(), nil)
var tokenfn = func() string {
logger.Debugf("refreshing token now")
iap, err := iap.New(hc, cfg.ServiceAccountCredentials, cfg.ClientID)
if err != nil {
return "INVALID"
}
token, err := iap.Token()
if err != nil {
return "INVALID"
}
return token
}
atomictoken.Store(tokenfn())
go func() {
for range ticker.C {
mu.Lock()
atomictoken.Store(tokenfn())
mu.Unlock()
}
}()
p, err := proxy.New(cfg.IapHost, &atomictoken)
if err != nil {
logger.Errorf("Error creating a proxy %s", err.Error())
return
}
server := &http.Server{
Addr: fmt.Sprintf(":%s", cfg.Port),
Handler: p,
}
server.ListenAndServe()
}