-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.go
More file actions
76 lines (63 loc) · 2.03 KB
/
Copy pathhandlers.go
File metadata and controls
76 lines (63 loc) · 2.03 KB
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
package gophernaut
import (
"html/template"
"net/http"
"net/http/httputil"
"net/url"
"path"
"strings"
)
// AdminContext ... Simple struct for storing input to our admin template
type AdminContext struct {
Pool Pool
Config *Config
}
// GetGopherHandler ...
func GetGopherHandler(pool Pool, config *Config) func(w http.ResponseWriter, r *http.Request) {
var requestCount = 0
staticHandler := http.StripPrefix("/static", http.FileServer(http.Dir("static")))
adminTemplate := template.Must(template.ParseFiles("templates/admin.html"))
adminHandler := func(w http.ResponseWriter, req *http.Request) {
context := AdminContext{Pool: pool, Config: config}
adminTemplate.Execute(w, context)
}
myHandler := func(responseWriter http.ResponseWriter, myReq *http.Request) {
requestPath := myReq.URL.Path
// DONE: adjust request host to assign the request to the appropriate child process
// TODO: multiprocess, pick one of n hostnames based on pool status
worker := pool.GetWorker()
hostname := worker.Hostname
requestCount++
targetURL, _ := url.Parse(hostname)
director := func(req *http.Request) {
targetQuery := targetURL.RawQuery
req.URL.Scheme = targetURL.Scheme
req.URL.Host = targetURL.Host
// clean up but preserve trailing slash:
trailing := strings.HasSuffix(req.URL.Path, "/")
req.URL.Path = path.Join(targetURL.Path, req.URL.Path)
if trailing && !strings.HasSuffix(req.URL.Path, "/") {
req.URL.Path += "/"
}
// preserve query string:
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
}
proxy := &httputil.ReverseProxy{Director: director}
worker.StartRequest()
defer worker.CompleteRequest()
switch {
case requestPath == "/admin":
adminHandler(responseWriter, myReq)
return
case strings.HasPrefix(requestPath, "/static"):
staticHandler.ServeHTTP(responseWriter, myReq)
return
}
proxy.ServeHTTP(responseWriter, myReq)
}
return myHandler
}