Fix serving FastCGI requests

This commit is contained in:
Trevor Slocum 2020-12-06 22:09:41 -08:00
parent a96e2123fb
commit 055dd08886

View file

@ -4,9 +4,12 @@ import (
"bytes" "bytes"
"io" "io"
"io/ioutil" "io/ioutil"
"log"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"path/filepath"
"strings"
"github.com/yookoala/gofast" "github.com/yookoala/gofast"
) )
@ -46,12 +49,54 @@ func serveFastCGI(c net.Conn, connFactory gofast.ConnFactory, u *url.URL, filePa
Header: header, Header: header,
Body: ioutil.NopCloser(bytes.NewReader(nil)), Body: ioutil.NopCloser(bytes.NewReader(nil)),
Host: u.Host, Host: u.Host,
RemoteAddr: c.RemoteAddr().String(),
} }
gofast. req := gofast.NewRequest(r)
NewHandler( req.Params["CONTENT_TYPE"] = r.Header.Get("Content-Type")
gofast.NewFileEndpoint(filePath)(gofast.BasicSession), req.Params["CONTENT_LENGTH"] = r.Header.Get("Content-Length")
gofast.SimpleClientFactory(connFactory, 0), req.Params["HTTP_HOST"] = r.Host
). req.Params["HTTPS"] = "on"
ServeHTTP(newFakeResponseWriter(c), r) 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)
}
} }