Last active
August 29, 2015 14:05
-
-
Save Yasushi/17be0d71a6ef3a79b297 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (c) 2014, Yasushi Abe | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
package main | |
import ( | |
"flag" | |
"github.com/elazarl/goproxy" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"regexp" | |
"strings" | |
) | |
func readHosts(hostsfile string) (map[string]string, error) { | |
contents, err := ioutil.ReadFile(hostsfile) | |
if err != nil { | |
return nil, err | |
} | |
hosts := make(map[string]string) | |
pattern := regexp.MustCompile("[ ]+") | |
for _, line := range strings.Split(string(contents), "\n") { | |
if !strings.HasPrefix(line, "#") && len(line) > 0 { | |
record := pattern.Split(line, -1) | |
if len(record) > 1 { | |
for _, name := range record[1:] { | |
hosts[name] = record[0] | |
} | |
} | |
} | |
} | |
return hosts, nil | |
} | |
func main() { | |
verbose := flag.Bool("v", false, "should every proxy request be logged to stdout") | |
addr := flag.String("addr", ":8080", "proxy listen address") | |
hostsfile := flag.String("f", "hosts", "hosts file") | |
flag.Parse() | |
hosts, err := readHosts(*hostsfile) | |
if err != nil { | |
log.Fatal(err) | |
} | |
var condition goproxy.ReqConditionFunc = func(req *http.Request, ctx *goproxy.ProxyCtx) bool { | |
_, ok := hosts[req.URL.Host] | |
return ok | |
} | |
proxy := goproxy.NewProxyHttpServer() | |
proxy.Verbose = *verbose | |
proxy.OnRequest(condition).DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { | |
req.URL.Host = hosts[req.URL.Host] | |
return req, nil | |
}) | |
log.Fatal(http.ListenAndServe(*addr, proxy)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment