url.go (888B)
1 package core 2 3 type URL struct { 4 Domain string 5 Path string 6 Port uint32 7 Encrypted bool 8 } 9 10 const ( 11 DefaultHttpPort = 80 12 DefaultHttpsPort = 443 13 ) 14 15 // ParseURL a url string into a structured [URL]. 16 func ParseURL(s string) (u URL, _ error) { 17 protocol, body, ok := Cut(s, "://") 18 if !ok { 19 return u, Err{Msg: "missing protocol scheme"} 20 } 21 22 if protocol == "https" { 23 u.Encrypted = true 24 u.Port = DefaultHttpsPort 25 } 26 27 hostname, body, _ := Cut(body, "/") 28 hostname, port, _ := Cut(hostname, ":") 29 30 u.Domain = hostname 31 u.Path = body 32 33 if port != "" { 34 n, err := ParseUint(port) 35 if err != nil { 36 return u, Err{Cause: err, Msg: "parsing port"} 37 } 38 u.Port = uint32(n) 39 } 40 41 return u, nil 42 } 43 44 type Err struct { 45 Cause error 46 Msg string 47 } 48 49 func (e Err) Error() string { 50 var cause string 51 if e.Cause != nil { 52 cause += ": " + e.Cause.Error() 53 } 54 return e.Msg + cause 55 }