英文:
I dont understand golang, why does my app not call this function and not behave like nodejs
问题
我完全不了解golang。但是我对nodejs有一些了解。
现在我想学习Go,你可以看到这个应用程序应该启动一个web服务器,然后在控制台上打印hello。
但是在这行代码之后:
http.ListenAndServe(":"+serverportString, nil)
它完全停止了。在node.js中,它会并发运行。我是否有误解?
下面的下一行是
sayhello()
它应该启动一个函数来在控制台上打印hello。但是它停在这之前。
这里是完整的代码:
// 它应该在端口8080上启动一个web服务器
// 并且它应该在控制台上打印hello
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 () {
// 现在在控制台上打印hello
fmt.Println("hello")
英文:
I am completely new to golang. But I have some knowledge from nodejs
now I would like to learn Go, and here you can see an app that should fire up an webserver, and then it should print hello to the console.
but it seems that after the line
http.ListenAndServe(":"+serverportString, nil)
it completely stops. In node js it would run concurrently. Do I have a misunderstanding here?
The next line underneath is
sayhello()
which should start the function to say hello to the console. But it stops right before.
Here you can see the full code
// 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")
答案1
得分: 1
问题出在http.ListenAndServe(":"+serverportString, nil)
这一行。
ListenAndServe是一个阻塞调用,通常作为main
函数的最后一条语句。
你可以使用go http.ListenAndServe(...)
在一个goroutine中启动它,然后sayhello()
函数将被调用,但是整个程序将到达main函数的末尾,所有的goroutine都将被终止。
英文:
The problem is in the line http.ListenAndServe(":"+serverportString, nil)
.
ListenAndServe Is a blocking call, and usually is left as the last statement of your main
.
you could launch it in a goroutine with go http.ListenAndServe(...)
and then the sayhello()
function will be called, but then the entire program will reach the end of main and all the goroutines will be terminated.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论