party/cmd/server/main.go

105 lines
2.2 KiB
Go

package main
import (
//"encoding/json"
"html/template"
"net/http"
"fmt"
"time"
"github.com/gorilla/websocket"
)
type Message struct {
Type string `json:"type"`
Timestamp string `json:"timestamp"`
Random float64 `json:"random"`
}
var page_template = template.Must(template.ParseFiles("../../ui/index.html"))
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true }, // allow all origins
}
func handler(w http.ResponseWriter, r *http.Request) {
data := struct {
Name string
}{
Name: "Visitor",
}
page_template.Execute(w, data)
}
func ws_handler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("Upgrade error:", err)
return
}
defer conn.Close()
done := make(chan struct{})
go func() {
ticker := time.NewTicker(1 * time.Second);
for {
select {
case <-done:
return
case t := <-ticker.C:
msg := map[string]interface{}{
"type": "server_tick",
"timestamp": t.Format(time.RFC3339),
}
if err := conn.WriteJSON(msg); err != nil {
fmt.Println("Write error:", err)
return
}
}
}
}()
for {
var msg Message
err := conn.ReadJSON(&msg)
if err != nil {
fmt.Println("Read error:", err)
break
}
fmt.Println(msg)
// Send a response
// response := fmt.Sprintf("Server time: %s", time.Now())
// if err := conn.WriteMessage(websocket.TextMessage, []byte(response)); err != nil {
// fmt.Println("Write error:", err)
// break
// }
}
}
func redirect_to_HTTPS(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://localhost:8443" + r.URL.RequestURI(), http.StatusMovedPermanently)
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/ws", ws_handler)
go func() {
err := http.ListenAndServe(":8080", http.HandlerFunc(redirect_to_HTTPS))
if err != nil {
panic(err)
}
}()
// Start HTTPS server (requires cert.pem and key.pem in current dir)
err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
if err != nil {
panic(err)
}
}