终端上的golang简单静态服务器打印

标签 go

这是我最初的 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 包装实现了 HandlerFunchelloHandler

在此示例中,我们仅记录请求方法(GET、POST、PUT 等)和请求路径(例如“/”)。但是,您可以记录其他数据:

  • req.RemoteAddr 发送请求的网络地址
  • req.Proto协议(protocol)版本
  • req.Host 指定在其上查找 URL 的主机

关于终端上的golang简单静态服务器打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45909745/

相关文章:

go - 在同一行打印多行字符串

go - 简单的服务器客户端通信不起作用

json - Go - 即时构建 struct/json

go - Go[lang] 二进制文件上的 SetGID/SetUID 安全吗?

go - 如何查看嵌套 Go 依赖项的完整依赖树

go - 如何使用连字符访问命令行参数但在 Go Lang 中没有值

go - 独立应用程序的本地子域

Go例程矩阵乘法错误

去全局变量初始化

go - fmt.Sprint() 返回不正确的结果