Initial Websocket service
This commit is contained in:
parent
6b798480a9
commit
26129be3e5
3 changed files with 70 additions and 2 deletions
2
go.mod
2
go.mod
|
|
@ -1,3 +1,5 @@
|
|||
module example/hello
|
||||
|
||||
go 1.24.11
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3 // indirect
|
||||
|
|
|
|||
2
go.sum
Normal file
2
go.sum
Normal file
|
|
@ -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=
|
||||
68
main.go
68
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))
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue