服务器启动时的日志

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

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之后打印日志消息,因为它会阻塞并且永远不会返回,所以基本上你有两个主要选项:

  1. 只打印“在端口上启动服务器...”这样的消息 - 但是如果ListenAndServe无法启动,它会返回一个错误,所以除非由于这个原因打印了一些错误或恐慌,否则你可以假设服务器已经启动。

  2. 在一个单独的goroutine中调用ListenAndServe,并确保没有返回错误,然后打印“服务器已启动...”等等。

我个人更喜欢第一种方法。

英文:

You can't print a log message after ListenAndServe since it blocks and never returns, so basically you have two main options:

  1. 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.

  2. 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
}

这是一个更大的示例,其中服务器使用ListenServe分别进行验证。以这种方式进行操作的好处是可以轻松捕获不正确的端口。

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 &lt;-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 &lt;- true.

package main

import (
    &quot;log&quot;
    &quot;net/http&quot;
)

func MyHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(&quot;Hello World&quot;))
}

func main() {
    port := &quot;8080&quot;

    http.HandleFunc(&quot;/&quot;, MyHandler)

	done := make(chan bool)
    go http.ListenAndServe(&quot;:&quot;+port, nil)
    log.Printf(&quot;Server started at port %v&quot;, port)
    &lt;-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 (
    &quot;log&quot;
    &quot;net&quot;
    &quot;net/http&quot;
    &quot;os&quot;
)

func MyHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(&quot;Hello World&quot;))
}

func main() {
    port := &quot;8080&quot;

    http.HandleFunc(&quot;/&quot;, MyHandler)

    listener, err := net.Listen(&quot;tcp&quot;, &quot;:&quot;+port)
    if err != nil {
    	log.Fatal(err)
    }

    done := make(chan bool)
    go http.Serve(listener, nil)

    // Log server started
    log.Printf(&quot;Server started at port %v&quot;, port)

    // Attempt to connect
    log.Printf(&quot;Fetching...&quot;)
    res, err := http.Get(&quot;http://&quot; + listener.Addr().String())
    log.Printf(&quot;Received: %v, %v&quot;, res, err)
    if err != nil {
	    log.Fatal(err)
    }
    res.Write(os.Stdout)

    &lt;-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(&quot;Server is started at port 8080&quot;)
		}
	}()
	err := http.ListenAndServe(&quot;:8080&quot;, nil)
	if err != nil {
		errStart = true
		log.Error(...)
	}

huangapple
  • 本文由 发表于 2015年12月16日 20:52:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/34312615.html
匿名

发表评论

匿名网友

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

确定