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

后端 未结 4 539
执笔经年
执笔经年 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:53

    I'm not familiar with napping, but using Golang's net/http package works fine (playground):

    func main() {
        url := "http://restapi3.apiary.io/notes"
        fmt.Println("URL:>", url)
    
        var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
        req.Header.Set("X-Custom-Header", "myvalue")
        req.Header.Set("Content-Type", "application/json")
    
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            panic(err)
        }
        defer resp.Body.Close()
    
        fmt.Println("response Status:", resp.Status)
        fmt.Println("response Headers:", resp.Header)
        body, _ := ioutil.ReadAll(resp.Body)
        fmt.Println("response Body:", string(body))
    }
    

提交回复
热议问题