init
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package parseurl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Target is host, port, secret string from tg://proxy or explicit flags.
|
||||
type Target struct {
|
||||
Host string
|
||||
Port int
|
||||
Secret string
|
||||
}
|
||||
|
||||
// ParseTGProxy parses tg://proxy?server=&port=&secret= or t.me/proxy style query.
|
||||
func ParseTGProxy(raw string) (*Target, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil, fmt.Errorf("empty proxy url")
|
||||
}
|
||||
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if u.Scheme != "tg" {
|
||||
return nil, fmt.Errorf("expected tg:// scheme, got %q", u.Scheme)
|
||||
}
|
||||
|
||||
host := u.Hostname()
|
||||
if host != "" && host != "proxy" {
|
||||
return nil, fmt.Errorf("unexpected tg host %q", host)
|
||||
}
|
||||
|
||||
q := u.Query()
|
||||
server := strings.TrimSpace(q.Get("server"))
|
||||
if server == "" {
|
||||
return nil, fmt.Errorf("missing server parameter")
|
||||
}
|
||||
portStr := strings.TrimSpace(q.Get("port"))
|
||||
if portStr == "" {
|
||||
return nil, fmt.Errorf("missing port parameter")
|
||||
}
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return nil, fmt.Errorf("invalid port %q", portStr)
|
||||
}
|
||||
sec := strings.TrimSpace(q.Get("secret"))
|
||||
if sec == "" {
|
||||
return nil, fmt.Errorf("missing secret parameter")
|
||||
}
|
||||
|
||||
return &Target{Host: server, Port: port, Secret: sec}, nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package parseurl
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseTGProxy(t *testing.T) {
|
||||
raw := "tg://proxy?server=example.com&port=443&secret=ee0102030405060708090a0b0c0d0e0f10632e6578616d706c652e636f6d"
|
||||
tg, err := ParseTGProxy(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tg.Host != "example.com" || tg.Port != 443 {
|
||||
t.Fatalf("%+v", tg)
|
||||
}
|
||||
if tg.Secret == "" {
|
||||
t.Fatal("secret")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user