-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
148 lines (107 loc) · 2.48 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
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"path/filepath"
"github.com/spf13/viper"
"github.com/yookoala/gofast"
)
var (
revProxURL string
listenHostPort string
sockAddress string
phpFsPath string
revProxHost string
hostProxy = make(map[string]*httputil.ReverseProxy)
staticFileExt = make(map[string]int)
)
type baseHandle struct{}
func phpFast() {
connFactory := gofast.SimpleConnFactory("unix", sockAddress)
gs := gofast.NewHandler(
gofast.NewPHPFS(phpFsPath)(gofast.BasicSession),
gofast.SimpleClientFactory(connFactory),
)
// route all requests to relevant PHP file
http.Handle("/", gs)
err := http.ListenAndServe(revProxHost, nil)
if err != nil {
panic(err)
}
}
func headerToJson(header http.Header) {
jsonHeader, err := json.Marshal(header)
if err != nil {
fmt.Println(err)
}
log.Println(string(jsonHeader))
}
func startRevProx() {
revMux := http.NewServeMux()
h := &baseHandle{}
revMux.Handle("/", h)
server := &http.Server{
Addr: listenHostPort,
Handler: h,
}
log.Printf("Starting server listening on %s", listenHostPort)
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}
func (h *baseHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Server", "WP GoFast")
rip := r.Header.Get("X-Forwarded-For")
if rip == "" {
var err error
rip, _, err = net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Println(err)
}
}
fpExt := filepath.Ext(r.URL.Path)
r.Header.Add("URL", r.URL.String())
headerToJson(r.Header)
if fpExt != ".php" && fpExt != "" {
// serve a static file here
http.ServeFile(w, r, phpFsPath+"/"+r.URL.Path)
} else {
// pass to goFast
remoteURL, err := url.Parse(revProxURL)
if err != nil {
log.Println(err)
}
proxy := httputil.NewSingleHostReverseProxy(remoteURL)
proxy.ServeHTTP(w, r)
}
}
func loadConfig() {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
revProxURL = viper.GetString("revProxURL")
listenHostPort = viper.GetString("listenHostPort")
sockAddress = viper.GetString("sockAddress")
phpFsPath = viper.GetString("phpFsPath")
// parse the host from the revProxURL
u, err := url.Parse(revProxURL)
if err != nil {
log.Fatal(err)
}
revProxHost = u.Host
}
func main() {
loadConfig()
go phpFast()
startRevProx()
}