我对golang完全不熟悉。但我从nodejs
获得了一些知识现在我想学习Go,在这里你可以看到一个应该启动网络服务器的应用程序,然后它应该打开你好的控制台。
但似乎在行之后
http.ListenAndServe(":"+serverportString, nil)
它完全停止了。在节点js中,它将同时运行。我在这里有误会吗?
下面的下一行是
sayhello()
应该启动函数向控制台问好。但它之前就停止了。
在这里您可以看到完整的代码
// it should start a web server at port 8080
// and it should print hello to the console
package main
import (
"fmt"
"net/http"
"strconv"
)
var serverport int = 8080
func main(){
serverportString := strconv.Itoa(serverport)
http.HandleFunc("/", handler)
http.ListenAndServe(":"+serverportString, nil)
sayhello()
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func sayhello () {
// now print hello to the console
fmt.Println("hello")
答案 0 :(得分:1)
问题在于http.ListenAndServe(":"+serverportString, nil)
行。
ListenAndServe是阻止通话,通常留作main
的最后一个声明。
您可以使用go http.ListenAndServe(...)
在goroutine中启动它,然后调用sayhello()
函数,但随后整个程序将到达main的末尾,所有goroutine将被终止。