<p>here is my code </p>
<pre><code>func TimeShow(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
fmt.Printf("%s>%s\t>\t%d\n",time.Since(start).String(),r.URL.String(),200)
})
}
</code></pre>
<p>what it is supposed to do is go get information about the current request and log this. Currently everything is fine but i have no clue how to get the status code. Do you have any ideas ?</p>
<hr/>**评论:**<br/><br/>TheMerovius: <pre><p>Re-implementing your own <code>ResponseWriter</code> is the way to do this, but keep in mind, that you are <a href="https://blog.merovius.de/2017/07/30/the-trouble-with-optional-interfaces.html" rel="nofollow">hiding optional methods in the process</a>.</p></pre>nemith: <pre><p>http.ReponseWritter is an interface so you can implement your own. Here is something I use regularly.</p>
<pre><code>type statusWriter struct {
http.ResponseWriter
status int
length int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = 200
}
n, err := w.ResponseWriter.Write(b)
w.length += n
return n, err
}
func LogHTTP(handler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := statusWriter{ResponseWriter: w}
handler.ServeHTTP(&sw, r)
duration := time.Now().Sub(start)
Log(LogEntry{
Host: r.Host,
RemoteAddr: r.RemoteAddr,
Method: r.Method,
RequestURI: r.RequestURI,
Proto: r.Proto,
Status: sw.status,
ContentLen: sw.length,
UserAgent: r.Header.Get("User-Agent"),
Duration: duration,
})
}
}
</code></pre></pre>nefthias: <pre><p>i see so theres really no way of doing this without creating my own response writer and passing it down each time for each endpoint </p></pre>nemith: <pre><p>You need to wrap your handler anyway. </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传