82 lines
1.6 KiB
Go
82 lines
1.6 KiB
Go
package tunnelbroker
|
|
|
|
import (
|
|
`fmt`
|
|
`runtime`
|
|
`strings`
|
|
|
|
`github.com/go-resty/resty/v2`
|
|
`golang.org/x/text/cases`
|
|
`golang.org/x/text/language`
|
|
`r00t2.io/gobroke/conf`
|
|
`r00t2.io/gobroke/version`
|
|
)
|
|
|
|
// GetTunnel returns a tunnel configuration from tunnelbroker.net.
|
|
func GetTunnel(cfg *conf.Tunnel, debug bool) (tun *Tunnel, err error) {
|
|
|
|
var tuns TunnelList
|
|
var resp *resty.Response
|
|
var req *resty.Request
|
|
var client *resty.Client
|
|
|
|
// Set up the client. Namely the UA.
|
|
client = resty.New()
|
|
client.SetDebug(debug)
|
|
client.SetHeader(
|
|
"User-Agent",
|
|
fmt.Sprintf(
|
|
"GoBroke/%s go-resty/%s Go/%s "+
|
|
"(%s %s) "+
|
|
"(https://pkg.go.dev/r00t2.io/gobroke)",
|
|
version.Ver.Short(), resty.Version, runtime.Version(),
|
|
cases.Title(language.English).String(runtime.GOOS), runtime.GOARCH,
|
|
),
|
|
)
|
|
|
|
req = client.R()
|
|
req.SetResult(&tuns)
|
|
req.SetBasicAuth(*cfg.Username, cfg.UpdateKey)
|
|
req.SetQueryParam(infoTidParam, fmt.Sprintf("%d", cfg.TunnelID))
|
|
|
|
if resp, err = req.Get(infoBaseUrl); err != nil {
|
|
return
|
|
}
|
|
if !resp.IsSuccess() {
|
|
err = respToErr(resp)
|
|
return
|
|
}
|
|
if strings.HasPrefix(resp.String(), tunRespNoTuns) {
|
|
err = ErrHENoTuns
|
|
return
|
|
}
|
|
|
|
tun = tuns.Tunnels[0]
|
|
tun.client = client
|
|
tun.TunCfg = cfg
|
|
|
|
return
|
|
}
|
|
|
|
// respToErr returns an HTTPError from a resty.Response. err will be nill if the response was a success.
|
|
func respToErr(resp *resty.Response) (err *HTTPError) {
|
|
|
|
if resp.IsSuccess() {
|
|
return
|
|
}
|
|
|
|
err = &HTTPError{
|
|
Code: resp.StatusCode(),
|
|
CodeStr: resp.Status(),
|
|
Message: nil,
|
|
Resp: resp,
|
|
}
|
|
|
|
if resp.String() != "" {
|
|
err.Message = new(string)
|
|
*err.Message = resp.String()
|
|
}
|
|
|
|
return
|
|
}
|