Go 使用 io.Pipe()

package main

import (
    "encoding/json"
    "io"
    "log"
    "net/http"
)

type Person struct {
    Name string
    Age  int
    Addr string
}

func main() {
    person := Person{
        Name: "Tom",
        Age:  26,
        Addr: "Beijing",
    }
    pr, pw := io.Pipe()

    go func() {
        defer func() {
            _ = pw.Close()
        }()

        if err := json.NewEncoder(pw).Encode(person); err != nil {
            log.Fatalf("failed to marshal data:%s", err.Error())
        }
    }()

    resp, err := http.Post("https://httpbin.org/post", "application/json;chartset=utf8", pr)
    if err != nil {
        log.Fatalf("failed to post data:%s", err.Error())
        return
    }
    defer func() {
        _ = resp.Body.Close()
    }()
    data, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatalf("failed to read data from resp body:%s", err.Error())
        return
    }
    log.Printf("resp data:%s", data)
}

你可能感兴趣的:(Go 使用 io.Pipe())