最近工作中涉及到了使用Go來發(fā)送restful請求,因為Go默認的http只提供GO
&PATCH
兩種請求,其余類型的請求需要開發(fā)人員通過http.Request
來實現(xiàn),本文提供PATCH
操作帶json
數(shù)據(jù)的一個Demo邻梆。
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "http://127.0.0.1:5000/api/version/resources/resource_item"
fmt.Println("URL:>", url)
// 使用轉(zhuǎn)義反引號完成json轉(zhuǎn)換
item := "testKey"
updateParams := `{"testKey":"` + item + `"}`
var jsonStr = []byte(updateParams)
req, _ := http.NewRequest(http.MethodPatch, url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, _ := client.Do(req)
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
其他類型請求同上,只需要將動作改為對應的操作即可绎秒。