Initial commit, just the basic webui layout and basic golang backend with websocket communication tested.
This commit is contained in:
72
main.go
Normal file
72
main.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/gorilla/websocket"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
httpAddr = flag.String("addr", ":8000", "Http server address")
|
||||
baseTmpl string = "templates/base.tmpl"
|
||||
|
||||
APP_ID = os.Getenv("APP_ID")
|
||||
APP_SECRET = os.Getenv("APP_SECRET")
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
}
|
||||
|
||||
func serveHome(w http.ResponseWriter, r *http.Request) {
|
||||
s1, _ := template.ParseFiles("templates/home.tmpl")
|
||||
s1.ExecuteTemplate(w, "base", map[string]string{"APP_ID": APP_ID})
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
r := mux.NewRouter()
|
||||
|
||||
r.HandleFunc("/", serveHome)
|
||||
http.Handle("/static/", http.FileServer(http.Dir("public")))
|
||||
http.Handle("/", r)
|
||||
http.HandleFunc("/websocket", func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
for {
|
||||
msgType, msg, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
if string(msg) == "ping" {
|
||||
fmt.Println("ping")
|
||||
time.Sleep(2 * time.Second)
|
||||
err = conn.WriteMessage(msgType, []byte("pong"))
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
conn.Close()
|
||||
fmt.Println(string(msg))
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
if err := http.ListenAndServe(*httpAddr, nil); err != nil {
|
||||
log.Fatalf("Error listening, %v", err)
|
||||
}
|
||||
|
||||
//
|
||||
}
|
Reference in New Issue
Block a user