-
Notifications
You must be signed in to change notification settings - Fork 6
/
http.go
135 lines (122 loc) · 3.47 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package gofcgisrv
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/textproto"
"strings"
)
func parseEnv(envStr string) (key, value string, err error) {
if idx := strings.Index(envStr, "="); idx > 0 {
return envStr[:idx], envStr[idx+1:], nil
}
return "", "", errors.New("Not a valid environment string.")
}
// HTTPEnv sets up an environment with standard HTTP/CGI variables.
func HTTPEnv(start []string, r *http.Request) []string {
envMap := make(map[string]string)
env := make([]string, 0, 10)
for _, e := range start {
if k, v, err := parseEnv(e); err == nil {
envMap[k] = v
env = append(env, e)
}
}
appendEnv := func(key, value string) {
if _, ok := envMap[key]; !ok {
env = append(env, key+"="+value)
}
}
appendEnv("SCRIPT_NAME", "")
appendEnv("REQUEST_METHOD", r.Method)
appendEnv("SERVER_PROTOCOL", "HTTP/1.1")
appendEnv("GATEWAY_INTERFACE", "CGI/1.1")
appendEnv("REQUEST_URI", r.URL.String())
host, port, err := net.SplitHostPort(r.Host)
if err != nil {
host, port = r.Host, "80"
}
appendEnv("REMOTE_ADDR", r.RemoteAddr)
appendEnv("SERVER_NAME", host)
appendEnv("SERVER_PORT", port)
appendEnv("QUERY_STRING", r.URL.RawQuery)
if t := r.Header.Get("Content-type"); t != "" {
appendEnv("CONTENT_TYPE", t)
}
for key := range r.Header {
upper := strings.ToUpper(key)
cgikey := "HTTP_" + strings.Replace(upper, "-", "_", 1)
appendEnv(cgikey, r.Header.Get(key))
}
return env
}
// ServeHTTP serves an http request using FastCGI
func ServeHTTP(s Requester, env []string, w http.ResponseWriter, r *http.Request) {
env = HTTPEnv(env, r)
var body io.Reader = r.Body
// CONTENT_LENGTH is special and important
if l := r.Header.Get("Content-length"); l != "" {
env = append(env, "CONTENT_LENGTH="+l)
} else if r.Body != nil {
// Some different transfer-encoding, presumably.
// Read the body into a buffer
// If there is an error we'll just ignore it for now.
buf := bytes.NewBuffer(nil)
io.Copy(buf, r.Body)
r.Body.Close()
body = buf
env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", buf.Len()))
} else {
env = append(env, "CONTENT_LENGTH=0")
}
outreader, outwriter := io.Pipe()
stderr := bytes.NewBuffer(nil)
done := make(chan struct{})
go func() {
defer close(done)
defer outwriter.Close()
err := s.Request(env, body, outwriter, stderr)
if err != nil {
// There should not be anything in stdout. We should really guard against that.
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}()
// Add any headers produced by the application, and skip to the response.
ProcessResponse(outreader, w, r)
<-done
}
// ProcessResponse adds any returned header data to the response header and sends the rest
// to the response body.
func ProcessResponse(stdout io.Reader, w http.ResponseWriter, r *http.Request) error {
bufReader := bufio.NewReader(stdout)
mimeReader := textproto.NewReader(bufReader)
hdr, err := mimeReader.ReadMIMEHeader()
if err != nil {
// We got nothing! Assume there is an error. Should be more robust.
return err
}
if err == nil {
for k, vals := range hdr {
for _, v := range vals {
w.Header().Add(k, v)
}
}
}
statusCode := http.StatusOK
if status := hdr.Get("Status"); status != "" {
delete(w.Header(), "Status")
// Parse the status code
var code int
if n, _ := fmt.Sscanf(status, "%d", &code); n == 1 {
statusCode = int(code)
}
}
// Are there other fields we need to rewrite? Probably!
w.WriteHeader(statusCode)
io.Copy(w, bufReader)
return nil
}