github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/catgo/catgo.go (about) 1 package catgo 2 3 import ( 4 "errors" 5 "fmt" 6 "io" 7 "strconv" 8 "strings" 9 10 "github.com/sirupsen/logrus" 11 12 "github.com/artisanhe/tools/catgo/cat-go/cat" 13 "github.com/artisanhe/tools/conf" 14 ) 15 16 func init() { 17 cat.ResetLogger(&innerLogger{l: logrus.WithField("Component", "Catgo")}) 18 } 19 20 type Catgo struct { 21 Domain string `conf:"env"` 22 Debug bool `conf:"env"` 23 HttpServers []string `conf:"env"` 24 } 25 26 func (c Catgo) DockerDefaults() conf.DockerDefaults { 27 return conf.DockerDefaults{ 28 "HttpServers": []string{"cat:2280"}, 29 } 30 } 31 32 func (c Catgo) MarshalDefaults(v interface{}) { 33 if cat, ok := v.(*Catgo); ok { 34 if cat.Domain == "" { 35 cat.Domain = "g7pay.local" 36 } 37 cat.Debug = true 38 if len(cat.HttpServers) == 0 { 39 cat.HttpServers = []string{"cat:2280"} 40 } 41 } 42 } 43 44 func (c *Catgo) Init() { 45 if c.Debug { 46 cat.DebugOn() 47 } 48 services := []cat.HostConfig{} 49 50 for _, s := range c.HttpServers { 51 h, p, e := parseHost(s) 52 if e != nil { 53 panic(e) 54 } 55 services = append(services, cat.HostConfig{ 56 Host: h, 57 Port: p, 58 }) 59 } 60 if err := cat.InitWithServer(c.Domain, services); err != nil { 61 panic(err) 62 } 63 64 } 65 66 type innerLogger struct { 67 l *logrus.Entry 68 } 69 70 func (i *innerLogger) SetOutput(io.Writer) { 71 72 } 73 74 func (i *innerLogger) Printf(format string, args ...interface{}) { 75 i.l.Printf(format, args...) 76 } 77 78 func parseHost(raw string) (string, int, error) { 79 ss := strings.Split(raw, ":") 80 if len(ss) != 2 { 81 return "", 0, errors.New("parse host error") 82 } 83 port, err := strconv.Atoi(ss[1]) 84 if err != nil { 85 return "", 0, fmt.Errorf("parse host error : %v", err) 86 } 87 if port <= 0 || port > 65535 { 88 return "", 0, errors.New("parse host error : port illegal") 89 } 90 91 return ss[0], port, nil 92 93 }