proxy.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 proxy
  15. import (
  16. "net/http"
  17. "time"
  18. )
  19. const (
  20. // DefaultMaxIdleConnsPerHost indicates the default maximum idle connection
  21. // count maintained between proxy and each member. We set it to 128 to
  22. // let proxy handle 128 concurrent requests in long term smoothly.
  23. // If the number of concurrent requests is bigger than this value,
  24. // proxy needs to create one new connection when handling each request in
  25. // the delta, which is bad because the creation consumes resource and
  26. // may eat up ephemeral ports.
  27. DefaultMaxIdleConnsPerHost = 128
  28. )
  29. // GetProxyURLs is a function which should return the current set of URLs to
  30. // which client requests should be proxied. This function will be queried
  31. // periodically by the proxy Handler to refresh the set of available
  32. // backends.
  33. type GetProxyURLs func() []string
  34. // NewHandler creates a new HTTP handler, listening on the given transport,
  35. // which will proxy requests to an etcd cluster.
  36. // The handler will periodically update its view of the cluster.
  37. func NewHandler(t *http.Transport, urlsFunc GetProxyURLs, failureWait time.Duration, refreshInterval time.Duration) http.Handler {
  38. return &reverseProxy{
  39. director: newDirector(urlsFunc, failureWait, refreshInterval),
  40. transport: t,
  41. }
  42. }
  43. // NewReadonlyHandler wraps the given HTTP handler to allow only GET requests
  44. func NewReadonlyHandler(hdlr http.Handler) http.Handler {
  45. readonly := readonlyHandlerFunc(hdlr)
  46. return http.HandlerFunc(readonly)
  47. }
  48. func readonlyHandlerFunc(next http.Handler) func(http.ResponseWriter, *http.Request) {
  49. return func(w http.ResponseWriter, req *http.Request) {
  50. if req.Method != "GET" {
  51. w.WriteHeader(http.StatusNotImplemented)
  52. return
  53. }
  54. next.ServeHTTP(w, req)
  55. }
  56. }