我从Go开发开始.http服务器启动时是否有任何方法可以打印?例如"Server is started at port 8080"
在Node(使用Express)中,它会像:
app.listen(8080, function() { console.log('Server started at port 8080') });
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
func main() {
http.HandleFunc("/", MyHandler)
http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
ListenAndServe由于它阻止并且永不返回,因此您无法打印日志消息,因此基本上您有两个主要选项:
打印"在端口上启动服务器...."就是这样 - 但是如果ListenAndServe无法启动它会返回错误,所以除非因此而打印出一些错误或恐慌,否则您可以假设服务器已启动.
ListenAndServe在一个单独的goroutine中调用,并确保没有返回错误并打印"服务器启动..."等.
我个人更喜欢第一种方法.
使用Go的日志包:
package main
import (
"net/http"
"log"
)
func main() {
addr := ":8080"
http.HandleFunc("/", MyHandler)
log.Println("listen on", addr)
log.Fatal( http.ListenAndServe(addr, nil) )
}
Run Code Online (Sandbox Code Playgroud)
http.ListenAndServe打开服务器端口,永远阻止等待客户端.如果无法打开端口,则log.Fatal呼叫将报告问题并退出程序.
要ListenAndServe在 Not_a_Golfer 提到的 goroutine 中运行,您可以使用无缓冲的阻塞通道在 goroutine 中运行它并保持服务器处于活动状态。
下面的示例创建了一个名为donewhere的通道,<-done它将在服务器等待 goroutine 完成时保持活动状态,在这种情况下不会。通常,goroutine 会通过执行来告诉主函数它已完成done <- true。
package main
import (
"log"
"net/http"
)
func MyHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
}
func main() {
port := "8080"
http.HandleFunc("/", MyHandler)
done := make(chan bool)
go http.ListenAndServe(":"+port, nil)
log.Printf("Server started at port %v", port)
<-done
}
Run Code Online (Sandbox Code Playgroud)
这是一个更大的示例,它让服务器验证它是否可以运行、使用Listen和Serve单独进行。这样做的好处是您可以轻松捕获不正确的端口。
package main
import (
"log"
"net"
"net/http"
"os"
)
func MyHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
}
func main() {
port := "8080"
http.HandleFunc("/", MyHandler)
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatal(err)
}
done := make(chan bool)
go http.Serve(listener, nil)
// Log server started
log.Printf("Server started at port %v", port)
// Attempt to connect
log.Printf("Fetching...")
res, err := http.Get("http://" + listener.Addr().String())
log.Printf("Received: %v, %v", res, err)
if err != nil {
log.Fatal(err)
}
res.Write(os.Stdout)
<-done
}
Run Code Online (Sandbox Code Playgroud)