从 JSON 文件中读取数据并将其作为 Post 请求发送

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

如何从 json 文件中读取数据并将其作为 post 请求发送到 uri 端点。 我目前正在学习 Go 语言并从事我的第一个学习项目。

这是我的示例数据

// 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"}}

这就是我写的,当我运行下面的脚本时,我往往会得到一个类似于下面的数据作为输出,我也会得到发送到数据库的空数据。

"{\"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()
    }
}

如果你改为这样做会怎么样。 http.Post 的第三个参数是一个 io.Reader 接口——你的文件“f”实现了它。

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