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

script.js

//
	document.getElementById("message").addEventListener("keydown", function(event){
		if (event.code === "Enter"){
			if(!socket){
				console.log("no connection")
				return false
			}
			event.preventDefault()
			event.stopPropagation()
			sendMessage()
		}
	})
//
function sendMessage(){
	console.log("Send Message...")
	let jsonData = {}
	jsonData["action"] = "broadcast"
	jsonData["username"] = document.getElementById("username").value
	jsonData["message"] = document.getElementById("message").value
	socket.send(JSON.stringify(jsonData))
	document.getElementById("message").value = ""
}

html

				<button id="submit" class="submit" onclick="sendMessage()">
					<i class="far far-paper-plane"></i>
				</button>

handler.go

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)
		case "broadcast":
			response.Action = "broadcast"
			response.Message = fmt.Sprintf(
				"<li class='replace'><strong>%s</strong>: %s</li>",
				e.Username,
				e.Message)
			broadcastToAll(response)
		}
	}
}

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
			case "broadcast":
				let message = data.message
				let username = document.getElementById("username").value
				if (message.indexOf(username) > 0){
					message = message.replace("replace", "me")
				} else {
					message = message.replace("replace", "other")
				}
				messageList.innerHTML = messageList.innerHTML + message
				break
		}
	}

おおおおおおおおお、これは凄い
あとはrevelでやってfrontを書くか