summaryrefslogtreecommitdiff
path: root/pkg/prxy/prxy.go
blob: 0e6e8c31a39d4925484136cb44dae1400836da10 (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
package prxy

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"

	"github.com/xlgmokha/x/pkg/x"
)

func New(routes map[string]string) http.Handler {
	mapped := map[string]*url.URL{}
	for source, destination := range routes {
		mapped[source] = x.Must(url.Parse(destination))
	}

	return &httputil.ReverseProxy{
		Director: func(r *http.Request) {
			host, _, err := net.SplitHostPort(r.Host)
			if err != nil {
				fmt.Printf("%v\n", err)
				return
			}

			destination := mapped[host]
			r.URL.Scheme = destination.Scheme
			r.Host = destination.Host
			r.URL.Host = destination.Host
		},
		Transport:     http.DefaultTransport,
		FlushInterval: -1,
		ErrorLog:      nil,
		ModifyResponse: func(r *http.Response) error {
			r.Header.Add("Via", fmt.Sprintf("%v gtwy", r.Proto))
			return nil
		},
		ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
			log.Println(err)
		},
	}
}