lotus/cli/util/apiinfo.go

104 lines
1.8 KiB
Go
Raw Normal View History

2020-10-09 00:57:41 +00:00
package cliutil
import (
"net/http"
"net/url"
"regexp"
"strings"
logging "github.com/ipfs/go-log/v2"
"github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
)
var log = logging.Logger("cliutil")
var (
infoWithToken = regexp.MustCompile("^[a-zA-Z0-9\\-_]+?\\.[a-zA-Z0-9\\-_]+?\\.([a-zA-Z0-9\\-_]+)?:.+$")
)
type APIInfo struct {
Addr string
Token []byte
}
func ParseApiInfo(s string) APIInfo {
var tok []byte
2022-09-27 16:08:04 +00:00
2020-10-09 00:57:41 +00:00
if infoWithToken.Match([]byte(s)) {
sp := strings.SplitN(s, ":", 2)
tok = []byte(sp[0])
s = sp[1]
}
return APIInfo{
Addr: s,
Token: tok,
}
}
2022-09-27 16:08:04 +00:00
func ParseApiInfoMulti(s string) []APIInfo {
var apiInfos []APIInfo
if infoWithToken.Match([]byte(s)) {
allAddrs := strings.SplitN(s, ",", -1)
for _, addr := range allAddrs {
sp := strings.SplitN(addr, ":", 2)
apiInfos = append(apiInfos, APIInfo{
Addr: sp[1],
Token: []byte(sp[0]),
})
}
}
return apiInfos
}
2021-03-23 18:15:44 +00:00
func (a APIInfo) DialArgs(version string) (string, error) {
2020-10-09 00:57:41 +00:00
ma, err := multiaddr.NewMultiaddr(a.Addr)
if err == nil {
_, addr, err := manet.DialArgs(ma)
if err != nil {
return "", err
}
2021-03-23 18:15:44 +00:00
return "ws://" + addr + "/rpc/" + version, nil
2020-10-09 00:57:41 +00:00
}
_, err = url.Parse(a.Addr)
if err != nil {
return "", err
}
2021-03-23 18:15:44 +00:00
return a.Addr + "/rpc/" + version, nil
2020-10-09 00:57:41 +00:00
}
func (a APIInfo) Host() (string, error) {
ma, err := multiaddr.NewMultiaddr(a.Addr)
if err == nil {
_, addr, err := manet.DialArgs(ma)
if err != nil {
return "", err
}
return addr, nil
}
spec, err := url.Parse(a.Addr)
if err != nil {
return "", err
}
return spec.Host, nil
}
func (a APIInfo) AuthHeader() http.Header {
if len(a.Token) != 0 {
headers := http.Header{}
headers.Add("Authorization", "Bearer "+string(a.Token))
return headers
}
log.Warn("API Token not set and requested, capabilities might be limited.")
return nil
}