这是我最初的 golang 代码:
package main
import (
"net/http"
"io"
)
const hello = `hello world`
func helloHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, hello)
}
func main() {
http.HandleFunc("/", helloHandler)
http.ListenAndServe(":1088", nil)
}
这是一个简单的http服务器,我需要添加新的功能,在linux终端ip、METHOD、/request中打印每个get请求。
终端需要的示例输出:
95.250.33.36 GET /
95.250.33.36 GET /favicon.ico
95.250.33.36 GET /robots.txt
我该怎么做?
最佳答案
Golang 最好的地方就是接口(interface)。
您的 helloHandler
实际上实现了 HandlerFunc
界面。
使用 Open/Close Principle我们可以使用 helloHandler
并扩展它以通过以下方式记录请求:
func wrapHandlerWithLogging(wrappedHandler http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
log.Printf("--> %s %s", req.Method, req.URL.Path)
wrappedHandler.ServeHTTP(w, req)
})
}
func main() {
...
http.HandleFunc("/", wrapHandlerWithLogging(http.HandlerFunc(helloHandler)))
...
}
基本上,我们用另一个 HandlerFunc
包装实现了 HandlerFunc
的 helloHandler
。
在此示例中,我们仅记录请求方法(GET、POST、PUT 等)和请求路径(例如“/”)。但是,您可以记录其他数据:
req.RemoteAddr
发送请求的网络地址req.Proto
协议(protocol)版本req.Host
指定在其上查找 URL 的主机
关于终端上的golang简单静态服务器打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45909745/