Programming Tips - Go Language: Example CGI program

Date: 2019sep11 Language: Go Keywords: golang Q. Go Language: Example CGI program A.
package main import ( "fmt" "net/http" "net/http/cgi" ) func ServeHTTP(writer http.ResponseWriter, request *http.Request) { header := writer.Header() header.Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintln(writer, "Method:", request.Method) fmt.Fprintln(writer, "URL:", request.URL.String()) query := request.URL.Query() for key := range query { fmt.Fprintln(writer, "Query", key + ":", query.Get(key)) } // How to get your own field myfield := query.Get("myfield"); fmt.Fprintln(writer, "The exact myfield=" + myfield); request.ParseForm() form := request.Form for key := range form { fmt.Fprintln(writer, "Form", key + ":", form.Get(key)) } post := request.PostForm for key := range post { fmt.Fprintln(writer, "PostForm", key + ":", post.Get(key)) } fmt.Fprintln(writer, "RemoteAddr:", request.RemoteAddr) if referer := request.Referer(); len(referer) > 0 { fmt.Fprintln(writer, "Referer:", referer) } if ua := request.UserAgent(); len(ua) > 0 { fmt.Fprintln(writer, "UserAgent:", ua) } for _, cookie := range request.Cookies() { fmt.Fprintln(writer, "Cookie", cookie.Name + ":", cookie.Value, cookie.Path, cookie.Domain, cookie.RawExpires) } } func main() { err := cgi.Serve(http.HandlerFunc(ServeHTTP)); if err != nil { fmt.Println(err) } } // go build -ldflags "-s -w" -o example.cgi example.go // Based on https://gist.github.com/larryli/8299764