summaryrefslogtreecommitdiff
path: root/cmd/gtwy/main.go
blob: 9b21c149ed0f1ef1046e9cfdb2be089e83a8d599 (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
package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"strings"
	"time"
)

func NewProxy(from, to string) http.Handler {
	return &httputil.ReverseProxy{
		Director: func(r *http.Request) {
			log.Printf("%v (from: %v to: %v)\n", r.URL, from, to)
			r.URL.Scheme = "http"
			r.Host = to
			r.URL.Host = to
			r.URL.Path = strings.TrimPrefix(r.URL.Path, strings.TrimSuffix(from, "/*"))
			r.URL.RawPath = strings.TrimPrefix(r.URL.RawPath, strings.TrimSuffix(from, "/*"))
		},
		Transport:     http.DefaultTransport,
		FlushInterval: -1,
		ErrorLog:      nil,
		ModifyResponse: func(r *http.Response) error {
			r.Header.Add("Via", fmt.Sprintf("%v gateway", r.Proto))
			return nil
		},
		ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
			log.Println(err)
		},
	}
}

func main() {
	mux := http.NewServeMux()
	mux.Handle("/idp/", NewProxy("/idp", "localhost:8282"))
	mux.Handle("/sp/", NewProxy("/sp", "localhost:8283"))

	log.Fatal((&http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 10 * time.Second,
		ReadTimeout:       30 * time.Second,
		WriteTimeout:      2 * time.Minute,
		IdleTimeout:       5 * time.Minute,
		ErrorLog:          log.Default(),
	}).ListenAndServe())
}