From 055dd08886799eb3c8658e6032b4fc40750910a8 Mon Sep 17 00:00:00 2001 From: Trevor Slocum Date: Sun, 6 Dec 2020 22:09:41 -0800 Subject: [PATCH] Fix serving FastCGI requests --- serve_fcgi.go | 57 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/serve_fcgi.go b/serve_fcgi.go index 9d89f25..3e52062 100644 --- a/serve_fcgi.go +++ b/serve_fcgi.go @@ -4,9 +4,12 @@ import ( "bytes" "io" "io/ioutil" + "log" "net" "net/http" "net/url" + "path/filepath" + "strings" "github.com/yookoala/gofast" ) @@ -46,12 +49,54 @@ func serveFastCGI(c net.Conn, connFactory gofast.ConnFactory, u *url.URL, filePa Header: header, Body: ioutil.NopCloser(bytes.NewReader(nil)), Host: u.Host, + RemoteAddr: c.RemoteAddr().String(), } - gofast. - NewHandler( - gofast.NewFileEndpoint(filePath)(gofast.BasicSession), - gofast.SimpleClientFactory(connFactory, 0), - ). - ServeHTTP(newFakeResponseWriter(c), r) + req := gofast.NewRequest(r) + req.Params["CONTENT_TYPE"] = r.Header.Get("Content-Type") + req.Params["CONTENT_LENGTH"] = r.Header.Get("Content-Length") + req.Params["HTTP_HOST"] = r.Host + req.Params["HTTPS"] = "on" + req.Params["GATEWAY_INTERFACE"] = "CGI/1.1" + req.Params["REMOTE_ADDR"] = strings.SplitN(c.RemoteAddr().String(), ":", 2)[0] + req.Params["REMOTE_PORT"] = "1965" + req.Params["SERVER_PORT"] = "1965" + req.Params["SERVER_NAME"] = r.Host + req.Params["SERVER_PROTOCOL"] = r.Proto + req.Params["SERVER_SOFTWARE"] = "twins" + req.Params["REDIRECT_STATUS"] = "200" + req.Params["REQUEST_METHOD"] = r.Method + req.Params["REQUEST_URI"] = r.RequestURI + req.Params["QUERY_STRING"] = r.URL.RawQuery + req.Params["DOCUMENT_ROOT"] = filepath.Dir(filePath) + req.Params["DOCUMENT_URI"] = r.URL.Path + req.Params["SCRIPT_FILENAME"] = filePath + req.Params["SCRIPT_NAME"] = filepath.Base(filePath) + + w := newFakeResponseWriter(c) + + client, err := gofast.SimpleClientFactory(connFactory, 0)() + if err != nil { + log.Printf("FastCGI Error: %s", err) + http.Error(w, "Failed to connect to FastCGI server", http.StatusInternalServerError) + return + } + + resp, err := client.Do(req) + if err != nil { + log.Printf("FastCGI Error: %s", err) + http.Error(w, "Failed to connect to FastCGI server", http.StatusInternalServerError) + return + } + + errBuffer := new(bytes.Buffer) + err = resp.WriteTo(w, errBuffer) + if err != nil { + log.Printf("FastCGI Error: %s", err) + http.Error(w, "Failed to connect to FastCGI server", http.StatusInternalServerError) + return + } else if errBuffer.Len() > 0 { + log.Printf("FastCGI Error: %s", errBuffer.String()) + http.Error(w, "Failed to connect to FastCGI server", http.StatusInternalServerError) + } }