You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

57 lines
1.6 KiB

  1. // Copyright 2016 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 api contains a forwarder to route system HTTP requests to the
  15. // local API server.
  16. package api
  17. import (
  18. "fmt"
  19. "net/http"
  20. "github.com/google/martian"
  21. "github.com/google/martian/log"
  22. )
  23. // Forwarder is a request modifier that routes the request to the API server and
  24. // marks the request for skipped logging.
  25. type Forwarder struct {
  26. host string
  27. port int
  28. }
  29. // NewForwarder returns a Forwarder that rewrites requests to host.
  30. func NewForwarder(host string, port int) *Forwarder {
  31. return &Forwarder{
  32. host: host,
  33. port: port,
  34. }
  35. }
  36. // ModifyRequest forwards the request to the local API server running at f.port,
  37. // downgrades the scheme to http and marks the request context for skipped logging.
  38. func (f *Forwarder) ModifyRequest(req *http.Request) error {
  39. ctx := martian.NewContext(req)
  40. ctx.APIRequest()
  41. ctx.SkipLogging()
  42. in := req.URL.String()
  43. req.URL.Scheme = "http"
  44. req.URL.Host = fmt.Sprintf("%s:%d", "localhost", f.port)
  45. out := req.URL.String()
  46. log.Infof("api.Forwarder: forwarding %s to %s", in, out)
  47. return nil
  48. }