25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

68 lines
1.9 KiB

  1. // Copyright 2015 Google Inc. All rights reserved.
  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 header
  15. import (
  16. "encoding/json"
  17. "net/http"
  18. "github.com/google/martian"
  19. "github.com/google/martian/parse"
  20. )
  21. const idHeaderName string = "X-Martian-ID"
  22. func init() {
  23. parse.Register("header.Id", idModifierFromJSON)
  24. }
  25. type idModifier struct{}
  26. type idModifierJSON struct {
  27. Scope []parse.ModifierType `json:"scope"`
  28. }
  29. // NewIDModifier returns a request modifier that will set a header with the name
  30. // X-Martian-ID with a value that is a unique identifier for the request. In the case
  31. // that the X-Martian-ID header is already set, the header is unmodified.
  32. func NewIDModifier() martian.RequestModifier {
  33. return &idModifier{}
  34. }
  35. // ModifyRequest sets the X-Martian-ID header with a unique identifier. In the case
  36. // that the X-Martian-ID header is already set, the header is unmodified.
  37. func (im *idModifier) ModifyRequest(req *http.Request) error {
  38. // Do not rewrite an ID if req already has one
  39. if req.Header.Get(idHeaderName) != "" {
  40. return nil
  41. }
  42. ctx := martian.NewContext(req)
  43. req.Header.Set(idHeaderName, ctx.ID())
  44. return nil
  45. }
  46. func idModifierFromJSON(b []byte) (*parse.Result, error) {
  47. msg := &idModifierJSON{}
  48. if err := json.Unmarshal(b, msg); err != nil {
  49. return nil, err
  50. }
  51. modifier := NewIDModifier()
  52. return parse.NewResult(modifier, msg.Scope)
  53. }