golibp2pgo-libp2p

Bugs when running the example of go-libp2p-http


The problem lies in go func. The error message is expression in go must be function call

 listener, _ := gostream.Listen(host1, p2phttp.DefaultP2PProtocol)
    defer listener.Close()
    go func() {
        http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
            w.Write([]byte("Hi!"))
        })
        server := &http.Server{}
        server.Serve(listener)
    }

The error is

command-line-arguments
.\sever.go:18:5: expression in go must be function call


Solution

  • If you decide to make an anonymous function, then

    listener, _ := gostream.Listen(host1, p2phttp.DefaultP2PProtocol)
    defer listener.Close()
    go func() {
        http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
            w.Write([]byte("Hi!"))
        })
        server := &http.Server{}
        server.Serve(listener)
    }()
    

    Named function:

    listener, _ := gostream.Listen(host1, p2phttp.DefaultP2PProtocol)
    defer listener.Close()
    go Greet()
    
    func Greet() {
        http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
            w.Write([]byte("Hi!"))
        })
        server := &http.Server{}
        server.Serve(listener)
    }