reworked reverse proxy domain router to utilize transport to throw 400 bad requests instead of having the server handle it.

This commit is contained in:
George Shaw 2018-01-24 15:18:11 -06:00
parent 384d3c247f
commit b9e450ec5d
3 changed files with 50 additions and 25 deletions

View file

@ -19,11 +19,6 @@ func (con *Controller) ServeHTTP(res http.ResponseWriter, req *http.Request) {
path = (con.Directory + con.DocumentRoot + path)
}
if strings.HasSuffix(path, "throw400") {
http.Error(res, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
if strings.HasSuffix(path, "index.html") {
if con.checkAuth(res, req) == true {
http.Redirect(res, req, "gPanel.html", http.StatusFound)

48
pkg/router/proxy.go Normal file
View file

@ -0,0 +1,48 @@
package router
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
type customTrip struct{}
func (customTrip) RoundTrip(req *http.Request) (*http.Response, error) {
if req.URL.Host == "fail" {
if req.Body != nil {
io.Copy(ioutil.Discard, req.Body)
defer req.Body.Close()
}
return &http.Response{
StatusCode: http.StatusBadRequest,
Status: http.StatusText(http.StatusBadRequest),
Body: ioutil.NopCloser(&bytes.Reader{}),
}, nil
}
return http.DefaultTransport.RoundTrip(req)
}
func proxyDirector(req *http.Request) {
host := req.Host
if strings.Count(host, ".") == 2 {
host = strings.SplitN(host, ".", 2)[1] //Remove sub-domain
}
req.Header.Set("Host", req.Host)
req.URL.Scheme = "http"
mutex.Lock()
if d, ok := domainToPort[host]; ok {
mutex.Unlock()
req.URL.Host = "127.0.0.1:" + strconv.Itoa(d)
} else {
mutex.Unlock()
req.URL.Host = "fail"
}
}

View file

@ -7,7 +7,6 @@ import (
"time"
"log"
"strings"
"sync"
"github.com/Ennovar/gPanel/pkg/database"
@ -58,25 +57,8 @@ func New() *Router {
server = http.Server{
Addr: "localhost:" + strconv.Itoa(r.Port),
Handler: &httputil.ReverseProxy{
Director: func(req *http.Request) {
host := req.Host
if strings.Count(host, ".") == 2 {
host = strings.SplitN(host, ".", 2)[1] //Remove sub-domain
}
req.Header.Set("Host", req.Host)
req.URL.Scheme = "http"
mutex.Lock()
if d, ok := domainToPort[host]; ok {
mutex.Unlock()
req.URL.Host = "127.0.0.1:" + strconv.Itoa(d)
} else {
mutex.Unlock()
req.URL.Host = "127.0.0.1:2082"
req.URL.Path = "/throw400"
}
},
Director: proxyDirector,
Transport: customTrip{},
},
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,