init: Initial commit
This commit is contained in:
42
app/server/proxy.go
Normal file
42
app/server/proxy.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
|
||||
"git.secnex.io/secnex/api-gateway/config"
|
||||
)
|
||||
|
||||
type Proxy struct {
|
||||
proxies []config.ProxyConfiguration
|
||||
handlers map[string]http.Handler
|
||||
}
|
||||
|
||||
func NewProxy(proxies []config.ProxyConfiguration) *Proxy {
|
||||
handlers := make(map[string]http.Handler)
|
||||
for _, proxy := range proxies {
|
||||
backend, err := url.Parse(proxy.Target)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to parse proxy target: %v", err)
|
||||
}
|
||||
p := httputil.NewSingleHostReverseProxy(backend)
|
||||
originalDirector := p.Director
|
||||
p.Director = func(r *http.Request) {
|
||||
originalDirector(r)
|
||||
r.Host = backend.Host
|
||||
}
|
||||
handlers[proxy.Host] = p
|
||||
}
|
||||
return &Proxy{proxies: proxies, handlers: handlers}
|
||||
}
|
||||
|
||||
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
handler, ok := p.handlers[r.Host]
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
}
|
||||
Reference in New Issue
Block a user