proxy.go 2.2 KB

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