-
Notifications
You must be signed in to change notification settings - Fork 0
/
autof5.go
68 lines (59 loc) · 1.21 KB
/
autof5.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
package autof5
import (
"fmt"
"net/http"
"strings"
)
const js = `
<script>
let _wait = () => fetch("/_autoF5_wait", { mode: 'no-cors' }).catch(function(err) {
let refresh = () => {
fetch("/_autoF5").then(() => {
location.reload();
_wait();
}).catch(() => {
setTimeout(() => {
refresh();
}, 500);
});
};
refresh();
});
_wait();
</script>
`
type responseRecorder struct {
w http.ResponseWriter
status int
body string
}
func (r *responseRecorder) Header() http.Header {
return r.w.Header()
}
func (r *responseRecorder) Write(b []byte) (int, error) {
r.body += string(b)
return len(b), nil
}
func (r *responseRecorder) WriteHeader(status int) {
r.status = status
r.w.WriteHeader(status)
}
func (r *responseRecorder) Flush() {
_, _ = r.w.Write([]byte(r.body))
}
func AutoF5(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/_autoF5_wait" {
<-r.Context().Done()
return
}
if r.URL.Path == "/_autoF5" {
fmt.Fprintf(w, "ok")
return
}
rec := &responseRecorder{w: w}
next.ServeHTTP(rec, r)
rec.body = strings.Replace(rec.body, "</body>", js+"</body>", 1)
rec.Flush()
})
}