serve.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdmain
  15. import (
  16. "io/ioutil"
  17. defaultLog "log"
  18. "net"
  19. "net/http"
  20. "time"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/cockroachdb/cmux"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  23. )
  24. // serve accepts incoming connections on the listener l,
  25. // creating a new service goroutine for each. The service goroutines
  26. // read requests and then call handler to reply to them.
  27. func serve(l net.Listener, grpcS *grpc.Server, handler http.Handler, readTimeout time.Duration) error {
  28. // TODO: assert net.Listener type? Arbitrary listener might break HTTPS server which
  29. // expect a TLS Conn type.
  30. httpl := l
  31. if grpcS != nil {
  32. m := cmux.New(l)
  33. grpcl := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
  34. httpl = m.Match(cmux.Any())
  35. go func() { plog.Fatal(m.Serve()) }()
  36. go plog.Fatal(grpcS.Serve(grpcl))
  37. }
  38. logger := defaultLog.New(ioutil.Discard, "etcdhttp", 0)
  39. // TODO: add debug flag; enable logging when debug flag is set
  40. srv := &http.Server{
  41. Handler: handler,
  42. ReadTimeout: readTimeout,
  43. ErrorLog: logger, // do not log user error
  44. }
  45. return srv.Serve(httpl)
  46. }