You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang中如何使用fasthttp正确发送键值对格式请求体?

在fasthttp中发送键值对格式的请求体

在fasthttp里,对应标准库net/http中url.Values的是fasthttp.Args结构体,它专门用来处理application/x-www-form-urlencoded类型的键值对请求体,用法和url.Values类似但更贴合fasthttp的设计。

以下是修改后的完整示例代码,替换你原来的JSON请求逻辑,改成键值对格式:

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/valyala/fasthttp"
)

var client *fasthttp.Client

// 表单类型的Content-Type
var headerContentTypeForm = []byte("application/x-www-form-urlencoded")

func main() {
	readTimeout, _ := time.ParseDuration("500ms")
	writeTimeout, _ := time.ParseDuration("500ms")
	maxIdleConnDuration, _ := time.ParseDuration("1h")

	client = &fasthttp.Client{
		ReadTimeout:                   readTimeout,
		WriteTimeout:                  writeTimeout,
		MaxIdleConnDuration:           maxIdleConnDuration,
		NoDefaultUserAgentHeader:      true,
		DisableHeaderNamesNormalizing: true,
		DisablePathNormalizing:        true,
		Dial: (&fasthttp.TCPDialer{
			Concurrency:      4096,
			DNSCacheDuration: time.Hour,
		}).Dial,
	}
	reqTimeout := time.Duration(100) * time.Millisecond

	// 构建键值对参数
	args := &fasthttp.Args{}
	args.Add("login", "login")
	args.Add("pass", "password")

	req := fasthttp.AcquireRequest()
	defer fasthttp.ReleaseRequest(req) // 用defer确保资源释放

	req.SetRequestURI("https://oskelly.ru/api/v2/account/rawauth")
	req.Header.SetMethod(fasthttp.MethodPost)
	req.Header.SetContentTypeBytes(headerContentTypeForm)
	// 将Args编码为标准键值对格式的请求体
	req.SetBody(args.QueryString())

	resp := fasthttp.AcquireResponse()
	defer fasthttp.ReleaseResponse(resp)

	err := client.DoTimeout(req, resp, reqTimeout)
	if err != nil {
		fmt.Printf("ERR request failed: %v\n", err)
		return
	}

	statusCode := resp.StatusCode()
	respBody := resp.Body()
	fmt.Printf("DEBUG Response: %s\n", respBody)

	if statusCode == http.StatusOK {
		fmt.Printf("DEBUG Request succeeded with status 200\n")
	} else {
		fmt.Printf("ERR invalid HTTP response code: %d\n", statusCode)
	}
}

关键说明:

  • 参数构建:用fasthttp.Args的Add方法添加键值对,和url.Values的Add用法一致;如果要设置单个键的唯一值,可用Set方法。
  • Content-Type设置:必须指定为application/x-www-form-urlencoded,这是键值对表单请求的标准类型,和你预期的请求格式匹配。
  • 请求体生成:args.QueryString()会自动把键值对编码成key1=value1&key2=value2格式的字节流,直接作为请求体即可。
  • 资源管理:用defer提前声明请求/响应对象的释放,避免资源泄漏,比原写法更稳妥。

如果一定要用标准库的url.Values,可以先将其编码为字节流再传入,但推荐使用fasthttp.Args——它是为fasthttp优化的类型,性能更好且更贴合框架生态。

内容的提问来源于stack exchange,提问作者0xnina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:20:46