http.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 etcdhttp
  14. import (
  15. "errors"
  16. "log"
  17. "math"
  18. "net/http"
  19. "strings"
  20. "time"
  21. etcdErr "github.com/coreos/etcd/error"
  22. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  23. )
  24. const (
  25. // time to wait for response from EtcdServer requests
  26. // 5s for disk and network delay + 10*heartbeat for commit and possible
  27. // leader switch
  28. // TODO: use heartbeat set in etcdserver
  29. defaultServerTimeout = 5*time.Second + 10*(100*time.Millisecond)
  30. // time to wait for a Watch request
  31. defaultWatchTimeout = time.Duration(math.MaxInt64)
  32. )
  33. var errClosed = errors.New("etcdhttp: client closed connection")
  34. // writeError logs and writes the given Error to the ResponseWriter
  35. // If Error is an etcdErr, it is rendered to the ResponseWriter
  36. // Otherwise, it is assumed to be an InternalServerError
  37. func writeError(w http.ResponseWriter, err error) {
  38. if err == nil {
  39. return
  40. }
  41. switch e := err.(type) {
  42. case *etcdErr.Error:
  43. e.WriteTo(w)
  44. case *httptypes.HTTPError:
  45. e.WriteTo(w)
  46. default:
  47. log.Printf("etcdhttp: unexpected error: %v", err)
  48. herr := httptypes.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
  49. herr.WriteTo(w)
  50. }
  51. }
  52. // allowMethod verifies that the given method is one of the allowed methods,
  53. // and if not, it writes an error to w. A boolean is returned indicating
  54. // whether or not the method is allowed.
  55. func allowMethod(w http.ResponseWriter, m string, ms ...string) bool {
  56. for _, meth := range ms {
  57. if m == meth {
  58. return true
  59. }
  60. }
  61. w.Header().Set("Allow", strings.Join(ms, ","))
  62. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  63. return false
  64. }