登录
首页 >  Golang >  Go问答

如何使用 JSON 文件在 GO 中发送请求负载数据?

来源:stackoverflow

时间:2024-02-11 10:18:23 393浏览 收藏

本篇文章给大家分享《如何使用 JSON 文件在 GO 中发送请求负载数据?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我对编码和 Golang 本身都很陌生。 我想知道如何在 GO 中使用 JSON 文件发送请求负载数据?

我的意思是,我有一个 post 请求和 JSON 文件,我想将其放入请求正文中,但我遇到了一些错误。

当我使用替代 HTTP 客户端时,该请求有效。


正确答案


根据 http 请求的性质,您也许可以使用现有的客户端包。例如,JSON RPC

如果您想了解如何使用标准库发出请求,这里有一个示例。此示例还演示了如何使用 context 设置客户端请求的超时:

package main

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

func main() {
    ctx := context.Background()
    var client http.Client

    reqCtx, cancel := context.WithTimeout(ctx, time.Minute)
    defer cancel()
    err := deleteEntry(reqCtx, &client, 42)

    fmt.Println(err)
}

func deleteEntry(ctx context.Context, client *http.Client, entryID int) error {
    payload := &struct {
        EntryID int    `json:"entry_id"`
        Method  string `json:"method"`
    }{
        EntryID: entryID,
        Method:  "delete",
    }

    buf, err := json.Marshal(payload)
    if err != nil {
        return err
    }

    req, err := http.NewRequestWithContext(ctx, "POST", "http://localhost/example", bytes.NewReader(buf))
    if err != nil {
        return err
    }
    req.Header.Set("Content-Type", "application/json")

    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    // Note: Response body must always be closed.
    // Response body data (if any) should be consumed before closure, otherwise the
    // the client connection may not be reused.
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("request failed with %s", resp.Status)
    }
    return nil
}

我建议阅读 net/http 文档以获得更好的理解。特别是:

终于介绍完啦!小伙伴们,这篇关于《如何使用 JSON 文件在 GO 中发送请求负载数据?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>