英文:
golang simple static server print on terminal
问题
这是我的初始 Golang 代码:
package main
import (
"net/http"
"io"
"log"
)
const hello = `hello world`
func helloHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, hello)
}
func logHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
func main() {
http.HandleFunc("/", logHandler(helloHandler))
http.ListenAndServe(":1088", nil)
}
这是一个简单的 HTTP 服务器,你想要添加一个新的功能,即每个 GET 请求都在 Linux 终端中打印出 IP、METHOD 和 /request。
你可以通过添加一个名为 logHandler
的中间件来实现这个功能。这个中间件将在处理每个请求之前打印出请求的信息。在 main
函数中,将 logHandler
应用到 helloHandler
上,这样每个请求都会经过 logHandler
。
希望对你有帮助!
英文:
this is my initial golang code :
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)
}
it is a simple http server, i need add new function, every get request print in linux terminal ip, METHOD, /request.
example output in terminal need:
95.250.33.36 GET /
95.250.33.36 GET /favicon.ico
95.250.33.36 GET /robots.txt
how i can do this ?
答案1
得分: 2
Golang最好的地方就是接口。你的helloHandler
实际上实现了HandlerFunc
接口。使用开闭原则,我们可以对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
:协议版本req.Host
:指定所请求的主机名
英文:
The best thing about Golang is interfaces.
Your helloHandler
actually implements the HandlerFunc
interface.
Using the Open/Close Principle we can take helloHandler
and extend it for logging the request in the following way:
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)))
...
}
So basically, we wrap helloHandler
which implements HandlerFunc
with another HandlerFunc
.
In this example, we only log the request method (GET, POST, PUT and etc) and the request path (e.g. '/'). However, you can log other data:
req.RemoteAddr
network address that sent the requestreq.Proto
the protocol versionreq.Host
specifies the host on which URL is sought
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论