Files
CMNETSMSInfo/internal/cmnet/debug.go
T

117 lines
2.7 KiB
Go

package cmnet
import (
"bytes"
"log"
"net/http"
"net/url"
"strings"
)
// debugEnabled 为调试总开关。关闭后所有 debugf 调用都不会输出。
const debugEnabled = false
func debugf(format string, args ...any) {
if !debugEnabled {
return
}
log.Printf("调试 "+format, args...)
}
func Debugf(format string, args ...any) {
debugf(format, args...)
}
func DebugOn() bool {
return debugEnabled
}
func (c *Client) debugCookies(where string) {
if !debugEnabled {
return
}
var b strings.Builder
seen := map[string]bool{}
for _, raw := range []string{loginOrigin + "/", shopOrigin + "/", "https://10086.cn/", "https://www.10086.cn/"} {
u, err := url.Parse(raw)
if err != nil {
continue
}
for _, ck := range c.jar.Cookies(u) {
line := u.Hostname() + " " + ck.Name + "=" + ck.Value
if seen[line] {
continue
}
seen[line] = true
if b.Len() > 0 {
b.WriteString(" | ")
}
b.WriteString(line)
}
}
debugf("%s Cookie %s", where, b.String())
}
func debugSetCookies(resp *http.Response) string {
if resp == nil {
return ""
}
parts := make([]string, 0, len(resp.Cookies()))
for _, ck := range resp.Cookies() {
parts = append(parts, ck.Name+"="+ck.Value)
}
return strings.Join(parts, "; ")
}
func debugBody(tag string, buf []byte) {
if !debugEnabled {
return
}
if len(buf) == 0 {
debugf("%s 响应空", tag)
return
}
const limit = 8000
if len(buf) > limit {
debugf("%s 响应 %d 字节 %s", tag, len(buf), string(buf[:limit]))
return
}
debugf("%s 响应 %s", tag, string(buf))
}
func debugHTTP(req *http.Request, resp *http.Response, buf []byte, reqErr error) {
if !debugEnabled || req == nil || req.URL == nil {
return
}
if reqErr != nil {
debugf("%s %s 请求失败 %v", req.Method, req.URL.String(), reqErr)
return
}
if resp == nil {
return
}
ctype := resp.Header.Get("Content-Type")
debugf("%s %s -> %d %s Set-Cookie [%s]", req.Method, req.URL.String(), resp.StatusCode, ctype, debugSetCookies(resp))
if debugSkipBody(req, ctype, buf) {
debugf("%s 响应 %d 字节", req.URL.Path, len(buf))
return
}
debugBody(req.URL.RequestURI(), buf)
}
func debugSkipBody(req *http.Request, ctype string, buf []byte) bool {
ct := strings.ToLower(ctype)
path := strings.ToLower(req.URL.Path)
if strings.Contains(ct, "image") || strings.Contains(ct, "javascript") || strings.Contains(ct, "text/css") {
return true
}
switch {
case strings.HasSuffix(path, ".js"), strings.HasSuffix(path, ".css"), strings.HasSuffix(path, ".png"),
strings.HasSuffix(path, ".jpg"), strings.HasSuffix(path, ".jpeg"), strings.HasSuffix(path, ".gif"),
strings.HasSuffix(path, ".ico"), strings.HasSuffix(path, ".html"):
return true
}
trim := bytes.TrimSpace(buf)
return len(trim) > 0 && trim[0] == '<'
}