gatus/config/web.go

64 lines
1.8 KiB
Go
Raw Normal View History

2020-11-20 23:40:57 +01:00
package config
import (
"fmt"
"math"
"net/url"
"strings"
2020-11-20 23:40:57 +01:00
)
// webConfig is the structure which supports the configuration of the endpoint
// which provides access to the web frontend
type webConfig struct {
// Address to listen on (defaults to 0.0.0.0 specified by DefaultAddress)
Address string `yaml:"address"`
// Port to listen on (default to 8080 specified by DefaultPort)
Port int `yaml:"port"`
2020-11-21 03:42:42 +01:00
// ContextRoot set the root context for the web application
ContextRoot string `yaml:"context-root"`
2020-11-20 23:40:57 +01:00
}
2020-11-21 23:35:08 +01:00
// validateAndSetDefaults checks and sets the default values for fields that are not set
2020-11-20 23:40:57 +01:00
func (web *webConfig) validateAndSetDefaults() {
2020-11-21 23:35:08 +01:00
// Validate the Address
2020-11-20 23:40:57 +01:00
if len(web.Address) == 0 {
web.Address = DefaultAddress
}
2020-11-21 23:35:08 +01:00
// Validate the Port
2020-11-20 23:40:57 +01:00
if web.Port == 0 {
web.Port = DefaultPort
} else if web.Port < 0 || web.Port > math.MaxUint16 {
2020-11-21 23:35:08 +01:00
panic(fmt.Sprintf("invalid port: value should be between %d and %d", 0, math.MaxUint16))
2020-11-20 23:40:57 +01:00
}
2020-11-21 23:35:08 +01:00
// Validate the ContextRoot
if len(web.ContextRoot) == 0 {
web.ContextRoot = DefaultContextRoot
} else {
2020-11-21 23:35:08 +01:00
trimmedContextRoot := strings.Trim(web.ContextRoot, "/")
if len(trimmedContextRoot) == 0 {
web.ContextRoot = DefaultContextRoot
return
}
rootContextURL, err := url.Parse(trimmedContextRoot)
if err != nil {
2020-11-21 23:35:08 +01:00
panic("invalid context root:" + err.Error())
}
2020-11-21 23:35:08 +01:00
if rootContextURL.Path != trimmedContextRoot {
panic("invalid context root: too complex")
2020-11-21 03:42:42 +01:00
}
2020-11-21 23:35:08 +01:00
web.ContextRoot = "/" + strings.Trim(rootContextURL.Path, "/") + "/"
}
2020-11-20 23:40:57 +01:00
}
// SocketAddress returns the combination of the Address and the Port
func (web *webConfig) SocketAddress() string {
return fmt.Sprintf("%s:%d", web.Address, web.Port)
}
2020-11-21 23:35:08 +01:00
// PrependWithContextRoot appends the given path to the ContextRoot
func (web *webConfig) PrependWithContextRoot(path string) string {
2020-11-30 15:23:03 +01:00
return web.ContextRoot + strings.Trim(path, "/")
}