-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
67 lines (58 loc) · 1.5 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"fmt"
"log"
"math"
"net/http"
"os"
"strconv"
"text/template"
"gopkg.in/igm/sockjs-go.v2/sockjs"
"github.com/joho/godotenv"
"golang.org/x/net/websocket"
)
// SquareMultiplierHandler will square the data received on the WebSocket.
func SquareMultiplierHandler(ws *websocket.Conn) {
for {
var message string
websocket.Message.Receive(ws, &message)
f, _ := strconv.ParseFloat(message, 64)
fmt.Fprintln(ws, math.Pow(f, 2))
}
}
func serveTemplate(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
data := struct {
Title string
}{
"WSConnection Test",
}
t, _ := template.ParseFiles("tmpl/index.html")
t.Execute(w, data)
}
func squareHandler(session sockjs.Session) {
log.Println("new sockjs session established")
for {
if msg, err := session.Recv(); err == nil {
f, _ := strconv.ParseFloat(msg, 64)
session.Send(fmt.Sprintln(math.Pow(f, 2)))
continue
}
break
}
log.Println("sockjs session closed")
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
http.Handle("/square", websocket.Handler(SquareMultiplierHandler))
http.Handle("/sock/", sockjs.NewHandler("/sock", sockjs.DefaultOptions, squareHandler))
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/", serveTemplate)
fail := http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("PORT")), nil)
if fail != nil {
log.Fatal("ListenAndServe: " + fail.Error())
}
}