How do I send a JSON string in a POST request in Go

后端 未结 4 541
执笔经年
执笔经年 2020-11-30 16:17

I tried working with Apiary and made a universal template to send JSON to mock server and have this code:

package main

import (
    \"encoding/json\"
    \"         


        
4条回答
  •  忘掉有多难
    2020-11-30 16:52

    If you already have a struct.

    import (
        "bytes"
        "encoding/json"
        "io"
        "net/http"
        "os"
    )
    
    // .....
    
    type Student struct {
        Name    string `json:"name"`
        Address string `json:"address"`
    }
    
    // .....
    
    body := &Student{
        Name:    "abc",
        Address: "xyz",
    }
    
    payloadBuf := new(bytes.Buffer)
    json.NewEncoder(payloadBuf).Encode(body)
    req, _ := http.NewRequest("POST", url, payloadBuf)
    
    client := &http.Client{}
    res, e := client.Do(req)
    if e != nil {
        return e
    }
    
    defer res.Body.Close()
    
    fmt.Println("response Status:", res.Status)
    // Print the body to the stdout
    io.Copy(os.Stdout, res.Body)
    

    Full gist.

提交回复
热议问题