2022-01-02 08:44:18 -03:00
|
|
|
package nostr
|
2021-01-31 11:05:09 -03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2023-11-28 22:23:51 -03:00
|
|
|
// NormalizeURL normalizes the url and replaces http://, https:// schemes with ws://, wss://
|
|
|
|
// and normalizes the path.
|
2021-01-31 11:05:09 -03:00
|
|
|
func NormalizeURL(u string) string {
|
2022-11-19 07:19:10 -03:00
|
|
|
if u == "" {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2023-03-14 21:54:25 -03:00
|
|
|
u = strings.TrimSpace(u)
|
|
|
|
u = strings.ToLower(u)
|
|
|
|
|
2024-08-19 11:53:18 -03:00
|
|
|
if fqn := strings.Split(u, ":")[0]; fqn == "localhost" || fqn == "127.0.0.1" {
|
2024-07-04 12:06:24 -03:00
|
|
|
u = "ws://" + u
|
2024-07-04 16:29:04 -03:00
|
|
|
} else if !strings.HasPrefix(u, "http") && !strings.HasPrefix(u, "ws") {
|
2021-02-20 17:44:05 -03:00
|
|
|
u = "wss://" + u
|
2021-01-31 11:05:09 -03:00
|
|
|
}
|
2024-07-04 16:29:04 -03:00
|
|
|
|
2021-01-31 11:05:09 -03:00
|
|
|
p, err := url.Parse(u)
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2021-02-20 17:44:05 -03:00
|
|
|
if p.Scheme == "http" {
|
|
|
|
p.Scheme = "ws"
|
|
|
|
} else if p.Scheme == "https" {
|
|
|
|
p.Scheme = "wss"
|
2021-01-31 11:05:09 -03:00
|
|
|
}
|
|
|
|
|
2022-11-18 14:15:41 -03:00
|
|
|
p.Path = strings.TrimRight(p.Path, "/")
|
2021-01-31 11:05:09 -03:00
|
|
|
|
|
|
|
return p.String()
|
|
|
|
}
|
2023-11-28 22:23:51 -03:00
|
|
|
|
|
|
|
// NormalizeOKMessage takes a string message that is to be sent in an `OK` or `CLOSED` command
|
|
|
|
// and prefixes it with "<prefix>: " if it doesn't already have an acceptable prefix.
|
|
|
|
func NormalizeOKMessage(reason string, prefix string) string {
|
|
|
|
if idx := strings.Index(reason, ": "); idx == -1 || strings.IndexByte(reason[0:idx], ' ') != -1 {
|
|
|
|
return prefix + ": " + reason
|
|
|
|
}
|
|
|
|
return reason
|
|
|
|
}
|