add https only forwarding

master
bel 2022-07-09 15:49:14 -06:00
parent c8e09a989d
commit fc7451ab40
2 changed files with 17 additions and 4 deletions

BIN
exec-simpleserve Executable file

Binary file not shown.

21
main.go
View File

@ -33,6 +33,7 @@ func main() {
fs.Append(args.STRING, "p", "port to serve", "8100")
fs.Append(args.BOOL, "md", "whether to render markdown as html", true)
fs.Append(args.BOOL, "ro", "read only mode", false)
fs.Append(args.BOOL, "https", "https only", false)
fs.Append(args.STRING, "md-css", "css to load for md", "/dev/null")
fs.Append(args.STRING, "md-class", "class to wrap md", "phb")
fs.Append(args.STRING, "d", "static path to serve", "./public")
@ -43,6 +44,7 @@ func main() {
d := fs.Get("d").GetString()
md := fs.Get("md").GetBool()
ro := fs.Get("ro").GetBool()
https := fs.Get("https").GetBool()
mdCss := fs.Get("md-css").GetString()
mdClass := fs.Get("md-class").GetString()
if mdCss != "" {
@ -91,15 +93,15 @@ func main() {
}
p := strings.TrimPrefix(fs.Get("p").GetString(), ":")
http.Handle("/", http.HandlerFunc(handler(ro, d, md, mdCss, mdClass)))
http.Handle("/", http.HandlerFunc(handler(https, ro, d, md, mdCss, mdClass)))
log.Printf("Serving %s on HTTP port: %s\n", d, p)
log.Fatal(http.ListenAndServe(":"+p, nil))
}
func handler(ro bool, d string, md bool, mdCss, mdClass string) http.HandlerFunc {
return gzip(endpoints(ro, withDel(ro, withMD(d, md, mdCss, mdClass, fserve(d)))))
func handler(https, ro bool, d string, md bool, mdCss, mdClass string) http.HandlerFunc {
return httpsOnly(https, gzip(endpoints(ro, withDel(ro, withMD(d, md, mdCss, mdClass, fserve(d))))))
}
func writeMeta(w http.ResponseWriter) {
@ -120,6 +122,17 @@ func writeForm(w http.ResponseWriter) {
`, ENDPOINT_UPLOAD)
}
func httpsOnly(https bool, foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if https && r.URL.Scheme != "https" {
r.URL.Scheme = "https"
http.Redirect(w, r, r.URL.String(), http.StatusSeeOther)
return
}
foo(w, r)
}
}
func gzip(foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if gziphttp.Can(r) {
@ -208,7 +221,7 @@ func withDel(ro bool, foo http.HandlerFunc) http.HandlerFunc {
foo(w, r)
return
}
fmt.Fprintln(w, `<a href=".."><input type="button" style="padding: .15em 4em .35em 4em" value=".."/></a>`+"\n")
fmt.Fprintln(w, `<a href=".."><input type="button" style="padding: .15em 4em .35em 4em" value=".."/></a>`)
w2 := httptest.NewRecorder()
foo(w2, r)
b := bytes.Split(w2.Body.Bytes(), []byte("\n"))