aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: dad740bdb561e8078fdc9301895997292fe56b38 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main

import (
	"flag"
	"io/fs"
	"log"
	"net"
	"net/http"
	"net/http/cgi"
	"os"
	"os/signal"
	"strconv"
	"strings"
)

func main() {
	path := flag.String("path", "", "Path to the cgi binary")
	dir := flag.String("dir", "", "set a different working directory from the base path of 'path'")
	env := flag.String("env", "", "set environment variables for the CGI process")
	prefix := flag.String("uri-prefix", "/", "set the URL prefix when the CGI process is hosted in a sub directory")
	socketMode := flag.String("mode", "777", "set the filesystem mode when using a unix socket")
	addr := flag.String("listen", "127.0.0.1:8080", "set the listen address")
	flag.Parse()

	listenAddr := *addr
	listenType := "unix"
	switch listenAddr[0] {
	case ':', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		listenType = "tcp"
	}
	if listenType == "unix" {
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt)
		go func() {
			<-c
			os.Remove(listenAddr)
			os.Exit(0)
		}()
	}
	l, err := net.Listen(listenType, listenAddr)
	if err != nil {
		log.Fatalf("could not start to listen: %s", err)
	}
	if listenType == "unix" {
		mode, err := strconv.ParseUint(*socketMode, 8, 32)
		if err != nil {
			log.Fatalf("could not parse mode: %s", err)
		}
		log.Printf("what we parsed: %s", fs.FileMode(mode))
		os.Chmod(listenAddr, fs.FileMode(mode))
	}

	forwarder := &cgi.Handler{
		Path: *path,
		Root: *prefix,
		Env:  strings.Split(*env, ","),
		Dir:  *dir,
	}
	http.Handle("/", forwarder)
	log.Printf("server stopped working: %s", http.Serve(l, nil))
}