http.go 2.0 KB

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