无法在websocket.Message.Send的参数中将ccc(int类型)用作* websocket.Conn类型

I am trying to send a broadcast message to clients using websockets. How to fix this code to send message properly to all clients and without that error?

package main

import (
    "fmt"
    "golang.org/x/net/websocket"
    "net/http"
)

var connections []websocket.Conn

func main() {
    fmt.Println("vim-go")
    http.Handle("/", websocket.Handler(Server))
    err := http.ListenAndServe(":8888", nil)
    if err != nil {
        panic("ListenAndServe: " + err.Error())
    }
}

func Server(ws *websocket.Conn) {
    lll := append(connections, *ws)
    var message string
    websocket.Message.Receive(ws, &message)
    fmt.Println(message)
    for ccc := range connections {
        websocket.Message.Send(ccc, "Another connection!!!")
    }
}

Not sure what you're trying to do with lll but without using it your code should not event compile.


When rangeing over slices/arrays with a single iteration variable on the left of := it will be assigned the index of the iteration. So in your case ccc is the index.

One thing you can do is:

for ccc := range connections {
    websocket.Message.Send(connections[ccc], "Another connection!!!")
}

But what you probably really want is, drop the index and get the element right away which you can do using two iteration variables with the _ as the first one if you don't inted to use the index at all.

for _, ccc := range connections {
    websocket.Message.Send(ccc, "Another connection!!!")
}

read more here: https://golang.org/ref/spec#For_range