github.com/m3db/m3@v1.5.0/src/query/api/v1/middleware/source.go (about) 1 // Copyright (c) 2021 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package middleware 22 23 import ( 24 "fmt" 25 "net/http" 26 27 "github.com/gorilla/mux" 28 "go.uber.org/zap" 29 30 "github.com/m3db/m3/src/query/source" 31 "github.com/m3db/m3/src/query/util/logging" 32 "github.com/m3db/m3/src/x/headers" 33 xhttp "github.com/m3db/m3/src/x/net/http" 34 ) 35 36 var errInvalidSourceHeader = xhttp.NewError( 37 fmt.Errorf("invalid %s header", headers.SourceHeader), 38 http.StatusBadRequest) 39 40 // SourceOptions are the options for the source middleware. 41 type SourceOptions struct { 42 Deserializer source.Deserializer 43 } 44 45 // Source adds the headers.SourceHeader value to the request context. 46 // Installing this middleware function allows application code to access the typed source value using FromContext. 47 // Additionally a source log field is added to the request scope logger. 48 func Source(opts Options) mux.MiddlewareFunc { 49 return func(base http.Handler) http.Handler { 50 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 51 hs := r.Header.Get(headers.SourceHeader) 52 if len(hs) == 0 { 53 // bail early if the header is not set on the request. 54 base.ServeHTTP(w, r) 55 return 56 } 57 iOpts := opts.InstrumentOpts 58 s := []byte(hs) 59 ctx := logging.NewContext(r.Context(), iOpts, zap.ByteString("source", s)) 60 l := logging.WithContext(ctx, iOpts) 61 ctx, err := source.NewContext(ctx, s, opts.Source.Deserializer) 62 if err != nil { 63 l.Error("failed to deserialize source", zap.Error(err)) 64 xhttp.WriteError(w, errInvalidSourceHeader) 65 return 66 } 67 base.ServeHTTP(w, r.WithContext(ctx)) 68 }) 69 } 70 }