blob: 4ac4c87539e5735e8ea469ff4839cb8271952d59 (
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
|
package handlers
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/LMBishop/gunnel/pkg/store"
)
func ReverseProxy(storeService store.Service) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
hostParts := strings.Split(r.Host, ".")
slug := hostParts[0]
rule := storeService.GetRuleBySlug(slug)
if rule == nil {
http.Error(w, fmt.Sprintf("Unknown peer '%s'", slug), http.StatusNotFound)
return
}
targetURL, err := url.Parse("http://" + rule.Peer.IPAddr.String() + ":" + rule.Port)
rule.LastUsed = time.Now()
if err != nil {
http.Error(w, "Invalid target URL", http.StatusInternalServerError)
return
}
proxy := httputil.NewSingleHostReverseProxy(targetURL)
proxy.ServeHTTP(w, r)
}
}
|