-
Notifications
You must be signed in to change notification settings - Fork 0
/
ngrok.go
94 lines (86 loc) · 2.19 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
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
"github.com/ngrok/ngrok-api-go/v5"
"github.com/ngrok/ngrok-api-go/v5/tunnels"
)
func Getenv(key, val string) string {
s := os.Getenv(key)
if s == "" {
return val
}
return s
}
func ngrokWeb() (publicURL string, forwardsTo string, err error) {
web_addr := Getenv("web_addr", "localhost:4040")
var client struct {
Tunnels []struct {
// Name string `json:"name"`
// ID string `json:"ID"`
// URI string `json:"uri"`
PublicURL string `json:"public_url"`
// Proto string `json:"proto"`
Config struct {
Addr string `json:"addr"`
// Inspect bool `json:"inspect"`
} `json:"config"`
} `json:"tunnels"`
// URI string `json:"uri"`
}
resp, err := http.Get("http://" + web_addr + "/api/tunnels")
if err != nil {
return "", "", srcError(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
err = fmt.Errorf("http.Get resp.StatusCode: %v", resp.StatusCode)
return "", "", Errorf("http.Get resp.StatusCode: %v", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", "", srcError(err)
}
err = json.Unmarshal(body, &client)
if err != nil {
return "", "", srcError(err)
}
for _, tunnel := range client.Tunnels {
if true { //free version allow only one tunnel
return tunnel.PublicURL, tunnel.Config.Addr, nil
}
}
return "", "", Errorf("not found online client")
}
// get ngrok info of first tunnel
func ngrokAPI(NGROK_API_KEY string) (publicURL, forwardsTo string, er error) {
if NGROK_API_KEY == "" {
return "", "", Errorf("empty NGROK_API_KEY")
}
// construct the api client
clientConfig := ngrok.NewClientConfig(NGROK_API_KEY)
// list all online client
client := tunnels.NewClient(clientConfig)
iter := client.List(nil)
err := iter.Err()
if err != nil {
return "", "", srcError(err)
}
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().ForwardsTo, nil
}
err = iter.Err()
if err != nil {
return "", "", srcError(err)
} else {
return "", "", Errorf("not found online client")
}
}