forked from fastai/http2fcgi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
163 lines (141 loc) · 3.96 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package main
import (
"errors"
"flag"
"fmt"
"github.com/alash3al/go-fastcgi-client"
"io"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
)
var (
FlagHTTPAddr = flag.String("http", ":6065", "the http address to listen on")
FlagFCGIBackend = flag.String("fcgi", "fcgi.sock", "fcgi backend to connect to")
FlagReadTimeout = flag.Int("rtimeout", 0, "the read timeout, zero means unlimited")
FlagWriteTimeout = flag.Int("wtimeout", 0, "the write timeout, zero means unlimited")
)
var (
FCGIBackendConfig *BackendConfig
)
type BackendConfig struct {
Network string
Address string
Params map[string]string
}
func main() {
flag.Parse()
fmt.Println("⇨ checking the fcgi backend ...")
cnf, err := GetBackendConfig(*FlagFCGIBackend)
if err != nil {
log.Fatal(err)
}
FCGIBackendConfig = cnf
fmt.Printf("⇨ http server started on %s\n", *FlagHTTPAddr)
log.Fatal(http.ListenAndServe(*FlagHTTPAddr, http.HandlerFunc(Serve)))
}
func Serve(res http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
defer func() {
if err := recover(); err != nil {
res.WriteHeader(500)
res.Write([]byte("ForwarderError, please see the logs"))
log.Println(err)
}
}()
fullfilename := req.URL.Path
host, port, _ := net.SplitHostPort(req.RemoteAddr)
params := map[string]string{
"SERVER_SOFTWARE": "http2fcgi",
"SERVER_PROTOCOL": req.Proto,
"REQUEST_METHOD": req.Method,
"REQUEST_TIME": fmt.Sprintf("%d", time.Now().Unix()),
"REQUEST_TIME_FLOAT": fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Microsecond)),
"QUERY_STRING": req.URL.RawQuery,
"DOCUMENT_ROOT": fullfilename,
"REMOTE_ADDR": host,
"REMOTE_PORT": port,
"SCRIPT_FILENAME": fullfilename,
"PATH_TRANSLATED": fullfilename,
"SCRIPT_NAME": req.URL.Path,
"REQUEST_URI": req.URL.RequestURI(),
"AUTH_DIGEST": req.Header.Get("Authorization"),
"PATH_INFO": req.URL.Path,
"ORIG_PATH_INFO": req.URL.Path,
"HTTP_HOST": req.Host,
}
for k, v := range req.Header {
if len(v) < 1 {
continue
}
k = strings.ToUpper(fmt.Sprintf("HTTP_%s", strings.Replace(k, "-", "_", -1)))
params[k] = strings.Join(v, ";")
}
c, e := fcgiclient.Dial(FCGIBackendConfig.Network, FCGIBackendConfig.Address)
if c == nil {
res.WriteHeader(500)
res.Write([]byte(e.Error()))
return
}
defer c.Close()
c.SetReadTimeout(time.Duration(*FlagReadTimeout) * time.Second)
c.SetSendTimeout(time.Duration(*FlagWriteTimeout) * time.Second)
resp, err := c.Request(params, req.Body)
if resp == nil || resp.Body == nil || err != nil {
res.WriteHeader(500)
res.Write([]byte(err.Error()))
return
}
defer resp.Body.Close()
for k, vals := range resp.Header {
for _, v := range vals {
res.Header().Add(k, v)
}
}
res.Header().Set("Server", "http2fcgi")
if resp.ContentLength > 0 {
res.Header().Set("Content-Length", fmt.Sprintf("%d", resp.ContentLength))
}
res.WriteHeader(resp.StatusCode)
n, _ := io.Copy(res, resp.Body)
if n < 1 {
stderr := c.Stderr()
stderr.WriteTo(res)
}
}
// GetBackendConfig returns the configs of the fcgi backend
func GetBackendConfig(backend string) (cnf *BackendConfig, err error) {
var u *url.URL
u, err = url.Parse(backend)
if err != nil {
return nil, err
}
cnf = &BackendConfig{}
cnf.Params = map[string]string{}
u.Scheme = strings.ToLower(u.Scheme)
if u.Scheme == "" && u.Host == "" && u.Path != "" {
cnf.Network, cnf.Address = "unix", u.Path
}
if u.Scheme == "" && u.Host != "" && u.Path == "" {
cnf.Network, cnf.Address = "tcp", u.Host
}
if u.Scheme == "unix" && u.Path != "" {
cnf.Network, cnf.Address = "unix", u.Path
}
if u.Scheme == "tcp" && u.Host != "" {
cnf.Network, cnf.Address = "tcp", u.Host
}
for k, v := range u.Query() {
if len(v) < 1 {
v = []string{""}
}
cnf.Params[k] = v[0]
}
if cnf.Network == "" || cnf.Address == "" {
return nil, errors.New("Invalid fastcgi address (" + backend + ") specified `malformed`")
}
return cnf, nil
}