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