Code refactoring for bpa operator
[icn.git] / cmd / bpa-operator / vendor / go.opencensus.io / plugin / ochttp / route.go
1 // Copyright 2018, OpenCensus 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 ochttp
16
17 import (
18         "context"
19         "net/http"
20
21         "go.opencensus.io/tag"
22 )
23
24 // SetRoute sets the http_server_route tag to the given value.
25 // It's useful when an HTTP framework does not support the http.Handler interface
26 // and using WithRouteTag is not an option, but provides a way to hook into the request flow.
27 func SetRoute(ctx context.Context, route string) {
28         if a, ok := ctx.Value(addedTagsKey{}).(*addedTags); ok {
29                 a.t = append(a.t, tag.Upsert(KeyServerRoute, route))
30         }
31 }
32
33 // WithRouteTag returns an http.Handler that records stats with the
34 // http_server_route tag set to the given value.
35 func WithRouteTag(handler http.Handler, route string) http.Handler {
36         return taggedHandlerFunc(func(w http.ResponseWriter, r *http.Request) []tag.Mutator {
37                 addRoute := []tag.Mutator{tag.Upsert(KeyServerRoute, route)}
38                 ctx, _ := tag.New(r.Context(), addRoute...)
39                 r = r.WithContext(ctx)
40                 handler.ServeHTTP(w, r)
41                 return addRoute
42         })
43 }
44
45 // taggedHandlerFunc is a http.Handler that returns tags describing the
46 // processing of the request. These tags will be recorded along with the
47 // measures in this package at the end of the request.
48 type taggedHandlerFunc func(w http.ResponseWriter, r *http.Request) []tag.Mutator
49
50 func (h taggedHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
51         tags := h(w, r)
52         if a, ok := r.Context().Value(addedTagsKey{}).(*addedTags); ok {
53                 a.t = append(a.t, tags...)
54         }
55 }
56
57 type addedTagsKey struct{}
58
59 type addedTags struct {
60         t []tag.Mutator
61 }