package httpclient import ( "bytes" "context" "encoding/json" "errors" "io" "net/http" "net/url" "strings" "time" "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" ) // Request 描述单次请求,不保存跨请求的可变参数或供应商成功规则。 type Request struct { Method string `json:"method" dc:"HTTP 方法,缺省 GET"` URL string `json:"url" dc:"HTTP(S) 目标地址,不进入执行日志"` PathParams map[string]string `json:"path_params,omitempty" dc:"仅替换路径中的花括号占位符,值按单段转义"` Header http.Header `json:"-" dc:"原生请求头,构造时复制,避免凭据被意外序列化"` Query url.Values `json:"-" dc:"多值查询参数,同名配置覆盖 URL 中已有值,保留多值顺序"` Body io.Reader `json:"-" dc:"原始或流式请求正文,与 JSON、Form 互斥"` JSON any `json:"-" dc:"需要原样 JSON 编码的异构 DTO,不转换成 Map,与其他正文互斥"` Form url.Values `json:"-" dc:"URL 编码表单,与 JSON、Body 互斥;非 nil 空表单仍发送空正文"` } // Response 保存有界缓冲结果,不对供应商业务码作推断。 type Response struct { diagnostics diagnostic.Snapshot `dc:"发送时的可信标量快照,不持有请求 Context 或可变对象"` StatusCode int `json:"status_code" dc:"上游真实 HTTP 状态,非 2xx 也保留正文"` Header http.Header `json:"-" dc:"上游原生响应头,不参与默认序列化"` Body []byte `json:"-" dc:"完整响应字节,超限或读取失败时不返回部分正文"` Duration time.Duration `json:"duration" dc:"从构造后发送到正文读取关闭完成的耗时,纳秒"` } // Build 创建原生请求,保留多值参数和正文类型,不执行网络请求。 // 入参:ctx 为非空取消上下文,input 为单次请求参数。 // 返回:可传入 Do 的原生请求;编码或 URL 无效时保留原因链,不修改输入 Header 和 Query。 func Build(ctx context.Context, input Request) (*http.Request, error) { if ctx == nil { return nil, failure.Wrap(CodeContext, "validate outbound request context failed", errors.New("request context is required")) } target, err := url.Parse(input.URL) if err != nil { return nil, failure.WrapContext(ctx, CodeURL, "parse outbound HTTP target failed", err) } if (target.Scheme != "http" && target.Scheme != "https") || target.Host == "" { return nil, failure.WrapContext(ctx, CodeURL, "validate outbound HTTP target failed", errors.New("absolute HTTP or HTTPS URL is required")) } escapedPath := target.EscapedPath() var ( replacements []string ) for name, value := range input.PathParams { replacements = append(replacements, url.PathEscape("{"+name+"}"), url.PathEscape(value)) } if len(replacements) > 0 { escapedPath = strings.NewReplacer(replacements...).Replace(escapedPath) } target.Path, err = url.PathUnescape(escapedPath) if err != nil { return nil, failure.WrapContext(ctx, CodeURL, "expand outbound URL path failed", err) } target.RawPath = escapedPath // 没有查询覆盖时保留原始编码及顺序,避免破坏签名下载地址。 if len(input.Query) > 0 { query, queryErr := url.ParseQuery(target.RawQuery) if queryErr != nil { return nil, failure.WrapContext(ctx, CodeURL, "parse outbound query parameters failed", queryErr) } for name, values := range input.Query { query[name] = append([]string(nil), values...) } target.RawQuery = query.Encode() } count := 0 if input.Body != nil { count++ } if input.JSON != nil { count++ } if input.Form != nil { count++ } if count > 1 { return nil, failure.WrapContext(ctx, CodeBodyConflict, "validate outbound request body selection failed", errors.New("body, JSON and form are mutually exclusive")) } body := input.Body contentType := "" if input.JSON != nil { raw, encodeErr := json.Marshal(input.JSON) if encodeErr != nil { return nil, failure.WrapContext(ctx, CodeJSONEncode, "encode outbound JSON request failed", encodeErr) } body = bytes.NewReader(raw) contentType = "application/json" } else if input.Form != nil { body = strings.NewReader(input.Form.Encode()) contentType = "application/x-www-form-urlencoded" } request, err := http.NewRequestWithContext(ctx, input.Method, target.String(), body) if err != nil { return nil, failure.WrapContext(ctx, CodeRequestBuild, "build outbound HTTP request failed", err) } request.Header = input.Header.Clone() if request.Header == nil { request.Header = make(http.Header) } if contentType != "" && request.Header.Get("Content-Type") == "" { request.Header.Set("Content-Type", contentType) } return request, nil } // Send 构造并执行单次请求,有界读取并关闭响应正文。 // 入参:ctx 为调用上下文,input 为请求参数,原始 Reader 只消费一次。 // 返回:包含非 2xx 在内的完整结果;传输、读取或超限时返回错误,不解析业务码或重试。 // 隐式逻辑:流式或大型下载使用 Do 并由调用方管理读取和关闭,不通过此缓冲接口。 func (c *Client) Send(ctx context.Context, input Request) (result *Response, err error) { request, err := Build(ctx, input) if err != nil { return nil, err } start := time.Now() response, err := c.Do(request) if err != nil { return nil, err } defer func() { closeErr := failure.WrapContext(ctx, CodeResponseClose, "close outbound response body failed", response.Body.Close()) err = errors.Join(err, closeErr) if err != nil { result = nil } else { result.Duration = time.Since(start) } }() body, readErr := io.ReadAll(io.LimitReader(response.Body, c.maxResponseBytes+1)) if readErr != nil { return nil, failure.WrapContext(ctx, CodeResponseRead, "read outbound response body failed", readErr) } if int64(len(body)) > c.maxResponseBytes { return nil, failure.WrapContext(ctx, CodeResponseLimit, "buffer outbound response limit exceeded", ErrResponseTooLarge) } return &Response{StatusCode: response.StatusCode, Header: response.Header.Clone(), Body: body, diagnostics: diagnostic.From(ctx)}, nil } // DecodeJSON 解码单份响应 JSON,保留动态数字精度,不把解析失败当作空数据。 // 入参:target 为 encoding/json 支持的非空接收指针。 // 返回:目标类型不匹配、无效 JSON 或多份 JSON 返回内部错误,原始正文不进入日志。 func (r *Response) DecodeJSON(target any) error { ctx := diagnostic.With(context.Background(), r.diagnostics) decoder := json.NewDecoder(bytes.NewReader(r.Body)) decoder.UseNumber() if err := decoder.Decode(target); err != nil { return failure.WrapContext(ctx, CodeJSONDecode, "decode outbound JSON response failed", err) } var ( extra any ) if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { if err == nil { err = errors.New("multiple JSON values in response") } return failure.WrapContext(ctx, CodeJSONDocuments, "validate outbound JSON document count failed", err) } return nil }