Using Go to make a POST request using a JSON file

huangapple go评论138阅读模式
英文:

Using Go to make a POST request using a JSON file

问题

我非常新手Go语言,并在搜索中找不到相关问题,所以如果这是我错过的重复问题,我很抱歉。

我需要使用Go发送一个POST请求,并且请求体来自一个JSON文件。下面是我使用作为起点的https://golangtutorial.dev/tips/http-post-json-go/上的代码的修改版本。

我认为我可以用一个我引入的JSON文件替换jsonData变量,但我只是想知道这是否是正确的方法,以及如何最好地实现。谢谢!

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	httpposturl := "https://reqres.in/api/users"

    // 我认为这是我需要修改的部分?:
	var jsonData = []byte(`{
		"name": "morpheus",
		"job": "leader"
	}`)

	request, error := http.NewRequest("POST", httpposturl, bytes.NewBuffer(jsonData))
	request.Header.Set("Content-Type", "application/json; charset=UTF-8")

	client := &http.Client{}
	response, error := client.Do(request)
	if error != nil {
		panic(error)
	}
	defer response.Body.Close()

	fmt.Println("response Status:", response.Status)
}
英文:

I am very new to Go and searched around for this question but did not find anything, so I apologize if this is a duplicate that I missed.

I need to send a POST request using Go and have the body come from a JSON file. Below is a modified version of the code from https://golangtutorial.dev/tips/http-post-json-go/ that I am using as a starting point.

I am thinking that I can just substitute the jsonData var with a JSON file that I pull in but I just wanted to know if this is the correct approach and how to best go about doing this. Thanks!

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	httpposturl := "https://reqres.in/api/users"

    // I think this is the block I need to alter?:
	var jsonData = []byte(`{
		"name": "morpheus",
		"job": "leader"
	}`)

	request, error := http.NewRequest("POST", httpposturl, bytes.NewBuffer(jsonData))
	request.Header.Set("Content-Type", "application/json; charset=UTF-8")

	client := &http.Client{}
	response, error := client.Do(request)
	if error != nil {
		panic(error)
	}
	defer response.Body.Close()

	fmt.Println("response Status:", response.Status)
}

答案1

得分: 1

要发布一个文件,请将打开的文件作为HTTP请求的主体:

f, err := os.Open("file.json")
if err != nil {
    log.Fatal(err)
}
defer f.Close()

httpposturl := "https://reqres.in/api/users"
request, err := http.NewRequest("POST", httpposturl, f)
if err != nil {
    log.Fatal(err)
}
request.Header.Set("Content-Type", "application/json; charset=UTF-8")

response, err := http.DefaultClient.Do(request)
if err != nil {
    log.Fatal(err)
}
defer response.Body.Close()

fmt.Println("response Status:", response.Status)
英文:

To post a file, use the opened file as the HTTP request body:

f, err := os.Open("file.json")
if err != nil {
	log.Fatal(err)
}
defer f.Close()

httpposturl := "https://reqres.in/api/users"
request, err := http.NewRequest("POST", httpposturl, f)
if err != nil {
	log.Fatal(err)
}
request.Header.Set("Content-Type", "application/json; charset=UTF-8")

response, err := http.DefaultClient.Do(request)
if err != nil {
	log.Fatal(err)
}
defer response.Body.Close()

fmt.Println("response Status:", response.Status)

答案2

得分: 1

注意:无论你想通过http协议发布什么(文字、文件、图片甚至视频等),你实际上都应该将其作为二进制字节的数组进行处理。

在你的情况下,你应该首先打开你想要发布的文件,并创建一个指向该文件的io.Reader类型的实例。简单的代码如下所示:

f, _ := os.Open("./my-file")

http.Post("https://example.com/api", "application/json", f)
英文:

Note: whatever(words, file, image, or even video, etc..) you want to post by the http protocol, you post bytes stream in fact. That means you should treat anything you want to post as an array of binary bytes.

In your case, you should first open the file you want to post, and creates an instance of type io.Reader which pointes to your file. the simple code as belows:

f, _ := os.Open("./my-file")
	
http.Post("https://example.com/api","application/json",f)

huangapple
  • 本文由 发表于 2022年2月9日 08:33:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/71042623.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定