Address various lint and gocyclo warnings. Fixes #253

This commit is contained in:
Zac Bergquist
2015-10-09 18:35:34 -04:00
parent 17c91152e0
commit f9bc74626d
29 changed files with 293 additions and 258 deletions

View File

@ -58,17 +58,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error)
}
// Connect to FastCGI gateway
var fcgi *FCGIClient
// check if unix socket or tcp
if strings.HasPrefix(rule.Address, "/") || strings.HasPrefix(rule.Address, "unix:") {
if strings.HasPrefix(rule.Address, "unix:") {
rule.Address = rule.Address[len("unix:"):]
}
fcgi, err = Dial("unix", rule.Address)
} else {
fcgi, err = Dial("tcp", rule.Address)
}
fcgi, err := getClient(&rule)
if err != nil {
return http.StatusBadGateway, err
}
@ -102,13 +92,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error)
return http.StatusBadGateway, err
}
// Write the response header
for key, vals := range resp.Header {
for _, val := range vals {
w.Header().Add(key, val)
}
}
w.WriteHeader(resp.StatusCode)
writeHeader(w, resp)
// Write the response body
// TODO: If this has an error, the response will already be
@ -126,6 +110,26 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error)
return h.Next.ServeHTTP(w, r)
}
func getClient(r *Rule) (*FCGIClient, error) {
// check if unix socket or TCP
if trim := strings.HasPrefix(r.Address, "unix"); strings.HasPrefix(r.Address, "/") || trim {
if trim {
r.Address = r.Address[len("unix:"):]
}
return Dial("unix", r.Address)
}
return Dial("tcp", r.Address)
}
func writeHeader(w http.ResponseWriter, r *http.Response) {
for key, vals := range r.Header {
for _, val := range vals {
w.Header().Add(key, val)
}
}
w.WriteHeader(r.StatusCode)
}
func (h Handler) exists(path string) bool {
if _, err := os.Stat(h.Root + path); err == nil {
return true

View File

@ -30,45 +30,45 @@ import (
"sync"
)
const FCGI_LISTENSOCK_FILENO uint8 = 0
const FCGI_HEADER_LEN uint8 = 8
const VERSION_1 uint8 = 1
const FCGI_NULL_REQUEST_ID uint8 = 0
const FCGI_KEEP_CONN uint8 = 1
const FCGIListenSockFileno uint8 = 0
const FCGIHeaderLen uint8 = 8
const Version1 uint8 = 1
const FCGINullRequestID uint8 = 0
const FCGIKeepConn uint8 = 1
const doubleCRLF = "\r\n\r\n"
const (
FCGI_BEGIN_REQUEST uint8 = iota + 1
FCGI_ABORT_REQUEST
FCGI_END_REQUEST
FCGI_PARAMS
FCGI_STDIN
FCGI_STDOUT
FCGI_STDERR
FCGI_DATA
FCGI_GET_VALUES
FCGI_GET_VALUES_RESULT
FCGI_UNKNOWN_TYPE
FCGI_MAXTYPE = FCGI_UNKNOWN_TYPE
BeginRequest uint8 = iota + 1
AbortRequest
EndRequest
Params
Stdin
Stdout
Stderr
Data
GetValues
GetValuesResult
UnknownType
MaxType = UnknownType
)
const (
FCGI_RESPONDER uint8 = iota + 1
FCGI_AUTHORIZER
FCGI_FILTER
Responder uint8 = iota + 1
Authorizer
Filter
)
const (
FCGI_REQUEST_COMPLETE uint8 = iota
FCGI_CANT_MPX_CONN
FCGI_OVERLOADED
FCGI_UNKNOWN_ROLE
RequestComplete uint8 = iota
CantMultiplexConns
Overloaded
UnknownRole
)
const (
FCGI_MAX_CONNS string = "MAX_CONNS"
FCGI_MAX_REQS string = "MAX_REQS"
FCGI_MPXS_CONNS string = "MPXS_CONNS"
MaxConns string = "MAX_CONNS"
MaxRequests string = "MAX_REQS"
MultiplexConns string = "MPXS_CONNS"
)
const (
@ -79,7 +79,7 @@ const (
type header struct {
Version uint8
Type uint8
Id uint16
ID uint16
ContentLength uint16
PaddingLength uint8
Reserved uint8
@ -92,7 +92,7 @@ var pad [maxPad]byte
func (h *header) init(recType uint8, reqID uint16, contentLength int) {
h.Version = 1
h.Type = recType
h.Id = reqID
h.ID = reqID
h.ContentLength = uint16(contentLength)
h.PaddingLength = uint8(-contentLength & 7)
}
@ -110,7 +110,7 @@ func (rec *record) read(r io.Reader) (buf []byte, err error) {
err = errors.New("fcgi: invalid header version")
return
}
if rec.h.Type == FCGI_END_REQUEST {
if rec.h.Type == EndRequest {
err = io.EOF
return
}
@ -126,13 +126,15 @@ func (rec *record) read(r io.Reader) (buf []byte, err error) {
return
}
// FCGIClient implements a FastCGI client, which is a standard for
// interfacing external applications with Web servers.
type FCGIClient struct {
mutex sync.Mutex
rwc io.ReadWriteCloser
h header
buf bytes.Buffer
keepAlive bool
reqId uint16
reqID uint16
}
// Dial connects to the fcgi responder at the specified network address.
@ -148,7 +150,7 @@ func Dial(network, address string) (fcgi *FCGIClient, err error) {
fcgi = &FCGIClient{
rwc: conn,
keepAlive: false,
reqId: 1,
reqID: 1,
}
return
@ -163,7 +165,7 @@ func (c *FCGIClient) writeRecord(recType uint8, content []byte) (err error) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.buf.Reset()
c.h.init(recType, c.reqId, len(content))
c.h.init(recType, c.reqID, len(content))
if err := binary.Write(&c.buf, binary.BigEndian, c.h); err != nil {
return err
}
@ -179,14 +181,14 @@ func (c *FCGIClient) writeRecord(recType uint8, content []byte) (err error) {
func (c *FCGIClient) writeBeginRequest(role uint16, flags uint8) error {
b := [8]byte{byte(role >> 8), byte(role), flags}
return c.writeRecord(FCGI_BEGIN_REQUEST, b[:])
return c.writeRecord(BeginRequest, b[:])
}
func (c *FCGIClient) writeEndRequest(appStatus int, protocolStatus uint8) error {
b := make([]byte, 8)
binary.BigEndian.PutUint32(b, uint32(appStatus))
b[4] = protocolStatus
return c.writeRecord(FCGI_END_REQUEST, b)
return c.writeRecord(EndRequest, b)
}
func (c *FCGIClient) writePairs(recType uint8, pairs map[string]string) error {
@ -334,17 +336,17 @@ func (w *streamReader) Read(p []byte) (n int, err error) {
// Do made the request and returns a io.Reader that translates the data read
// from fcgi responder out of fcgi packet before returning it.
func (c *FCGIClient) Do(p map[string]string, req io.Reader) (r io.Reader, err error) {
err = c.writeBeginRequest(uint16(FCGI_RESPONDER), 0)
err = c.writeBeginRequest(uint16(Responder), 0)
if err != nil {
return
}
err = c.writePairs(FCGI_PARAMS, p)
err = c.writePairs(Params, p)
if err != nil {
return
}
body := newWriter(c, FCGI_STDIN)
body := newWriter(c, Stdin)
if req != nil {
io.Copy(body, req)
}

View File

@ -34,13 +34,13 @@ import (
// test failed if the remote fcgi(script) failed md5 verification
// and output "FAILED" in response
const (
script_file = "/tank/www/fcgic_test.php"
//ip_port = "remote-php-serv:59000"
ip_port = "127.0.0.1:59000"
scriptFile = "/tank/www/fcgic_test.php"
//ipPort = "remote-php-serv:59000"
ipPort = "127.0.0.1:59000"
)
var (
t_ *testing.T = nil
t_ *testing.T
)
type FastCGIServer struct{}
@ -51,7 +51,7 @@ func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
stat := "PASSED"
fmt.Fprintln(resp, "-")
file_num := 0
fileNum := 0
{
length := 0
for k0, v0 := range req.Form {
@ -69,7 +69,7 @@ func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
}
}
if req.MultipartForm != nil {
file_num = len(req.MultipartForm.File)
fileNum = len(req.MultipartForm.File)
for kn, fns := range req.MultipartForm.File {
//fmt.Fprintln(resp, "server:filekey ", kn )
length += len(kn)
@ -101,11 +101,11 @@ func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
fmt.Fprintln(resp, "server:got data length", length)
}
fmt.Fprintln(resp, "-"+stat+"-POST(", len(req.Form), ")-FILE(", file_num, ")--")
fmt.Fprintln(resp, "-"+stat+"-POST(", len(req.Form), ")-FILE(", fileNum, ")--")
}
func sendFcgi(reqType int, fcgi_params map[string]string, data []byte, posts map[string]string, files map[string]string) (content []byte) {
fcgi, err := Dial("tcp", ip_port)
func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[string]string, files map[string]string) (content []byte) {
fcgi, err := Dial("tcp", ipPort)
if err != nil {
log.Println("err:", err)
return
@ -119,16 +119,16 @@ func sendFcgi(reqType int, fcgi_params map[string]string, data []byte, posts map
if len(data) > 0 {
length = len(data)
rd := bytes.NewReader(data)
resp, err = fcgi.Post(fcgi_params, "", rd, rd.Len())
resp, err = fcgi.Post(fcgiParams, "", rd, rd.Len())
} else if len(posts) > 0 {
values := url.Values{}
for k, v := range posts {
values.Set(k, v)
length += len(k) + 2 + len(v)
}
resp, err = fcgi.PostForm(fcgi_params, values)
resp, err = fcgi.PostForm(fcgiParams, values)
} else {
resp, err = fcgi.Get(fcgi_params)
resp, err = fcgi.Get(fcgiParams)
}
default:
@ -142,7 +142,7 @@ func sendFcgi(reqType int, fcgi_params map[string]string, data []byte, posts map
fi, _ := os.Lstat(v)
length += len(k) + int(fi.Size())
}
resp, err = fcgi.PostFile(fcgi_params, values, files)
resp, err = fcgi.PostFile(fcgiParams, values, files)
}
if err != nil {
@ -191,7 +191,7 @@ func generateRandFile(size int) (p string, m string) {
return
}
func Disabled_Test(t *testing.T) {
func DisabledTest(t *testing.T) {
// TODO: test chunked reader
t_ = t
@ -199,7 +199,7 @@ func Disabled_Test(t *testing.T) {
// server
go func() {
listener, err := net.Listen("tcp", ip_port)
listener, err := net.Listen("tcp", ipPort)
if err != nil {
// handle error
log.Println("listener creatation failed: ", err)
@ -212,19 +212,19 @@ func Disabled_Test(t *testing.T) {
time.Sleep(1 * time.Second)
// init
fcgi_params := make(map[string]string)
fcgi_params["REQUEST_METHOD"] = "GET"
fcgi_params["SERVER_PROTOCOL"] = "HTTP/1.1"
fcgiParams := make(map[string]string)
fcgiParams["REQUEST_METHOD"] = "GET"
fcgiParams["SERVER_PROTOCOL"] = "HTTP/1.1"
//fcgi_params["GATEWAY_INTERFACE"] = "CGI/1.1"
fcgi_params["SCRIPT_FILENAME"] = script_file
fcgiParams["SCRIPT_FILENAME"] = scriptFile
// simple GET
log.Println("test:", "get")
sendFcgi(0, fcgi_params, nil, nil, nil)
sendFcgi(0, fcgiParams, nil, nil, nil)
// simple post data
log.Println("test:", "post")
sendFcgi(0, fcgi_params, []byte("c4ca4238a0b923820dcc509a6f75849b=1&7b8b965ad4bca0e41ab51de7b31363a1=n"), nil, nil)
sendFcgi(0, fcgiParams, []byte("c4ca4238a0b923820dcc509a6f75849b=1&7b8b965ad4bca0e41ab51de7b31363a1=n"), nil, nil)
log.Println("test:", "post data (more than 60KB)")
data := ""
@ -240,13 +240,13 @@ func Disabled_Test(t *testing.T) {
data += k0 + "=" + url.QueryEscape(v0) + "&"
}
sendFcgi(0, fcgi_params, []byte(data), nil, nil)
sendFcgi(0, fcgiParams, []byte(data), nil, nil)
log.Println("test:", "post form (use url.Values)")
p0 := make(map[string]string, 1)
p0["c4ca4238a0b923820dcc509a6f75849b"] = "1"
p0["7b8b965ad4bca0e41ab51de7b31363a1"] = "n"
sendFcgi(1, fcgi_params, nil, p0, nil)
sendFcgi(1, fcgiParams, nil, p0, nil)
log.Println("test:", "post forms (256 keys, more than 1MB)")
p1 := make(map[string]string, 1)
@ -257,25 +257,25 @@ func Disabled_Test(t *testing.T) {
k0 := fmt.Sprintf("%x", h.Sum(nil))
p1[k0] = v0
}
sendFcgi(1, fcgi_params, nil, p1, nil)
sendFcgi(1, fcgiParams, nil, p1, nil)
log.Println("test:", "post file (1 file, 500KB)) ")
f0 := make(map[string]string, 1)
path0, m0 := generateRandFile(500000)
f0[m0] = path0
sendFcgi(1, fcgi_params, nil, p1, f0)
sendFcgi(1, fcgiParams, nil, p1, f0)
log.Println("test:", "post multiple files (2 files, 5M each) and forms (256 keys, more than 1MB data")
path1, m1 := generateRandFile(5000000)
f0[m1] = path1
sendFcgi(1, fcgi_params, nil, p1, f0)
sendFcgi(1, fcgiParams, nil, p1, f0)
log.Println("test:", "post only files (2 files, 5M each)")
sendFcgi(1, fcgi_params, nil, nil, f0)
sendFcgi(1, fcgiParams, nil, nil, f0)
log.Println("test:", "post only 1 file")
delete(f0, "m0")
sendFcgi(1, fcgi_params, nil, nil, f0)
sendFcgi(1, fcgiParams, nil, nil, f0)
os.Remove(path0)
os.Remove(path1)