route.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. package ochttp
  15. import (
  16. "net/http"
  17. "go.opencensus.io/tag"
  18. )
  19. // WithRouteTag returns an http.Handler that records stats with the
  20. // http_server_route tag set to the given value.
  21. func WithRouteTag(handler http.Handler, route string) http.Handler {
  22. return taggedHandlerFunc(func(w http.ResponseWriter, r *http.Request) []tag.Mutator {
  23. addRoute := []tag.Mutator{tag.Upsert(KeyServerRoute, route)}
  24. ctx, _ := tag.New(r.Context(), addRoute...)
  25. r = r.WithContext(ctx)
  26. handler.ServeHTTP(w, r)
  27. return addRoute
  28. })
  29. }
  30. // taggedHandlerFunc is a http.Handler that returns tags describing the
  31. // processing of the request. These tags will be recorded along with the
  32. // measures in this package at the end of the request.
  33. type taggedHandlerFunc func(w http.ResponseWriter, r *http.Request) []tag.Mutator
  34. func (h taggedHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  35. tags := h(w, r)
  36. if a, ok := r.Context().Value(addedTagsKey{}).(*addedTags); ok {
  37. a.t = append(a.t, tags...)
  38. }
  39. }
  40. type addedTagsKey struct{}
  41. type addedTags struct {
  42. t []tag.Mutator
  43. }