Home > database >  Using Go to make a POST request using a JSON file
Using Go to make a POST request using a JSON file

Time:02-10

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)
}

CodePudding user response:

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)

CodePudding user response:

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)
  • Related