github.com/nxtrace/NTrace-core@v1.3.1-0.20240513132635-39169291e8c9/tracemap/tracemap.go (about) 1 package tracemap 2 3 import ( 4 "crypto/tls" 5 "errors" 6 "fmt" 7 "github.com/fatih/color" 8 "github.com/nxtrace/NTrace-core/util" 9 "io" 10 "net" 11 "net/http" 12 "net/url" 13 "strings" 14 "time" 15 ) 16 17 func GetMapUrl(r string) (string, error) { 18 host, port := util.GetHostAndPort() 19 var fastIp string 20 // 如果 host 是一个 IP 使用默认域名 21 if valid := net.ParseIP(host); valid != nil { 22 fastIp = host 23 if len(strings.Split(fastIp, ":")) > 1 { 24 fastIp = "[" + fastIp + "]" 25 } 26 host = "origin-fallback.nxtrace.org" 27 } else { 28 // 默认配置完成,开始寻找最优 IP 29 fastIp = util.GetFastIP(host, port, false) 30 } 31 u := url.URL{Scheme: "https", Host: fastIp + ":" + port, Path: "/tracemap/api"} 32 tracemapUrl := u.String() 33 34 client := &http.Client{ 35 Timeout: 5 * time.Second, 36 Transport: &http.Transport{ 37 TLSClientConfig: &tls.Config{ 38 ServerName: host, 39 }, 40 }, 41 } 42 proxyUrl := util.GetProxy() 43 if proxyUrl != nil { 44 client.Transport.(*http.Transport).Proxy = http.ProxyURL(proxyUrl) 45 } 46 req, err := http.NewRequest("POST", tracemapUrl, strings.NewReader(r)) 47 if err != nil { 48 return "", errors.New("an issue occurred while connecting to the tracemap API") 49 } 50 req.Header.Add("User-Agent", util.UserAgent) 51 req.Host = host 52 req.Header.Add("Content-Type", "application/json") 53 resp, err := client.Do(req) 54 if err != nil { 55 return "", errors.New("an issue occurred while connecting to the tracemap API") 56 } 57 defer func(Body io.ReadCloser) { 58 err := Body.Close() 59 if err != nil { 60 return 61 } 62 }(resp.Body) 63 body, err := io.ReadAll(resp.Body) 64 if err != nil { 65 return "", errors.New("an issue occurred while connecting to the tracemap API") 66 } 67 return string(body), nil 68 } 69 70 func PrintMapUrl(r string) { 71 _, err := fmt.Fprintf(color.Output, "%s %s\n", 72 color.New(color.FgWhite, color.Bold).Sprintf("%s", "MapTrace URL:"), 73 color.New(color.FgBlue, color.Bold).Sprintf("%s", r), 74 ) 75 if err != nil { 76 return 77 } 78 }