http.go 2.2 KB

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