我尝试使用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
我对打n并不熟悉,但是使用Golang的net/http程序包可以很好地工作(游乐场):
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)) }