-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (81 loc) · 1.84 KB
/
main.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"net/http/cgi"
"net/http/fcgi"
"os"
"path/filepath"
)
var useHttp = flag.Bool("http", false, "Use HTTP instead of FCGI")
var port = flag.Int("port", 10101, "Port to bind to for FCGI/HTTP")
var prefix = flag.String("prefix", "/", "Path prefix for the CGI scripts")
var verbose = flag.Bool("v", false, "Verbose mode")
func main() {
flag.Parse()
protocolString := "FCGI"
if *useHttp {
protocolString = "HTTP"
}
cgiPath := flag.Arg(0)
if cgiPath == "" {
log.Fatal("A single argument of the path to the CGI directory is required")
}
cgiPath, err := filepath.Abs(cgiPath)
if err != nil {
log.Fatal(err)
}
log.Printf(
"Starting cgify using %s on port %d serving %s with prefix %s\n",
protocolString,
*port,
cgiPath,
*prefix,
)
sock, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatal(err)
}
handlerFunc := func(w http.ResponseWriter, r *http.Request) {
var path string
path = filepath.Join(cgiPath, r.URL.Path)
var logger *log.Logger = nil
if *verbose {
logger = log.Default()
}
stat, err := os.Stat(path)
if err == nil && stat.IsDir() {
path = filepath.Join(path, "index.html")
stat, err = os.Stat(path)
}
if err != nil {
if logger != nil {
logger.Print(err.Error())
}
if os.IsNotExist(err) {
http.NotFound(w, r);
} else {
http.Error(w, err.Error(), 500)
}
return
}
if stat.Mode()&0111 != 0 {
handler := &cgi.Handler{Path: path, Logger: logger, Root: *prefix}
handler.ServeHTTP(w, r)
} else {
if logger != nil {
log.Printf("Serving static file: %s", path)
}
http.ServeFile(w, r, path)
}
}
handler := http.StripPrefix(*prefix, http.HandlerFunc(handlerFunc))
if *useHttp {
log.Fatal(http.Serve(sock, handler))
} else {
log.Fatal(fcgi.Serve(sock, handler))
}
}