util.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package shared
  2. import (
  3. "fmt"
  4. "log"
  5. "strconv"
  6. "strings"
  7. )
  8. type Server struct {
  9. proto string // http or https
  10. host string // just the domain name, like 'qbit.local.lan' or whatever
  11. port int // port that the web ui listens on
  12. }
  13. func (s Server) Format() string {
  14. return fmt.Sprintf("%s://%s:%v", s.proto, s.host, s.port)
  15. }
  16. func (s Server) FormatWith(path string) string {
  17. return fmt.Sprintf("%s%s", s.Format(), path)
  18. }
  19. // strips everything but the port number and hostname from a string
  20. func sanitizeUrl(s string) string {
  21. protoStripped := strings.ReplaceAll(
  22. strings.ReplaceAll(
  23. strings.ReplaceAll(
  24. s, "https", "",
  25. ), "http", "",
  26. ), "://", "",
  27. )
  28. splitHost := strings.Split(protoStripped, "/")
  29. return splitHost[0]
  30. }
  31. // takes string s and returns the host and port
  32. func splitServerPort(s string) (string, int) {
  33. splitPort := strings.Split(s, ":")
  34. if len(splitPort) < 1 {
  35. // add log here
  36. log.Fatal("unhandled for now")
  37. }
  38. host := splitPort[0]
  39. port, err := strconv.Atoi(splitPort[1])
  40. if err != nil {
  41. log.Fatal("couldnt parse port. unhandled for now.")
  42. }
  43. return host, port
  44. }
  45. // strips everything but the port number and hostname from a string
  46. func ParseServer(s string) (Server, error) {
  47. var proto, host string
  48. var port int
  49. if strings.Contains(s, "https") {
  50. proto = "https"
  51. } else {
  52. proto = "http"
  53. }
  54. protoStripped := sanitizeUrl(s)
  55. splitHost := strings.Split(protoStripped, "/")
  56. host, port = splitServerPort(splitHost[0])
  57. return Server{proto: proto, host: host, port: port}, nil
  58. }