Fix serving FastCGI requests

This commit is contained in:
Trevor Slocum 2020-12-06 22:09:41 -08:00
parent a96e2123fb
commit 055dd08886
1 changed files with 51 additions and 6 deletions

View File

@ -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)
}
}