运行go-libp2p-http示例时出现的错误。

huangapple go评论74阅读模式
英文:

Bugs when running the example of go-libp2p-http

问题

问题出在go func中。错误信息是go中的表达式必须是函数调用

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)
}

错误信息为

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

英文:

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

答案1

得分: 0

你忘记调用(调用)匿名函数了。因此,出现错误:go中的表达式必须是函数调用

go func() { fmt.Prinln("我是一个IIFE") }()  // 注意括号

这被称为立即调用的函数表达式(IIFE)。

英文:

You forget to invoke (call) the anonymous function. Hence, the error: expression in go must be function call.

go func() { fmt.Prinln("Im an IIFE") }()  // note the parenthesis

This is called immediate invoked function expression (IIFE).

答案2

得分: 0

如果你决定创建一个匿名函数,那么可以使用以下代码:

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)
}()

如果你想使用命名函数,可以使用以下代码:

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)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2022年1月24日 20:44:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/70834064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定