Use W3C Fetch API instead of hacky JS

This commit is contained in:
nemunaire 2018-10-17 16:27:37 +02:00
parent fccd3e9a3c
commit 52686d369c
1 changed files with 10 additions and 35 deletions

45
main.go
View File

@ -79,7 +79,15 @@ function disp(rendus) {
<tbody id="students">
</tbody>
</table>
<script src="rendus.json?func=disp"></script>
<script type="text/javascript">
fetch('rendus.json') // You can also fetch login_x.json
.then(function(response) {
return response.json();
})
.then(function(submissions) {
disp(submissions);
});
</script>
</body>
</html>
`))
@ -99,35 +107,13 @@ func genStudents() map[string]map[string]*Submission {
func ServeJSON(w http.ResponseWriter, r *http.Request) {
log.Printf("Handling %s request from %s: %s [%s]\n", r.Method, r.RemoteAddr, r.URL.Path, r.UserAgent())
q := r.URL.Query()
varname := q.Get("var")
funcname := q.Get("func")
if funcname == "" && varname == "" {
w.Header().Set("Content-Type", "application/json")
} else {
w.Header().Set("Content-Type", "application/javascript")
}
w.Header().Set("Content-Type", "application/json")
if j, err := json.Marshal(genStudents()); err != nil {
http.Error(w, fmt.Sprintf("{errmsg:%q}", err), http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
if varname != "" {
w.Write([]byte("var "))
w.Write([]byte(varname))
w.Write([]byte(" = "))
}
if funcname != "" {
w.Write([]byte(funcname))
w.Write([]byte("("))
}
w.Write(j)
if funcname != "" {
w.Write([]byte(")"))
} else if varname != "" {
w.Write([]byte(";"))
}
}
}
@ -166,22 +152,11 @@ func ServeJSONStudent(w http.ResponseWriter, r *http.Request) {
login := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/"), ".json")
q := r.URL.Query()
varname := q.Get("var")
if j, err := json.Marshal(genStudent(login)); err != nil {
http.Error(w, fmt.Sprintf("{errmsg:%q}", err), http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
if varname != "" {
w.Write([]byte("var "))
w.Write([]byte(varname))
w.Write([]byte(" = "))
}
w.Write(j)
if varname != "" {
w.Write([]byte(";"))
}
}
}