proxy.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. // GetProxyURLs is a function which should return the current set of URLs to
  19. // which client requests should be proxied. This function will be queried
  20. // periodically by the proxy Handler to refresh the set of available
  21. // backends.
  22. type GetProxyURLs func() []string
  23. // NewHandler creates a new HTTP handler, listening on the given transport,
  24. // which will proxy requests to an etcd cluster.
  25. // The handler will periodically update its view of the cluster.
  26. func NewHandler(t *http.Transport, urlsFunc GetProxyURLs) http.Handler {
  27. return &reverseProxy{
  28. director: newDirector(urlsFunc),
  29. transport: t,
  30. }
  31. }
  32. // NewReadonlyHandler wraps the given HTTP handler to allow only GET requests
  33. func NewReadonlyHandler(hdlr http.Handler) http.Handler {
  34. readonly := readonlyHandlerFunc(hdlr)
  35. return http.HandlerFunc(readonly)
  36. }
  37. func readonlyHandlerFunc(next http.Handler) func(http.ResponseWriter, *http.Request) {
  38. return func(w http.ResponseWriter, req *http.Request) {
  39. if req.Method != "GET" {
  40. w.WriteHeader(http.StatusNotImplemented)
  41. return
  42. }
  43. next.ServeHTTP(w, req)
  44. }
  45. }