guiconfiguration.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package config
  7. import (
  8. "net/url"
  9. "os"
  10. "strings"
  11. )
  12. type GUIConfiguration struct {
  13. Enabled bool `xml:"enabled,attr" json:"enabled" default:"true"`
  14. RawAddress string `xml:"address" json:"address" default:"127.0.0.1:8384"`
  15. User string `xml:"user,omitempty" json:"user"`
  16. Password string `xml:"password,omitempty" json:"password"`
  17. RawUseTLS bool `xml:"tls,attr" json:"useTLS"`
  18. RawAPIKey string `xml:"apikey,omitempty" json:"apiKey"`
  19. }
  20. func (c GUIConfiguration) Address() string {
  21. if override := os.Getenv("STGUIADDRESS"); override != "" {
  22. // This value may be of the form "scheme://address:port" or just
  23. // "address:port". We need to chop off the scheme. We try to parse it as
  24. // an URL if it contains a slash. If that fails, return it as is and let
  25. // some other error handling handle it.
  26. if strings.Contains(override, "/") {
  27. url, err := url.Parse(override)
  28. if err != nil {
  29. return override
  30. }
  31. return url.Host
  32. }
  33. return override
  34. }
  35. return c.RawAddress
  36. }
  37. func (c GUIConfiguration) UseTLS() bool {
  38. if override := os.Getenv("STGUIADDRESS"); override != "" {
  39. return strings.HasPrefix(override, "https:")
  40. }
  41. return c.RawUseTLS
  42. }
  43. func (c GUIConfiguration) URL() string {
  44. u := url.URL{
  45. Scheme: "http",
  46. Host: c.Address(),
  47. Path: "/",
  48. }
  49. if c.UseTLS() {
  50. u.Scheme = "https"
  51. }
  52. if strings.HasPrefix(u.Host, ":") {
  53. // Empty host, i.e. ":port", use IPv4 localhost
  54. u.Host = "127.0.0.1" + u.Host
  55. } else if strings.HasPrefix(u.Host, "0.0.0.0:") {
  56. // IPv4 all zeroes host, convert to IPv4 localhost
  57. u.Host = "127.0.0.1" + u.Host[7:]
  58. } else if strings.HasPrefix(u.Host, "[::]:") {
  59. // IPv6 all zeroes host, convert to IPv6 localhost
  60. u.Host = "[::1]" + u.Host[4:]
  61. }
  62. return u.String()
  63. }
  64. func (c GUIConfiguration) APIKey() string {
  65. if override := os.Getenv("STGUIAPIKEY"); override != "" {
  66. return override
  67. }
  68. return c.RawAPIKey
  69. }