[Go言語] JSとGoでchatを作りたい その3

usernameをserver側に送る

script.js

	let userInput = document.getElementById("username")
	userInput.addEventListener("change", function(){
		let jsonData = {}
		jsonData["action"] = "username"
		jsonData["username"] = this.value;

		socket.send(JSON.stringify(jsonData))
	})

handlers.go

func getUserList() []string {
	var clientList []string
	for _, client := range clients {
		if client != "" {
			clientList = append(clientList, client)
		}
	}
	sort.Strings(clientList)
	return clientList
}

connect.go

type WsJsonResponse struct {
	Action string `json:"action"`
	Message string `json:"message"`
	ConnectedUsers []string `json:"connected_users"`
}

script.js

	socket.onmessage = msg => {
		let data = JSON.parse(msg.data)
		console.log({data})
		console.log("Action is", data.action)
		switch(data.action){
			case "list_users":
				let ul = document.getElementById("online-users")
				while (ul.firstChild) ul.removeChild(ul.firstChild)

				if (data.connected_users.length > 0){
					data.connected_users.forEach(function(item){
						let li = document.createElement("li")
						li.appendChild(document.createTextNode(item))
						ul.appendChild(li)
					})
				}
				break
		}
	}

script.js

window.onbeforeunload = function(){
	console.log("User Leaving")
	let jsonData = {}
	jsonData["action"] = "left"
	socket.send(JSON.stringify(jsonData))
}
func ListenToWsChannel(){
	var response domain.WsJsonResponse

	for {
		e := <-wsChan

		switch e.Action {
		case "username":
			clients[e.Conn] = e.Username
			users := getUserList()
			response.Action = "list_users"
			response.ConnectedUsers = users
			broadcastToAll(response)

		case "left":
			response.Action = "list_users"
			delete(clients, e.Conn)
			users := getUserList()
			response.ConnectedUsers = users
			broadcastToAll(response)
		}
	}
}

ちょっとこんがらがってきました。