-
Notifications
You must be signed in to change notification settings - Fork 0
/
ngrok.go
83 lines (69 loc) · 1.88 KB
/
ngrok.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"context"
"errors"
"os"
"time"
"github.com/ngrok/ngrok-api-go/v5"
"github.com/ngrok/ngrok-api-go/v5/tunnel_sessions"
"github.com/ngrok/ngrok-api-go/v5/tunnels"
)
var (
ErrNgrokOnlineNoTunnel = errors.New("not found online client")
ErrEmptyNgrokApiKey = errors.New("empty NGROK_API_KEY")
)
func Getenv(key, val string) string {
s := os.Getenv(key)
if s == "" {
return val
}
return s
}
// get publicURL and metadata of first tunnel by NGROK_API_KEY
func ngrokGet(NGROK_API_KEY string) (publicURL, metadata string, err error) {
if NGROK_API_KEY == "" {
return "", "", srcError(ErrEmptyNgrokApiKey)
}
// construct the api client
clientConfig := ngrok.NewClientConfig(NGROK_API_KEY)
// construct the tunnels client
client := tunnels.NewClient(clientConfig)
// list all online client
iter := client.List(nil)
ctx, ca := context.WithTimeout(context.Background(), time.Second*3)
defer ca()
//free version allow only one tunnel
if iter.Next(ctx) {
return iter.Item().PublicURL, iter.Item().Metadata, nil
}
err = iter.Err()
if err != nil {
return "", "", srcError(err)
}
return "", "", srcError(ErrNgrokOnlineNoTunnel)
}
// restart first tunnel sessions by NGROK_API_KEY
func ngrokRestart(NGROK_API_KEY string) (id string, err error) {
if NGROK_API_KEY == "" {
return "", srcError(ErrEmptyNgrokApiKey)
}
// construct the api client
clientConfig := ngrok.NewClientConfig(NGROK_API_KEY)
// construct the tunnel_sessions client
client := tunnel_sessions.NewClient(clientConfig)
// list all online tClient
iter := client.List(nil)
ctx, ca := context.WithTimeout(context.Background(), time.Second*3)
defer ca()
//free version allow only one tunnel
if iter.Next(ctx) {
id = iter.Item().ID
err = client.Restart(ctx, id)
return
}
err = iter.Err()
if err != nil {
return "", srcError(err)
}
return "", srcError(ErrNgrokOnlineNoTunnel)
}