You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gdg-counter-website/main.go

112 lines
2.4 KiB
Go

package main
import (
"encoding/json"
"log"
"net/http"
"github.com/r3labs/sse/v2"
)
func main() {
mux := http.NewServeMux()
setupRoutes(mux)
server := http.Server{
Addr: ":4000",
Handler: mux,
}
log.Printf("Starting server on port 4000...")
log.Fatal(server.ListenAndServe())
}
func broadcastCounterUpdate(srv *sse.Server, id string, value int) {
bytes, err := json.Marshal(value)
if err != nil {
log.Fatal(err)
}
srv.Publish(id, &sse.Event{Data: bytes})
}
func setupRoutes(mux *http.ServeMux) {
sseServer := sse.New()
sseServer.CreateStream("new-counter-value")
2 years ago
counter := 0
// API Routes
mux.HandleFunc("/api/events", sseServer.ServeHTTP)
mux.HandleFunc("/api/status", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode("ok")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
2 years ago
mux.HandleFunc("/api/value", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(counter)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.HandleFunc("/api/increment", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
counter++
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(counter)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
broadcastCounterUpdate(sseServer, "new-counter-value", counter)
2 years ago
})
mux.HandleFunc("/api/decrement", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
counter--
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(counter)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
broadcastCounterUpdate(sseServer, "new-counter-value", counter)
2 years ago
})
// Static Files
mux.Handle("/", http.FileServer(http.Dir("./dist/")))
}