-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_http_web_cgi.go
96 lines (81 loc) · 1.92 KB
/
handler_http_web_cgi.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 (
"errors"
"net/http"
"net/http/cgi"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/phuslu/log"
)
type HTTPWebCgiHandler struct {
Location string
Root string
DefaultApp string
phpcgi string
}
func (h *HTTPWebCgiHandler) Load() (err error) {
root := h.Root
if root == "" {
return errors.New("empty cgi root")
}
if strings.HasSuffix(h.Location, ".php") {
h.phpcgi, err = exec.LookPath("php-cgi")
if err != nil {
return err
}
}
return
}
func (h *HTTPWebCgiHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
ri := req.Context().Value(RequestInfoContextKey).(*RequestInfo)
var fullname string
if strings.TrimRight(req.URL.Path, "/") == strings.TrimRight(h.Location, "/") && h.DefaultApp != "" {
fullname = h.DefaultApp
if !strings.HasPrefix(fullname, "/") {
fullname = filepath.Join(h.Root, fullname)
}
}
if fullname == "" {
fullname = filepath.Join(h.Root, strings.TrimPrefix(req.URL.Path, h.Location))
}
log.Info().Context(ri.LogContext).Str("fullname", fullname).Msg("web cgi request")
if strings.HasSuffix(fullname, ".php") && h.phpcgi != "" {
/*
/etc/php/8.1/cgi/conf.d/99-enable-headers.ini
cgi.rfc2616_headers = 1
cgi.force_redirect = 0
force_cgi_redirect = 0
*/
(&cgi.Handler{
Path: h.phpcgi,
Dir: h.Root,
Root: h.Root,
Args: []string{fullname},
Env: []string{"SCRIPT_FILENAME=" + fullname},
}).ServeHTTP(rw, req)
return
}
if strings.HasSuffix(fullname, ".cgi") {
(&cgi.Handler{
Path: fullname,
Root: h.Root,
Env: []string{"SCRIPT_FILENAME=" + fullname},
}).ServeHTTP(rw, req)
return
}
fi, err := os.Stat(fullname)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if fi != nil && fi.IsDir() {
index := filepath.Join(fullname, "index.html")
fi, err = os.Stat(index)
if err == nil {
fullname = index
}
}
http.ServeFile(rw, req, fullname)
}