Last active
November 25, 2019 06:08
-
-
Save ismiyati/fa6ebfb4726783eb5c496e99fe9ce368 to your computer and use it in GitHub Desktop.
#golang . latihan server sent event
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "net/http" | |
| "time" | |
| ) | |
| func html(w http.ResponseWriter, r *http.Request) { | |
| w.Header().Add("Content-Type", "text/html") | |
| w.Write([]byte(` | |
| <a href="/startStop" target="none">start / stop</a><br> | |
| <a href="/reset" target="none">reset</a> | |
| <iframe name="none" style="display:none"></iframe> | |
| <div id="data" ></div> | |
| <script> | |
| var SSE = new EventSource("http://localhost:8080/SSE") | |
| SSE.onmessage = function(evt){ | |
| data.innerHTML = evt.data | |
| } | |
| </script> | |
| `)) | |
| } | |
| var inc = 0 | |
| func SSE(w http.ResponseWriter, r *http.Request) { | |
| w.Header().Set("Connection", "keep-alive") | |
| w.Header().Set("Content-Type", "text/event-stream") | |
| for range time.Tick(time.Second) { | |
| fmt.Fprintf(w, "data: %d\n\n", inc) | |
| w.(http.Flusher).Flush() | |
| } | |
| } | |
| var strtStpChn = make(chan struct{}) | |
| func startStop(w http.ResponseWriter, r *http.Request) { | |
| strtStpChn <- struct{}{} | |
| } | |
| var rstChn = make(chan struct{}) | |
| func reset(w http.ResponseWriter, r *http.Request) { | |
| rstChn <- struct{}{} | |
| } | |
| func main() { | |
| go func() { | |
| ok := false | |
| for { | |
| select { | |
| case <-time.Tick(time.Second): | |
| if ok { | |
| inc++ | |
| } | |
| case <-strtStpChn: | |
| ok = !ok | |
| case <-rstChn: | |
| inc = 0 | |
| } | |
| } | |
| }() | |
| http.HandleFunc("/", html) | |
| http.HandleFunc("/SSE", SSE) | |
| http.HandleFunc("/startStop", startStop) | |
| http.HandleFunc("/reset", reset) | |
| http.ListenAndServe(":8080", nil) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
