如何使Websocket客户端等待服务器运行?

I want to create a websocket client that waits until the server is running. If the connection is closed by the server it should reconnect.

What I tried does not work and my code exits with a runtime error:

panic: runtime error: invalid memory address or nil pointer dereference

func run() {
  origin := "http://localhost:8080/"
  url := "ws://localhost:8080/ws"

  ws, err := websocket.Dial(url, "", origin)

  if err != nil {
      fmt.Println("Connection fails, is being re-connection")
      main()
  }

  if _, err := ws.Write([]byte("something")); err != nil {
    log.Fatal(err)
  }
}

Your example looks like a code snippet. It's difficult to say why you're getting that error without seeing all the code. As were pointed out in the comments to your post, you can't call main() again from your code and including the line numbers from the panic report would be helpful as well.

Usually minimizing your program to a minimal case that anyone can run and reproduce the error is the fastest way to get help. I've reconstructed yours for you in such fashion. Hopefully you can use it to fix your own code.

package main

import (
    "websocket"
    "fmt"
    "log"
    "time"
    )

func main() {
    origin := "http://localhost:8080/"
    url := "ws://localhost:8080/ws"

    var err error
    var ws *websocket.Conn
    for {
        ws, err = websocket.Dial(url, "", origin)
        if err != nil {
            fmt.Println("Connection fails, is being re-connection")
            time.Sleep(1*time.Second)
            continue
        }
        break
    }
    if _, err := ws.Write([]byte("something")); err != nil {
        log.Fatal(err)
    }

}

To run this, just copy it into a file called main.go on your system and then run:

go run main.go