http.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2015 The etcd Authors
  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 v2http
  15. import (
  16. "math"
  17. "net/http"
  18. "strings"
  19. "time"
  20. "github.com/coreos/etcd/etcdserver/api/etcdhttp"
  21. "github.com/coreos/etcd/etcdserver/api/v2http/httptypes"
  22. "github.com/coreos/etcd/etcdserver/auth"
  23. "github.com/coreos/etcd/pkg/logutil"
  24. "github.com/coreos/pkg/capnslog"
  25. )
  26. const (
  27. // time to wait for a Watch request
  28. defaultWatchTimeout = time.Duration(math.MaxInt64)
  29. )
  30. var (
  31. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdserver/api/v2http")
  32. mlog = logutil.NewMergeLogger(plog)
  33. )
  34. func writeError(w http.ResponseWriter, r *http.Request, err error) {
  35. if err == nil {
  36. return
  37. }
  38. if e, ok := err.(auth.Error); ok {
  39. herr := httptypes.NewHTTPError(e.HTTPStatus(), e.Error())
  40. if et := herr.WriteTo(w); et != nil {
  41. plog.Debugf("error writing HTTPError (%v) to %s", et, r.RemoteAddr)
  42. }
  43. return
  44. }
  45. etcdhttp.WriteError(w, r, err)
  46. }
  47. // allowMethod verifies that the given method is one of the allowed methods,
  48. // and if not, it writes an error to w. A boolean is returned indicating
  49. // whether or not the method is allowed.
  50. func allowMethod(w http.ResponseWriter, m string, ms ...string) bool {
  51. for _, meth := range ms {
  52. if m == meth {
  53. return true
  54. }
  55. }
  56. w.Header().Set("Allow", strings.Join(ms, ","))
  57. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  58. return false
  59. }
  60. func requestLogger(handler http.Handler) http.Handler {
  61. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  62. plog.Debugf("[%s] %s remote:%s", r.Method, r.RequestURI, r.RemoteAddr)
  63. handler.ServeHTTP(w, r)
  64. })
  65. }