forked from mattn/go-cgiserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcgiserver.go
70 lines (64 loc) · 1.31 KB
/
cgiserver.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
package cgiserver
import (
"net/http"
"net/http/cgi"
"os"
"path/filepath"
)
type CgiHandler struct {
http.Handler
Root string
DefaultApp string
UseLangMap bool
LangMap map[string]string
}
func CgiServer() *CgiHandler {
path, _ := filepath.Abs(".")
return &CgiHandler{nil, path, "", true, map[string]string{}}
}
func (h *CgiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
var isCGI bool
file := filepath.FromSlash(path)
if len(file) > 0 && os.IsPathSeparator(file[len(file)-1]) {
file = file[:len(file)-1]
}
ext := filepath.Ext(file)
bin, isCGI := h.LangMap[ext]
file = filepath.Join(h.Root, file)
f, e := os.Stat(file)
if e != nil || f.IsDir() {
if len(h.DefaultApp) > 0 {
file = h.DefaultApp
}
ext := filepath.Ext(file)
bin, isCGI = h.LangMap[ext]
}
if isCGI {
var cgih cgi.Handler
if h.UseLangMap {
cgih = cgi.Handler{
Path: bin,
Dir: h.Root,
Root: h.Root,
Args: []string{file},
Env: []string{"SCRIPT_FILENAME=" + file},
}
} else {
cgih = cgi.Handler{
Path: file,
Root: h.Root,
}
}
cgih.ServeHTTP(w, r)
} else {
if (f != nil && f.IsDir()) || file == "" {
tmp := filepath.Join(file, "index.html")
f, e = os.Stat(tmp)
if e == nil {
file = tmp
}
}
http.ServeFile(w, r, file)
}
}