I have a golang connection. If the client opened the connection the database change the online column to 1. Here is my code but I didnt implement the last thing. My question, how can I change the database column to 0 if the client closed the connection. How can I track the client, and catch the connection close?
package main
import (
"golang.org/x/net/websocket"
"fmt"
"log"
"net/http"
"strconv"
)
type Clients struct {
webs *websocket.Conn
clientAddr string
id int
}
var (
ActiveClients = make(map[Clients]int)
)
func Echo(ws *websocket.Conn){
var err error
client := ws.Request().RemoteAddr
sockCli := Clients{webs: ws, clientAddr: client, id: 0}
ActiveClients[sockCli] = 1
for{
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil{
fmt.Println("Cant receive", err)
break
}else{
if sockCli.id == 0{
sockCli.id, err = strconv.Atoi(reply)
}
}
if err = websocket.Message.Send(ws, "id:"+strconv.Itoa(sockCli.id)); err != nil{
fmt.Println("Cant send")
}
for cs, _ := range ActiveClients {
if cs.id == 1{
if err = websocket.Message.Send(cs.webs, "asd"); err != nil {
// we could not send the message to a peer
log.Println("Could not send message to ", cs.clientAddr, err.Error())
}
}else {
fmt.Println("No")
}
}
}
}
func main(){
http.Handle("/", websocket.Handler(Echo))
if err := http.ListenAndServe(":1234", nil); err != nil{
log.Fatal("ListenAndServe: ", err)
}
}