Commit 113b175d authored by Matthew Holt's avatar Matthew Holt

Refactored fastcgi middleware

parent 40bf7c52
// Package fastcgi has middleware that acts as a FastCGI client. Requests // Package fastcgi has middleware that acts as a FastCGI client. Requests
// that get forwarded to FastCGI stop the middleware execution chain. // that get forwarded to FastCGI stop the middleware execution chain.
// The most common use for this layer is to serve PHP websites via php-fpm. // The most common use for this package is to serve PHP websites via php-fpm.
package fastcgi package fastcgi
import ( import (
...@@ -17,95 +17,114 @@ import ( ...@@ -17,95 +17,114 @@ import (
func New(c middleware.Controller) (middleware.Middleware, error) { func New(c middleware.Controller) (middleware.Middleware, error) {
root := c.Root() root := c.Root()
var rules []fastCgi rules, err := parse(c)
for c.Next() { if err != nil {
rule := fastCgi{} return nil, err
if !c.Args(&rule.path, &rule.address) {
return nil, c.ArgErr()
}
rules = append(rules, rule)
} }
return func(next middleware.Handler) middleware.Handler { return func(next middleware.Handler) middleware.Handler {
return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) { return Handler{Next: next, Rules: rules, Root: root}
}, nil
servedFcgi := false }
for _, rule := range rules {
if middleware.Path(r.URL.Path).Matches(rule.path) { // Handler is a middleware type that can handle requests as a FastCGI client.
servedFcgi = true type Handler struct {
Next middleware.Handler
// Get absolute file paths Root string
absPath, err := filepath.Abs(root + r.URL.Path) Rules []Rule
if err != nil { }
return http.StatusInternalServerError, err
} // ServeHTTP satisfies the middleware.Handler interface.
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// Get absolute file path to website root servedFcgi := false
absRootPath, err := filepath.Abs(root) for _, rule := range h.Rules {
if err != nil { if middleware.Path(r.URL.Path).Matches(rule.Path) {
return http.StatusInternalServerError, err servedFcgi = true
}
// Get absolute file paths
// Separate remote IP and port absPath, err := filepath.Abs(h.Root + r.URL.Path)
var ip, port string if err != nil {
if idx := strings.Index(r.RemoteAddr, ":"); idx > -1 { return http.StatusInternalServerError, err
ip = r.RemoteAddr[idx:]
port = r.RemoteAddr[:idx]
} else {
ip = r.RemoteAddr
}
// TODO: Do we really have to make this map from scratch for each request?
// TODO: We have quite a few more to map, too.
env := make(map[string]string)
env["SERVER_SOFTWARE"] = "caddy" // TODO: Obtain version info...
env["SERVER_PROTOCOL"] = r.Proto
env["SCRIPT_FILENAME"] = absPath
env["REMOTE_ADDR"] = ip
env["REMOTE_PORT"] = port
env["REQUEST_METHOD"] = r.Method
env["QUERY_STRING"] = r.URL.RawQuery
env["DOCUMENT_URI"] = r.URL.Path
env["DOCUMENT_ROOT"] = absRootPath
fcgi, err := Dial("tcp", rule.address)
if err != nil {
return http.StatusBadGateway, err
}
resp, err := fcgi.Get(env)
if err != nil && err != io.EOF {
return http.StatusBadGateway, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return http.StatusBadGateway, err
}
for key, vals := range resp.Header {
for _, val := range vals {
w.Header().Add(key, val)
}
}
w.WriteHeader(resp.StatusCode)
w.Write(body)
break
}
} }
if !servedFcgi { // Get absolute file path to website root
return next.ServeHTTP(w, r) absRootPath, err := filepath.Abs(h.Root)
if err != nil {
return http.StatusInternalServerError, err
} }
return 0, nil // Separate remote IP and port
}) var ip, port string
}, nil if idx := strings.Index(r.RemoteAddr, ":"); idx > -1 {
ip = r.RemoteAddr[idx:]
port = r.RemoteAddr[:idx]
} else {
ip = r.RemoteAddr
}
// TODO: Do we really have to make this map from scratch for each request?
// TODO: We have quite a few more to map, too.
env := make(map[string]string)
env["SERVER_SOFTWARE"] = "caddy" // TODO: Obtain version info...
env["SERVER_PROTOCOL"] = r.Proto
env["SCRIPT_FILENAME"] = absPath
env["REMOTE_ADDR"] = ip
env["REMOTE_PORT"] = port
env["REQUEST_METHOD"] = r.Method
env["QUERY_STRING"] = r.URL.RawQuery
env["DOCUMENT_URI"] = r.URL.Path
env["DOCUMENT_ROOT"] = absRootPath
fcgi, err := Dial("tcp", rule.Address)
if err != nil {
return http.StatusBadGateway, err
}
resp, err := fcgi.Get(env)
if err != nil && err != io.EOF {
return http.StatusBadGateway, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return http.StatusBadGateway, err
}
for key, vals := range resp.Header {
for _, val := range vals {
w.Header().Add(key, val)
}
}
w.WriteHeader(resp.StatusCode)
w.Write(body)
break
}
}
if !servedFcgi {
return h.Next.ServeHTTP(w, r)
}
return 0, nil
}
func parse(c middleware.Controller) ([]Rule, error) {
var rules []Rule
for c.Next() {
var rule Rule
if !c.Args(&rule.Path, &rule.Address) {
return rules, c.ArgErr()
}
rules = append(rules, rule)
}
return rules, nil
} }
type fastCgi struct { // Rule represents a FastCGI handling rule.
path string type Rule struct {
address string Path, Address string
} }
...@@ -9,7 +9,7 @@ import ( ...@@ -9,7 +9,7 @@ import (
"github.com/mholt/caddy/middleware" "github.com/mholt/caddy/middleware"
) )
// New instantiates a new Rewrites middleware. // New instantiates a new Redirect middleware.
func New(c middleware.Controller) (middleware.Middleware, error) { func New(c middleware.Controller) (middleware.Middleware, error) {
rules, err := parse(c) rules, err := parse(c)
if err != nil { if err != nil {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment