utils.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package conf
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. )
  7. // ProtoAddr ProtoAddr
  8. type ProtoAddr struct {
  9. Proto, Net, Addr string
  10. }
  11. func (p ProtoAddr) String() string {
  12. return p.Proto + "://" + p.Addr
  13. }
  14. // socketPath tests if a given address describes a domain socket,
  15. // and returns the relevant path part of the string if it is.
  16. func socketPath(addr string) string {
  17. if !strings.HasPrefix(addr, "unix://") {
  18. return ""
  19. }
  20. return strings.TrimPrefix(addr, "unix://")
  21. }
  22. // ClientListener is used to format a listener for a
  23. // port on a addr, whatever HTTP, HTTPS, DNS or RPC.
  24. func (c *Config) ClientListener(addr string, port int) (net.Addr, error) {
  25. if path := socketPath(addr); path != "" {
  26. return &net.UnixAddr{Name: path, Net: "unix"}, nil
  27. }
  28. ip := net.ParseIP(addr)
  29. if ip == nil {
  30. return nil, fmt.Errorf("Failed to parse IP: %v", addr)
  31. }
  32. return &net.TCPAddr{IP: ip, Port: port}, nil
  33. }
  34. // DNSAddrs returns the bind addresses for the DNS server.
  35. func (c *Config) DNSAddrs() ([]ProtoAddr, error) {
  36. if c.DNS == nil {
  37. return nil, nil
  38. }
  39. a, err := c.ClientListener(c.DNS.Addr, c.DNS.Port)
  40. if err != nil {
  41. return nil, err
  42. }
  43. addrs := []ProtoAddr{
  44. {"dns", "tcp", a.String()},
  45. {"dns", "udp", a.String()},
  46. }
  47. return addrs, nil
  48. }
  49. // HTTPAddrs returns the bind addresses for the HTTP server and
  50. // the application protocol which should be served, e.g. 'http'
  51. // or 'https'.
  52. func (c *Config) HTTPAddrs() ([]ProtoAddr, error) {
  53. var addrs []ProtoAddr
  54. if c.HTTP != nil {
  55. a, err := c.ClientListener(c.HTTP.Addr, c.HTTP.Port)
  56. if err != nil {
  57. return nil, err
  58. }
  59. addrs = append(addrs, ProtoAddr{"http", a.Network(), a.String()})
  60. }
  61. return addrs, nil
  62. }