github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/net/http/cgi/child.go (about) 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. 4 5 // This file implements CGI from the perspective of a child 6 // process. 7 8 package cgi 9 10 import ( 11 "bufio" 12 "crypto/tls" 13 "errors" 14 "fmt" 15 "io" 16 "io/ioutil" 17 "net" 18 "net/http" 19 "net/url" 20 "os" 21 "strconv" 22 "strings" 23 ) 24 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())) 31 if err != nil { 32 return nil, err 33 } 34 if r.ContentLength > 0 { 35 r.Body = ioutil.NopCloser(io.LimitReader(os.Stdin, r.ContentLength)) 36 } 37 return r, nil 38 } 39 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:] 45 } 46 } 47 return m 48 } 49 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"] 55 if r.Method == "" { 56 return nil, errors.New("cgi: no REQUEST_METHOD in environment") 57 } 58 59 r.Proto = params["SERVER_PROTOCOL"] 60 var ok bool 61 r.ProtoMajor, r.ProtoMinor, ok = http.ParseHTTPVersion(r.Proto) 62 if !ok { 63 return nil, errors.New("cgi: invalid SERVER_PROTOCOL version") 64 } 65 66 r.Close = true 67 r.Trailer = http.Header{} 68 r.Header = http.Header{} 69 70 r.Host = params["HTTP_HOST"] 71 72 if lenstr := params["CONTENT_LENGTH"]; lenstr != "" { 73 clen, err := strconv.ParseInt(lenstr, 10, 64) 74 if err != nil { 75 return nil, errors.New("cgi: bad CONTENT_LENGTH in environment: " + lenstr) 76 } 77 r.ContentLength = clen 78 } 79 80 if ct := params["CONTENT_TYPE"]; ct != "" { 81 r.Header.Set("Content-Type", ct) 82 } 83 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" { 87 continue 88 } 89 r.Header.Add(strings.Replace(k[5:], "_", "-", -1), v) 90 } 91 92 // TODO: cookies. parsing them isn't exported, though. 93 94 uriStr := params["REQUEST_URI"] 95 if uriStr == "" { 96 // Fallback to SCRIPT_NAME, PATH_INFO and QUERY_STRING. 97 uriStr = params["SCRIPT_NAME"] + params["PATH_INFO"] 98 s := params["QUERY_STRING"] 99 if s != "" { 100 uriStr += "?" + s 101 } 102 } 103 if r.Host != "" { 104 // Hostname is provided, so we can reasonably construct a URL, 105 // even if we have to assume 'http' for the scheme. 106 rawurl := "http://" + r.Host + uriStr 107 url, err := url.Parse(rawurl) 108 if err != nil { 109 return nil, errors.New("cgi: failed to parse host and REQUEST_URI into a URL: " + rawurl) 110 } 111 r.URL = url 112 } 113 // Fallback logic if we don't have a Host header or the URL 114 // failed to parse 115 if r.URL == nil { 116 url, err := url.Parse(uriStr) 117 if err != nil { 118 return nil, errors.New("cgi: failed to parse REQUEST_URI into a URL: " + uriStr) 119 } 120 r.URL = url 121 } 122 123 // There's apparently a de-facto standard for this. 124 // http://docstore.mik.ua/orelly/linux/cgi/ch03_02.htm#ch03-35636 125 if s := params["HTTPS"]; s == "on" || s == "ON" || s == "1" { 126 r.TLS = &tls.ConnectionState{HandshakeComplete: true} 127 } 128 129 // Request.RemoteAddr has its port set by Go's standard http 130 // server, so we do here too. We don't have one, though, so we 131 // use a dummy one. 132 r.RemoteAddr = net.JoinHostPort(params["REMOTE_ADDR"], "0") 133 134 return r, nil 135 } 136 137 // Serve executes the provided Handler on the currently active CGI 138 // request, if any. If there's no current CGI environment 139 // an error is returned. The provided handler may be nil to use 140 // http.DefaultServeMux. 141 func Serve(handler http.Handler) error { 142 req, err := Request() 143 if err != nil { 144 return err 145 } 146 if handler == nil { 147 handler = http.DefaultServeMux 148 } 149 rw := &response{ 150 req: req, 151 header: make(http.Header), 152 bufw: bufio.NewWriter(os.Stdout), 153 } 154 handler.ServeHTTP(rw, req) 155 rw.Write(nil) // make sure a response is sent 156 if err = rw.bufw.Flush(); err != nil { 157 return err 158 } 159 return nil 160 } 161 162 type response struct { 163 req *http.Request 164 header http.Header 165 bufw *bufio.Writer 166 headerSent bool 167 } 168 169 func (r *response) Flush() { 170 r.bufw.Flush() 171 } 172 173 func (r *response) Header() http.Header { 174 return r.header 175 } 176 177 func (r *response) Write(p []byte) (n int, err error) { 178 if !r.headerSent { 179 r.WriteHeader(http.StatusOK) 180 } 181 return r.bufw.Write(p) 182 } 183 184 func (r *response) WriteHeader(code int) { 185 if r.headerSent { 186 // Note: explicitly using Stderr, as Stdout is our HTTP output. 187 fmt.Fprintf(os.Stderr, "CGI attempted to write header twice on request for %s", r.req.URL) 188 return 189 } 190 r.headerSent = true 191 fmt.Fprintf(r.bufw, "Status: %d %s\r\n", code, http.StatusText(code)) 192 193 // Set a default Content-Type 194 if _, hasType := r.header["Content-Type"]; !hasType { 195 r.header.Add("Content-Type", "text/html; charset=utf-8") 196 } 197 198 r.header.Write(r.bufw) 199 r.bufw.WriteString("\r\n") 200 r.bufw.Flush() 201 }