45 lines
992 B
Go
Raw Permalink Normal View History

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)
2021-01-31 11:05:09 -03:00
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
}
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
}