Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Last active June 16, 2025 01:46
Show Gist options
  • Select an option

  • Save masakielastic/e78441ba49eeaeab77b91d072192bb82 to your computer and use it in GitHub Desktop.

Select an option

Save masakielastic/e78441ba49eeaeab77b91d072192bb82 to your computer and use it in GitHub Desktop.
Go で FastCGI サーバー

Go で FastCGI サーバー

Go のプログラムを実行して FCGI サーバーを起動させます。

go run main.go

ターミナルに次のメッセージが表示されます。

Listen at: /tmp/fastcgi.sock

別のターミナルで次のコマンドを実行します。cgi-fcgi はあらかじめインストールしておく必要があります。

env REQUEST_METHOD=GET \
    SERVER_PROTOCOL=HTTP/1.1 \
    SCRIPT_NAME=/ \
    cgi-fcgi -bind -connect /tmp/fastcgi.sock

実行結果は次のようになります。

Status: 200 OK
Content-Type: text/plain; charset=utf-8
Date: Mon, 16 Jun 2025 01:30:07 GMT

Hello

環境変数が不足する場合、次のようなエラーになります。

env REQUEST_METHOD=GET \
    SCRIPT_NAME=/ \
    cgi-fcgi -bind -connect /tmp/fastcgi.sock
cgi: invalid SERVER_PROTOCOL versionStatus: 500 Internal Server Error
Content-Type: text/plain; charset=utf-8
Date: Mon, 16 Jun 2025 01:44:46 GMT
package main
// https://github.com/link-u/the-simplest-fastcgi-server-in-this-world
import (
"fmt"
"net"
"net/http"
"net/http/fcgi"
"os"
)
func main() {
var sockFile = "/tmp/fastcgi.sock"
_ = os.Remove(sockFile)
fmt.Printf("Listen at: %s\n", sockFile)
listener, err := net.Listen("unix", sockFile)
if err != nil {
panic(err)
}
http.HandleFunc("/", handler)
err = fcgi.Serve(listener, nil)
if err != nil {
panic(err)
}
}
func handler(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte("Hello\n"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment