localhost interface
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Jake Hillion 2021-01-23 17:13:06 +00:00
parent d35b4b47ed
commit 8c4ee6c6d9

View File

@ -1,9 +1,36 @@
package config
import "github.com/go-playground/validator/v10"
import (
"github.com/go-playground/validator/v10"
"log"
"net"
)
var v = validator.New()
func init() {
if err := v.RegisterValidation("iface", func(fl validator.FieldLevel) bool {
name, ok := fl.Field().Interface().(string)
if ok {
ifaces, err := net.Interfaces()
if err != nil {
log.Printf("error getting interfaces: %v", err)
return false
}
for _, i := range ifaces {
if i.Name == name {
return true
}
}
}
return false
}); err != nil {
}
}
type Configuration struct {
Host Host
Peers []Peer `validate:"dive"`
@ -19,7 +46,7 @@ type Host struct {
type Peer struct {
Method string `validate:"oneof=TCP UDP"`
LocalHost string `validate:"omitempty,ip"`
LocalHost string `validate:"omitempty,ip|iface"`
LocalPort uint `validate:"max=65535"`
RemoteHost string `validate:"required_with=RemotePort,omitempty,fqdn|ip"`
@ -32,6 +59,30 @@ type Peer struct {
RetryWait uint
}
func (p Peer) GetLocalHost() string {
if err := v.Var(p.LocalHost, "ip"); err == nil {
return p.LocalHost
}
iface, err := net.InterfaceByName(p.LocalHost)
if err != nil {
panic(err)
}
if iface != nil {
addrs, err := iface.Addrs()
if err != nil {
panic(err)
}
if len(addrs) > 0 {
return addrs[0].String()
}
}
return "invalid"
}
func (c Configuration) Validate() error {
return v.Struct(c)
}