1 // Copyright 2018, OpenCensus Authors
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
21 "go.opencensus.io/tag"
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))
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)
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
50 func (h taggedHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
52 if a, ok := r.Context().Value(addedTagsKey{}).(*addedTags); ok {
53 a.t = append(a.t, tags...)
57 type addedTagsKey struct{}
59 type addedTags struct {