Search code examples
jsongoposthttp-post

Read data from a JSON file and send it as a Post request


How can i read data from a json file and send it as a post request to a uri endpoint. I am currently learning the Go language and working on my first learning project.

This is my sample data

// parent.json

{"name":"Jade Copnell","age":16,"gender":"Agender","occupation":"Account Representative II","numbers":"178-862-5967","children":{"name":"Kayne Belsham","age":38,"gender":"Genderqueer","occupation":"Clinical Specialist","interest":"Re-engineered discrete methodology","number":"145-355-4123"},"friends":{"name":"Stephi Aries","age":74,"gender":"Genderqueer","occupation":"Senior Sales Associate","numbers":"873-726-1453","interests":"Self-enabling systematic function","methow":"24/7"}}

This is what I have written, when i run the below script, I tend to get a data similar to the below as output and I also get empty data sent to the database.

"{\"name\":\"Jade Copnell\",\"age\":16,\"gender\":\"Agender\",\"occupation\":\"Account Representative II\",\"numbers\":\"178-862-5967\",\"children\":{\"name\":\"Kayne Belsham\",\"age\":38,\"gender\":\"Genderqueer\",\"occupation\":\"Clinical Specialist\",\"interest\":\"Re-engineered discrete methodology\",\"number\":\"145-355-4123\"},\"friends\":{\"name\":\"Stephi Aries\",\"age\":74,\"gender\":\"Genderqueer\",\"occupation\":\"Senior Sales Associate\",\"numbers\":\"873-726-1453\",\"interests\":\"Self-enabling systematic function\",\"methow\":\"24/7\"}}"
func main() {
    // Open the file.
    f, _ := os.Open("./go_data/parent.json")
    // Create a new Scanner for the file.
    scanner := bufio.NewScanner(f)
    // Loop over all lines in the file and print them.
    for scanner.Scan() {
        responseBody := scanner.Text()

        postBody, _ := json.Marshal(responseBody)
        //fmt.Println(postBody)
        time.Sleep(2 * time.Second)
        webBody := bytes.NewBuffer(postBody)
        // fmt.Println(webBody)

        resp, err := http.Post("http://127.0.0.1:5000/v1/parent", "application/json", webBody)

        if err != nil {
            log.Fatalf("An Error Occured %v", err)
        }
        time.Sleep(2 * time.Second)
        defer resp.Body.Close()
    }
}


Solution

  • What if you do this instead. The third argument to http.Post is an io.Reader interface - that your file "f" implements.

    package main
    
    import (
        "bufio"
        "log"
        "net/http"
        "os"
        "time"
    )
    
    func main() {
        // Open the file.
        f, _ := os.Open("./go_data/parent.json")
    
        resp, err := http.Post("http://127.0.0.1:5000/v1/parent", "application/json", f)
    
        if err != nil {
            log.Fatalf("An Error Occured %v", err)
        }
        time.Sleep(2 * time.Second)
        defer resp.Body.Close()
    }