listener.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package server
  2. import (
  3. "crypto/tls"
  4. "net"
  5. "time"
  6. "github.com/coreos/etcd/log"
  7. )
  8. const (
  9. DefaultReadTimeout = float64((5 * time.Minute) / time.Second)
  10. DefaultWriteTimeout = float64((5 * time.Minute) / time.Second)
  11. )
  12. // TLSServerConfig generates tls configuration based on TLSInfo
  13. // If any error happens, this function will call log.Fatal
  14. func TLSServerConfig(info *TLSInfo) *tls.Config {
  15. if info.KeyFile == "" || info.CertFile == "" {
  16. return nil
  17. }
  18. cfg, err := info.ServerConfig()
  19. if err != nil {
  20. log.Fatal("TLS info error: ", err)
  21. }
  22. return cfg
  23. }
  24. // NewListener creates a net.Listener
  25. // If the given scheme is "https", it will use TLS config to set listener.
  26. // If any error happens, this function will call log.Fatal
  27. func NewListener(scheme, addr string, cfg *tls.Config) net.Listener {
  28. if scheme == "https" {
  29. l, err := newTLSListener(addr, cfg)
  30. if err != nil {
  31. log.Fatal("Failed to create TLS listener: ", err)
  32. }
  33. return l
  34. }
  35. l, err := newListener(addr)
  36. if err != nil {
  37. log.Fatal("Failed to create listener: ", err)
  38. }
  39. return l
  40. }
  41. func newListener(addr string) (net.Listener, error) {
  42. if addr == "" {
  43. addr = ":http"
  44. }
  45. l, e := net.Listen("tcp", addr)
  46. if e != nil {
  47. return nil, e
  48. }
  49. return l, nil
  50. }
  51. func newTLSListener(addr string, cfg *tls.Config) (net.Listener, error) {
  52. if addr == "" {
  53. addr = ":https"
  54. }
  55. conn, err := net.Listen("tcp", addr)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return tls.NewListener(conn, cfg), nil
  60. }