dongrouyuan5685 2017-08-27 22:04
浏览 159
已采纳

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

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条回答 默认 最新

  • douzhangcuo2174 2017-08-27 22:16
    关注

    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 request
    • req.Proto the protocol version
    • req.Host specifies the host on which URL is sought
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法