/
handlers.go
244 lines (213 loc) · 7.34 KB
/
handlers.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"html/template"
"io"
"net/http"
"os"
"path"
"regexp"
"strings"
)
// Deprecated
func ssiHandler(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "<p>SSI handler (%s).</p>", r.URL.Path[1:])
_, _ = fmt.Fprintf(w, inspectRequestHTML(r))
}
// Get some status info
func statusHandler(w http.ResponseWriter, r *http.Request) {
var msg []string
status := "ok"
w.Header().Set("Content-Type", "application/json; charset=utf-8")
err := updateReleasesStatus()
if err != nil {
msg = append(msg, err.Error())
status = "error"
}
_ = json.NewEncoder(w).Encode(
ApiStatusResponseType{
Status: status,
Msg: strings.Join(msg, " "),
RootVersion: getRootReleaseVersion(),
RootVersionURL: VersionToURL(getRootReleaseVersion()),
Multiwerf: ReleasesStatus.Releases,
})
}
// X-Redirect to the stablest documentation version for specific group
func groupHandler(w http.ResponseWriter, r *http.Request) {
_ = updateReleasesStatus()
log.Debugln("Use handler - groupHandler")
vars := mux.Vars(r)
if err, version := getVersionFromGroup(&ReleasesStatus, vars["group"]); err == nil {
w.Header().Set("X-Accel-Redirect", fmt.Sprintf("/documentation/%v%v", VersionToURL(version), getDocPageURLRelative(r, true)))
} else {
var activeRelease string
if len(os.Getenv("ACTIVE_RELEASE")) > 0 {
activeRelease = os.Getenv("ACTIVE_RELEASE")
} else {
activeRelease = "1.2"
}
http.Redirect(w, r, fmt.Sprintf("/documentation/v%s", activeRelease), 302)
//w.Header().Set("X-Accel-Redirect", fmt.Sprintf("/%v%v", VersionToURL(version), r.URL.RequestURI()))
}
}
// Handles request to /v<group>-<channel>/. E.g. /v1.2-beta/
// Temporarily redirect to specific version
func groupChannelHandler(w http.ResponseWriter, r *http.Request) {
log.Debugln("Use handler - groupChannelHandler")
pageURLRelative := "/"
vars := mux.Vars(r)
_ = updateReleasesStatus()
var version, URLToRedirect string
var err error
re := regexp.MustCompile(`^/documentation/[^/]+(/.+)$`)
res := re.FindStringSubmatch(r.URL.RequestURI())
if res != nil {
pageURLRelative = res[1]
}
err, version = getVersionFromChannelAndGroup(&ReleasesStatus, vars["channel"], vars["group"])
if err == nil {
URLToRedirect = fmt.Sprintf("/documentation/%v%v", VersionToURL(version), pageURLRelative)
err = validateURL(fmt.Sprintf("https://%s%s", r.Host, URLToRedirect))
}
if err != nil {
log.Errorf("Error validating URL: %v, (original was https://%s/%v)", err.Error(), r.Host, r.URL.RequestURI())
//URLToRedirect = fmt.Sprintf("/404.html")
notFoundHandler(w, r)
} else {
http.Redirect(w, r, fmt.Sprintf("%s", URLToRedirect), 302)
//w.Header().Set("X-Accel-Redirect", URLToRedirect)
}
}
// Healthcheck handler
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
// Get HTML content for /includes/topnav.html request
func topnavHandler(w http.ResponseWriter, r *http.Request) {
_ = updateReleasesStatus()
versionMenu := versionMenuType{
VersionItems: []versionMenuItems{},
HTMLContent: "", // not used now
CurrentGroup: "", // not used now
CurrentChannel: "",
CurrentVersion: "",
CurrentVersionURL: "",
CurrentPageURLRelative: "",
MenuDocumentationLink: "",
AbsoluteVersion: "",
}
_ = versionMenu.getVersionMenuData(r, &ReleasesStatus)
tplPath := getRootFilesPath(r) + r.URL.Path
tpl := template.Must(template.ParseFiles(tplPath))
err := tpl.Execute(w, versionMenu)
if err != nil {
// Log error or maybe make some magic?
log.Errorf("Internal Server Error (template error), %v ", err.Error())
http.Error(w, "Internal Server Error (template error)", 500)
}
}
func groupMenuHandler(w http.ResponseWriter, r *http.Request) {
_ = updateReleasesStatus()
versionMenu := versionMenuType{
VersionItems: []versionMenuItems{},
HTMLContent: "", // not used now
CurrentGroup: "", // not used now
CurrentChannel: "",
CurrentVersion: "",
CurrentVersionURL: "",
CurrentPageURLRelative: "",
MenuDocumentationLink: "",
}
_ = versionMenu.getGroupMenuData(r, &ReleasesStatus)
tplPath := getRootFilesPath(r) + r.RequestURI
tpl := template.Must(template.ParseFiles(tplPath))
err := tpl.Execute(w, versionMenu)
if err != nil {
// Log error or maybe make some magic?
log.Errorf("Internal Server Error (template error), %v ", err.Error())
http.Error(w, "Internal Server Error (template error)", 500)
}
}
func channelMenuHandler(w http.ResponseWriter, r *http.Request) {
_ = updateReleasesStatus()
versionMenu := versionMenuType{
VersionItems: []versionMenuItems{},
HTMLContent: "", // not used now
CurrentGroup: "", // not used now
CurrentChannel: "",
CurrentVersion: "",
CurrentVersionURL: "",
CurrentPageURLRelative: "",
MenuDocumentationLink: "",
}
_ = versionMenu.getChannelMenuData(r, &ReleasesStatus)
tplPath := getRootFilesPath(r) + r.RequestURI
tpl := template.Must(template.ParseFiles(tplPath))
err := tpl.Execute(w, versionMenu)
if err != nil {
// Log error or maybe make some magic?
log.Errorf("Internal Server Error (template error), %v ", err.Error())
http.Error(w, "Internal Server Error (template error)", 500)
}
}
func serveFilesHandler(fs http.FileSystem) http.Handler {
fsh := http.FileServer(fs)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
r.URL.Path = upath
}
upath = path.Clean(upath)
if _, err := os.Stat(fmt.Sprintf("%v%s", fs, upath)); err != nil {
if os.IsNotExist(err) {
notFoundHandler(w, r)
return
}
}
fsh.ServeHTTP(w, r)
})
}
func rootDocHandler(w http.ResponseWriter, r *http.Request) {
var redirectTo, activeRelease string
if len(os.Getenv("ACTIVE_RELEASE")) > 0 {
activeRelease = os.Getenv("ACTIVE_RELEASE")
} else {
activeRelease = "1.2"
}
if hasSuffix, _ := regexp.MatchString("^/documentation/.+", r.RequestURI); hasSuffix {
items := strings.Split(r.RequestURI, "/documentation/")
if len(items) > 1 {
redirectTo = strings.Join(items[1:], "/documentation/")
}
}
http.Redirect(w, r, fmt.Sprintf("/documentation/v%s/%s", activeRelease, redirectTo), 301)
}
// Redirect to root documentation if request not matches any location (override 404 response)
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
page404File, err := os.Open(getRootFilesPath(r) + "/404.html")
defer page404File.Close()
if err != nil {
// 404.html file not found!
log.Error("404.html file not found")
http.Error(w, `<html lang="en"><head><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"><title>Page Not Found | werf</title><meta name="title" content="Page Not Found | werf">
</head>
<body>
<h1 class="docs__title">Page Not Found</h1>
<p>Sorry, the page you were looking for does not exist.<br>
Try searching for it or check the URL to see if it looks correct.</p>
<div class="error-image">
<img src="https://werf.io/images/404.png" alt="">
</div>
</body></html>`, 404)
return
}
io.Copy(w, page404File)
//w.Header().Set("X-Accel-Redirect", fmt.Sprintf("/404.html"))
}