feat: 调试开关打开时记录全部接口响应
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
crand "crypto/rand"
|
||||
_ "embed"
|
||||
@@ -142,7 +143,7 @@ func main() {
|
||||
mux.HandleFunc("POST /api/resume", app.resume)
|
||||
mux.HandleFunc("POST /api/interval", app.setInterval)
|
||||
|
||||
srv := &http.Server{Addr: cfg.Listen, Handler: mux, ReadHeaderTimeout: 10 * time.Second}
|
||||
srv := &http.Server{Addr: cfg.Listen, Handler: logLocalAPI(mux), ReadHeaderTimeout: 10 * time.Second}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
shut, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
@@ -699,6 +700,44 @@ func decode(r *http.Request, dest any) error {
|
||||
return json.NewDecoder(io.LimitReader(r.Body, 1<<16)).Decode(dest)
|
||||
}
|
||||
|
||||
func logLocalAPI(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !cmnet.DebugOn() || !strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
rec := &bodyCapture{ResponseWriter: w, code: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
body := rec.buf.Bytes()
|
||||
if strings.Contains(rec.Header().Get("Content-Type"), "image") {
|
||||
cmnet.Debugf("本地 %s %s -> %d 图片 %d 字节", r.Method, r.URL.RequestURI(), rec.code, len(body))
|
||||
return
|
||||
}
|
||||
const limit = 8000
|
||||
text := string(body)
|
||||
if len(text) > limit {
|
||||
text = text[:limit]
|
||||
}
|
||||
cmnet.Debugf("本地 %s %s -> %d %s", r.Method, r.URL.RequestURI(), rec.code, strings.TrimSpace(text))
|
||||
})
|
||||
}
|
||||
|
||||
type bodyCapture struct {
|
||||
http.ResponseWriter
|
||||
code int
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (c *bodyCapture) WriteHeader(code int) {
|
||||
c.code = code
|
||||
c.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (c *bodyCapture) Write(p []byte) (int, error) {
|
||||
c.buf.Write(p)
|
||||
return c.ResponseWriter.Write(p)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, code int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
|
||||
Reference in New Issue
Block a user