| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package shared
- import (
- "fmt"
- "log"
- "strconv"
- "strings"
- )
- type Server struct {
- proto string // http or https
- host string // just the domain name, like 'qbit.local.lan' or whatever
- port int // port that the web ui listens on
- }
- func (s Server) Format() string {
- return fmt.Sprintf("%s://%s:%v", s.proto, s.host, s.port)
- }
- func (s Server) FormatWith(path string) string {
- return fmt.Sprintf("%s%s", s.Format(), path)
- }
- // strips everything but the port number and hostname from a string
- func sanitizeUrl(s string) string {
- protoStripped := strings.ReplaceAll(
- strings.ReplaceAll(
- strings.ReplaceAll(
- s, "https", "",
- ), "http", "",
- ), "://", "",
- )
- splitHost := strings.Split(protoStripped, "/")
- return splitHost[0]
- }
- // takes string s and returns the host and port
- func splitServerPort(s string) (string, int) {
- splitPort := strings.Split(s, ":")
- if len(splitPort) < 1 {
- // add log here
- log.Fatal("unhandled for now")
- }
- host := splitPort[0]
- port, err := strconv.Atoi(splitPort[1])
- if err != nil {
- log.Fatal("couldnt parse port. unhandled for now.")
- }
- return host, port
- }
- // strips everything but the port number and hostname from a string
- func ParseServer(s string) (Server, error) {
- var proto, host string
- var port int
- if strings.Contains(s, "https") {
- proto = "https"
- } else {
- proto = "http"
- }
- protoStripped := sanitizeUrl(s)
- splitHost := strings.Split(protoStripped, "/")
- host, port = splitServerPort(splitHost[0])
- return Server{proto: proto, host: host, port: port}, nil
- }
|