英文:
Log when server is started
问题
在HTTP服务器启动时打印一些内容有没有办法?例如 "Server is started at port 8080"
。
在Node.js中(使用Express框架),可以这样写:
app.listen(8080, function() { console.log('Server started at port 8080') });
以下是你的代码:
func main() {
http.HandleFunc("/", MyHandler)
http.ListenAndServe(":8080", nil)
}
谢谢。
英文:
Is there any way to print something when the http server starts? For instance "Server is started at port 8080"
In Node (using Express), it would be like:
app.listen(8080, function() { console.log('Server started at port 8080') });
This is my code:
func main() {
http.HandleFunc("/", MyHandler)
http.ListenAndServe(":8080", nil)
}
Thanks.
答案1
得分: 18
使用Go的log包:
package main
import (
"net/http"
"log"
)
func main() {
addr := ":8080"
http.HandleFunc("/", MyHandler)
log.Println("监听地址:", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}
http.ListenAndServe
打开服务器端口,并永远阻塞等待客户端连接。如果无法打开端口,log.Fatal
调用将报告问题并退出程序。
英文:
Use Go's log package:
package main
import (
"net/http"
"log"
)
func main() {
addr := ":8080"
http.HandleFunc("/", MyHandler)
log.Println("listen on", addr)
log.Fatal( http.ListenAndServe(addr, nil) )
}
http.ListenAndServe
opens the server port, and blocks forever waiting for clients. If it fails to open the port, the log.Fatal
call will report the problem and exit the program.
答案2
得分: 9
你可以在ListenAndServe
之后打印日志消息,因为它会阻塞并且永远不会返回,所以基本上你有两个主要选项:
-
只打印“在端口上启动服务器...”这样的消息 - 但是如果
ListenAndServe
无法启动,它会返回一个错误,所以除非由于这个原因打印了一些错误或恐慌,否则你可以假设服务器已经启动。 -
在一个单独的goroutine中调用
ListenAndServe
,并确保没有返回错误,然后打印“服务器已启动...”等等。
我个人更喜欢第一种方法。
英文:
You can't print a log message after ListenAndServe
since it blocks and never returns, so basically you have two main options:
-
Print "Starting server on port...." and that's it - BUT if
ListenAndServe
could not start it returns an error, so unless there's some error or panic printed because of that, you can assume the server started. -
Call
ListenAndServe
in a separate goroutine, and make sure there was no error returned and print "Server started..." etc.
I personally prefer the first approach.
答案3
得分: 8
要在goroutine中运行ListenAndServe
,你可以使用一个无缓冲的阻塞通道来在goroutine中运行它并保持服务器的活动状态。
以下示例创建了一个名为done
的通道,其中<-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
}
这是一个更大的示例,其中服务器使用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.Printf("Server started at port %v", port)
// 尝试连接
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
}
英文:
To run ListenAndServe
in a goroutine as mentioned by Not_a_Golfer, you can use an unbuffered, blocking channel to run it in a goroutine and also keep the server alive.
The following example creates a channel called done
where <-done
will keep the server alive as it waits for the goroutine to finish, which it won't in this case. Typically, the goroutine will tell the main function it is finished by executing 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
}
Here's a larger example that has the server verify it is operational, using Listen
and Serve
separately. The nice thing about doing it this way is you can capture an incorrect port easily.
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
}
答案4
得分: 0
或者在goroutine中运行日志命令:
errStart := false
go func() {
time.Sleep(time.Second * 3)
if !errStart {
log.Info("服务器已在端口8080上启动")
}
}()
err := http.ListenAndServe(":8080", nil)
if err != nil {
errStart = true
log.Error(...)
}
英文:
Or to run log command in a goroutine:
errStart := false
go func() {
time.Sleep(time.Second * 3)
if !errStart {
log.Info("Server is started at port 8080")
}
}()
err := http.ListenAndServe(":8080", nil)
if err != nil {
errStart = true
log.Error(...)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论