proxy.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package proxy
  14. import (
  15. "net/http"
  16. )
  17. // GetProxyURLs is a function which should return the current set of URLs to
  18. // which client requests should be proxied. This function will be queried
  19. // periodically by the proxy Handler to refresh the set of available
  20. // backends.
  21. type GetProxyURLs func() []string
  22. // NewHandler creates a new HTTP handler, listening on the given transport,
  23. // which will proxy requests to an etcd cluster.
  24. // The handler will periodically update its view of the cluster.
  25. func NewHandler(t *http.Transport, urlsFunc GetProxyURLs) http.Handler {
  26. return &reverseProxy{
  27. director: newDirector(urlsFunc),
  28. transport: t,
  29. }
  30. }
  31. // NewReadonlyHandler wraps the given HTTP handler to allow only GET requests
  32. func NewReadonlyHandler(hdlr http.Handler) http.Handler {
  33. readonly := readonlyHandlerFunc(hdlr)
  34. return http.HandlerFunc(readonly)
  35. }
  36. func readonlyHandlerFunc(next http.Handler) func(http.ResponseWriter, *http.Request) {
  37. return func(w http.ResponseWriter, req *http.Request) {
  38. if req.Method != "GET" {
  39. w.WriteHeader(http.StatusNotImplemented)
  40. return
  41. }
  42. next.ServeHTTP(w, req)
  43. }
  44. }