Go Documentation

Package cgi

Package cgi implements CGI handling.

Overview

A CGI script is a program that generates dynamic web content. It's run by a web server (like Apache or Nginx) when a user requests a specific URL. The web server passes information about the request (like query parameters, headers, and the request method) to the CGI script as environment variables. The script then processes this information and writes its output (typically HTML) to standard output. The web server captures this output and sends it back to the client's browser.

The cgi package in Go provides tools to help you write CGI scripts. It makes it easier to parse incoming CGI environment variables and to construct valid HTTP responses.

CGI Environment Variables

When a CGI script is executed, the web server sets a number of environment variables that provide context about the request. Some common ones include:

Handling Requests

The cgi package provides the Request struct to represent an incoming CGI request. You can parse the request details using functions like ReadRequest.

Response Generation

The cgi package also helps in generating the HTTP response. You'll typically set HTTP headers and write the response body to standard output. The cgi.ServePage function can be used to easily serve an HTML page.

Basic Example

Here's a simple example of a Go CGI script:

package main

import (
	_ "net/http"
	_ "net/http/cgi"
	"fmt"
	"os"
)

func main() {
	// Handle CGI requests. The default handler writes the response.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Go CGI Example</title>
    <style>
        body { font-family: sans-serif; background-color: #f0f0f0; }
        h1 { color: #333; }
    </style>
</head>
<body>
    <h1>Hello from Go CGI!</h1>
    <p>Request Method: %s</p>
    <p>Query String: %s</p>
</body>
</html>`, r.Method, r.URL.RawQuery)
	})

	// Serve CGI requests.
	if err := cgi.ListenAndServe(nil); err != nil {
		fmt.Fprintf(os.Stderr, "Error starting CGI server: %v\n", err)
		os.Exit(1)
	}
}

Package Contents

Constants

There are no exported constants in this package.

Variables

There are no exported variables in this package.

Functions

func ParseGetenv() (mapstring, error)

ParseGetenv parses the CGI environment variables. It returns a map of variable names to their values, or an error if parsing fails.

func ParseGetenv() (mapstring, error)

func ListenAndServe(handler http.Handler) error

ListenAndServe serves CGI requests with the given handler. If handler is nil, it uses http.DefaultServeMux.

func ListenAndServe(handler http.Handler) error

Imported By