我尝试使用 Apiary 并制作了一个通用模板来将 JSON 发送到模拟服务器并使用以下代码:
package main import ( "encoding/json" "fmt" "github.com/jmcvetta/napping" "log" "net/http" ) func main() { url := "http://restapi3.apiary.io/notes" fmt.Println("URL:>", url) s := napping.Session{} h := &http.Header{} h.Set("X-Custom-Header", "myvalue") s.Header = h var jsonStr = []byte(` { "title": "Buy cheese and bread for breakfast." }`) var data map[string]json.RawMessage err := json.Unmarshal(jsonStr, &data) if err != nil { fmt.Println(err) } resp, err := s.Post(url, &data, nil, nil) if err != nil { log.Fatal(err) } fmt.Println("response Status:", resp.Status()) fmt.Println("response Headers:", resp.HttpResponse().Header) fmt.Println("response Body:", resp.RawText()) }
此代码未正确发送 JSON,但我不知道为什么。JSON 字符串在每次调用中都可以不同。我不能用Struct这个。
Struct
我不熟悉napping,但使用 Golang 的net/http包工作正常(play.golang):
net/http
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)) }