1
// Copyright 2011 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
5
// This file implements CGI from the perspective of a child
25
// Request returns the HTTP request as represented in the current
26
// environment. This assumes the current program is being run
27
// by a web server in a CGI environment.
28
// The returned Request's Body is populated, if applicable.
29
func Request() (*http.Request, error) {
30
r, err := RequestFromMap(envMap(os.Environ()))
34
if r.ContentLength > 0 {
35
r.Body = ioutil.NopCloser(io.LimitReader(os.Stdin, r.ContentLength))
40
func envMap(env []string) map[string]string {
41
m := make(map[string]string)
42
for _, kv := range env {
43
if idx := strings.Index(kv, "="); idx != -1 {
44
m[kv[:idx]] = kv[idx+1:]
50
// RequestFromMap creates an http.Request from CGI variables.
51
// The returned Request's Body field is not populated.
52
func RequestFromMap(params map[string]string) (*http.Request, error) {
53
r := new(http.Request)
54
r.Method = params["REQUEST_METHOD"]
56
return nil, errors.New("cgi: no REQUEST_METHOD in environment")
59
r.Proto = params["SERVER_PROTOCOL"]
61
r.ProtoMajor, r.ProtoMinor, ok = http.ParseHTTPVersion(r.Proto)
63
return nil, errors.New("cgi: invalid SERVER_PROTOCOL version")
67
r.Trailer = http.Header{}
68
r.Header = http.Header{}
70
r.Host = params["HTTP_HOST"]
72
if lenstr := params["CONTENT_LENGTH"]; lenstr != "" {
73
clen, err := strconv.ParseInt(lenstr, 10, 64)
75
return nil, errors.New("cgi: bad CONTENT_LENGTH in environment: " + lenstr)
77
r.ContentLength = clen
80
if ct := params["CONTENT_TYPE"]; ct != "" {
81
r.Header.Set("Content-Type", ct)
84
// Copy "HTTP_FOO_BAR" variables to "Foo-Bar" Headers
85
for k, v := range params {
86
if !strings.HasPrefix(k, "HTTP_") || k == "HTTP_HOST" {
89
r.Header.Add(strings.Replace(k[5:], "_", "-", -1), v)
92
// TODO: cookies. parsing them isn't exported, though.
94
uriStr := params["REQUEST_URI"]
96
// Fallback to SCRIPT_NAME, PATH_INFO and QUERY_STRING.
97
uriStr = params["SCRIPT_NAME"] + params["PATH_INFO"]
98
s := params["QUERY_STRING"]
104
// There's apparently a de-facto standard for this.
105
// http://docstore.mik.ua/orelly/linux/cgi/ch03_02.htm#ch03-35636
106
if s := params["HTTPS"]; s == "on" || s == "ON" || s == "1" {
107
r.TLS = &tls.ConnectionState{HandshakeComplete: true}
111
// Hostname is provided, so we can reasonably construct a URL.
112
rawurl := r.Host + uriStr
114
rawurl = "http://" + rawurl
116
rawurl = "https://" + rawurl
118
url, err := url.Parse(rawurl)
120
return nil, errors.New("cgi: failed to parse host and REQUEST_URI into a URL: " + rawurl)
124
// Fallback logic if we don't have a Host header or the URL
127
url, err := url.Parse(uriStr)
129
return nil, errors.New("cgi: failed to parse REQUEST_URI into a URL: " + uriStr)
134
// Request.RemoteAddr has its port set by Go's standard http
135
// server, so we do here too. We don't have one, though, so we
137
r.RemoteAddr = net.JoinHostPort(params["REMOTE_ADDR"], "0")
142
// Serve executes the provided Handler on the currently active CGI
143
// request, if any. If there's no current CGI environment
144
// an error is returned. The provided handler may be nil to use
145
// http.DefaultServeMux.
146
func Serve(handler http.Handler) error {
147
req, err := Request()
152
handler = http.DefaultServeMux
156
header: make(http.Header),
157
bufw: bufio.NewWriter(os.Stdout),
159
handler.ServeHTTP(rw, req)
160
rw.Write(nil) // make sure a response is sent
161
if err = rw.bufw.Flush(); err != nil {
167
type response struct {
174
func (r *response) Flush() {
178
func (r *response) Header() http.Header {
182
func (r *response) Write(p []byte) (n int, err error) {
184
r.WriteHeader(http.StatusOK)
186
return r.bufw.Write(p)
189
func (r *response) WriteHeader(code int) {
191
// Note: explicitly using Stderr, as Stdout is our HTTP output.
192
fmt.Fprintf(os.Stderr, "CGI attempted to write header twice on request for %s", r.req.URL)
196
fmt.Fprintf(r.bufw, "Status: %d %s\r\n", code, http.StatusText(code))
198
// Set a default Content-Type
199
if _, hasType := r.header["Content-Type"]; !hasType {
200
r.header.Add("Content-Type", "text/html; charset=utf-8")
203
r.header.Write(r.bufw)
204
r.bufw.WriteString("\r\n")