diff --git a/go.mod b/go.mod index 9ab4b84..e6d1d73 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module example/hello go 1.24.11 + +require github.com/gorilla/websocket v1.5.3 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..25a9fc4 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= diff --git a/main.go b/main.go index a3dd973..0d571b9 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,71 @@ package main -import "fmt" +import ( + "fmt" + "log" + "net/http" + + "github.com/gorilla/websocket" +) + +// HTTP endpoint example +func homePage(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "Home Page") +} + +// We'll need to define an Upgrader +// this will require a Read and Write buffer size +var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, +} + +// define a reader which will listen for +// new messages being sent to our WebSocket +// endpoint +func reader(conn *websocket.Conn) { + for { + // read in a message + messageType, p, err := conn.ReadMessage() + if err != nil { + log.Println(err) + return + } + // print out that message for clarity + fmt.Println(string(p)) + + if err := conn.WriteMessage(messageType, p); err != nil { + log.Println(err) + return + } + + } +} + +func wsEndpoint(w http.ResponseWriter, r *http.Request) { + upgrader.CheckOrigin = func(r *http.Request) bool { return true } + + // upgrade this connection to a WebSocket + // connection + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + log.Println(err) + } + + // helpful log statement to show connections + log.Println("Client Connected") + err = ws.WriteMessage(1, []byte("Connected")) + + reader(ws) +} + +func setupRoutes() { + http.HandleFunc("/", homePage) + http.HandleFunc("/ws", wsEndpoint) +} func main() { - fmt.Println("Hello, World!") + fmt.Println("Starting up") + setupRoutes() + log.Fatal(http.ListenAndServe(":8080", nil)) }