route.go 2.0 KB

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