“函数主体外的非声明语句”错误golang [关闭]

I keep getting an non-declaration statement outside function body error for my http func method. I'm not sure why it keeps coming up after I fixed some global variables.

    package main

import (
  "net/http"
  "github.com/gorilla/websocket"
)

var audioMessage   []byte
var whatType       int
var recieverReady  bool

http.HandleFunc("/send", func(w http.ResponseWriter, r *http.Request) {
  conn, _ := websocket.Upgrade(r, w)

  go func(){
        for {

      messageType, revdata, err := conn.ReadMessage()

      if recieverReady {
        audioMessage <- revdata
        whatType     <- messageType
      }
    }
    }()
})

put your http.HandleFunc inside a func main() {}

http.HandleFunc() is a method within http. You can't just drop it outside a function. it's like writing a strings.Compare(a,b) outside a function.

It is not a function declaration in itself.

The correct way to do this is include this in a main method (or another method). For clarity, you could move the anonymous function (that func(w http.ResponseWriter, r *http.Request) you have there) to a named function.

Example:

func send (w http.ResponseWriter, r *http.Request) {
  conn, _ := websocket.Upgrade(r, w)
  go func(){
    for {
      messageType, revdata, err := conn.ReadMessage()

      if recieverReady {
        audioMessage <- revdata
        whatType     <- messageType
      }
    }
  }()
}

func main () {
  http.HandleFunc("/send", send)
}

Don't ignore the error though.