summaryrefslogtreecommitdiff
path: root/main.go
blob: bd85dcc4cea2c09619f8eb1713dfc9e2c2416124 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main

import (
	"fmt"
	"io"
	"strings"
	"net"
	"net/http"
	"net/url"
	log "github.com/sirupsen/logrus"
)


//type Endpoint struct {
//	path string
//	address string
//}
//
//
//func proxy(w http.ResponseWriter, req *http.Request, end Endpoint) {
//}
//
//func makeProxiedRequest(w http.ResponseWriter, req *http.Request, end Endpoint) {
//	
//}
//

func main() {
	const addr = "localhost:3333"
	log.Info("configuring reverse proxy...")
	origin, err := url.Parse("http://localhost:8000")
	if err != nil {
		log.Fatal(err)
	}
	log.Infof("listening on %v", addr)
	http.ListenAndServe(addr, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		req.Host = origin.Host
		req.URL.Host = origin.Host
		req.URL.Scheme = origin.Scheme
		req.RequestURI = ""
		// set X-Forwarded-For
		forwardedFor, _, _ := net.SplitHostPort(req.RemoteAddr)
		req.Header.Set("X-Forwarded-For", forwardedFor)
		response, err := http.DefaultClient.Do(req)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintf(w, "%v", err)
			log.Fatal(err)
		}

		// copy header
		for key, values := range response.Header {
			for _, value := range values {
				w.Header().Add(key, value)
			}
		}

		// get trailer keys
		trailerKeys := []string{}
		for key := range response.Trailer {
			trailerKeys = append(trailerKeys, key)
		}
		if (len(trailerKeys) > 0) {
			w.Header().Set("Trailer", strings.Join(trailerKeys, ","))
		}

		w.WriteHeader(response.StatusCode)

		// copy body
		io.Copy(w, response.Body)
	}))
}