diff --git a/main.go b/main.go index df5efd4..e18aeb8 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "net/http" "time" @@ -24,8 +25,21 @@ func main() { log.Infof("User: %+v", user) mux := gorilla.NewRouter() + mux.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static")))) mux.HandleFunc("/login", handleTwitchLogin) mux.HandleFunc("/callback", handleTwitchCallback) + mux.HandleFunc("/data", func(w http.ResponseWriter, r *http.Request) { + if user == nil { + http.NotFound(w, r) + return + } + w.Header().Set("Access-Control-Allow-Headers", "*") + if err := json.NewEncoder(w).Encode(user.getWebUser()); err != nil { + log.WithError(err).Error("Unable to encode user data") + http.Error(w, "Unable to encode user data", http.StatusInternalServerError) + return + } + }) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hi!")) }) diff --git a/static/collector.js b/static/collector.js new file mode 100755 index 0000000..184ae69 --- /dev/null +++ b/static/collector.js @@ -0,0 +1,46 @@ +var twitchCollector = { + updateHooks: [], + data: null, + + + update: function(data) { + this.data = data; + var that = this; + this.updateHooks.forEach(function(v) { + v(that.data); + }); + }, + + registerHook: function(kind, callback) { + switch (kind) { + case "update": + this.updateHooks.push(callback); + break; + } + }, + + start: function() { + this.getData(); + var that = this; + window.setInterval(function() { + that.getData() + }, 20000); + }, + + getData: function() { + let xmlhttp = new XMLHttpRequest(); + let url = "/data"; + var that = this; + + xmlhttp.onreadystatechange = function() { + if (this.readyState == 4 && this.status == 200) { + let data = JSON.parse(this.responseText); + if (data !== null) { + that.update(data); + } + } + }; + xmlhttp.open("GET", url, true); + xmlhttp.send(); + } +} \ No newline at end of file diff --git a/static/index.html b/static/index.html new file mode 100755 index 0000000..732dcfb --- /dev/null +++ b/static/index.html @@ -0,0 +1,16 @@ + + +
+