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