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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?