blob: 1ae1c1a69c04a17ec7c039316cc6c9ab9cf001bf [file] [log] [blame]
Colby Ranger00e5dc62013-12-18 09:07:02 -08001// ui-api-proxy is a reverse http proxy that allows the UI to be served from
2// a different host than the API. This allows testing new UI features served
3// from localhost but using live production data.
4//
5// Run the binary, download & install the Go tools available at
6// http://golang.org/doc/install . To run, execute `go run ui-api-proxy.go`.
7// For a description of the available flags, execute
8// `go run ui-api-proxy.go --help`.
9package main
10
11import (
12 "flag"
13 "fmt"
14 "log"
15 "net"
16 "net/http"
17 "net/http/httputil"
18 "net/url"
19 "strings"
20 "time"
21)
22
23var (
24 ui = flag.String("ui", "http://localhost:8080", "host to which ui requests will be forwarded")
25 api = flag.String("api", "https://gerrit-review.googlesource.com", "host to which api requests will be forwarded")
26 port = flag.Int("port", 0, "port on which to run this server")
27)
28
29func main() {
30 flag.Parse()
31
32 uiURL, err := url.Parse(*ui)
33 if err != nil {
34 log.Fatalf("proxy: parsing ui addr %q failed: %v\n", *ui, err)
35 }
36 apiURL, err := url.Parse(*api)
37 if err != nil {
38 log.Fatalf("proxy: parsing api addr %q failed: %v\n", *api, err)
39 }
40
41 l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%v", *port))
42 if err != nil {
43 log.Fatalln("proxy: listen failed: ", err)
44 }
45 defer l.Close()
46 fmt.Printf("OK\nListening on http://%v/\n", l.Addr())
47
48 err = http.Serve(l, &httputil.ReverseProxy{
49 FlushInterval: 500 * time.Millisecond,
50 Director: func(r *http.Request) {
51 if strings.HasPrefix(r.URL.Path, "/changes/") || strings.HasPrefix(r.URL.Path, "/projects/") {
52 r.URL.Scheme, r.URL.Host = apiURL.Scheme, apiURL.Host
53 } else {
54 r.URL.Scheme, r.URL.Host = uiURL.Scheme, uiURL.Host
55 }
56 if r.URL.Scheme == "" {
57 r.URL.Scheme = "http"
58 }
59 r.Host, r.URL.Opaque, r.URL.RawQuery = r.URL.Host, r.RequestURI, ""
60 },
61 })
62 if err != nil {
63 log.Fatalln("proxy: serve failed: ", err)
64 }
65}