-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathngrok_proxy.go
60 lines (45 loc) · 1.24 KB
/
ngrok_proxy.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
package slss
import (
"bytes"
"os/exec"
"strings"
"time"
"github.com/pkg/errors"
)
// Proxy types
const (
ProxyProtoHTTP = "http"
ProxyProtoHTTPS = "https"
ProxyProtoTCP = "tcp"
ngrokBinPath = "./bin/ngrok"
)
// StartNgrokProxy starts the ngrok proxy
func StartNgrokProxy(config *ngrokConfig, protoType, port string) (string, error) {
if err := authNgrok(config.AuthToken); err != nil {
return "", errors.WithStack(err)
}
return start(protoType, port)
}
func authNgrok(authToken string) error {
cmd := exec.Command(ngrokBinPath, "authtoken", authToken)
return cmd.Run()
}
func start(proxyType, port string) (string, error) {
var responseMessage bytes.Buffer
cmd := exec.Command(ngrokBinPath, proxyType, port, "-log=stdout", "--log-level=debug", "--region=ap")
cmd.Stdout = &responseMessage
if err := cmd.Start(); err != nil {
return "", errors.WithStack(err)
}
go cmd.Wait()
var proxyTypePrefix = proxyType + "://"
for range time.Tick(time.Second) {
output := responseMessage.String()
if !strings.Contains(output, proxyTypePrefix) {
continue
}
i := strings.LastIndex(output, proxyTypePrefix)
return output[i+len(proxyTypePrefix) : i+strings.Index(output[i:], " ")], nil
}
return "", errors.New("unreachable")
}