Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
golang简易静态服务器终端打印_Go - Fatal编程技术网

golang简易静态服务器终端打印

golang简易静态服务器终端打印,go,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.

这是我最初的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服务器,我需要添加新的功能,每个get请求打印在linux终端ip,方法,/请求

终端需求中的输出示例:

95.250.33.36 GET /
95.250.33.36 GET /favicon.ico
95.250.33.36 GET /robots.txt

我怎样才能做到这一点呢?

Golang最好的地方就是界面。 您的helloHandler实际上实现了接口。 使用,我们可以使用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协议版本 主机指定在其上查找URL的主机
fmt.Println?这是我在golang开发的第一天,我不知道如何调用ip和requestr*http.Request有什么问题?root@kali:~/ss go run 111.go命令行参数。/111.go:14:未定义:wrapperHandler.ServeHTTP中的wrapperHandler./111.go:27:无法使用helloHandler类型funchttp.ResponseWriter,*http.Request作为Wraphandler的参数中的类型http.Handler,其日志记录为:funchttp.ResponseWriter,*http.Request未实现http.Handler缺少ServeHTTP方法。/111.go:27:无法使用wrapHandlerWithLogginghelloHandler类型http.Handler作为类型funchttp.ResponseWriter,*http.Request作为http的参数。HandleFunc@kingcope我修正了密码。请随意测试。@kingcope为什么没有按照我40分钟前的建议检查http.Request?如果你连阅读文档都不费心的话,你该怎么学习呢?