Skip to content

Instantly share code, notes, and snippets.

@bitristan
Created July 14, 2015 02:31
Show Gist options
  • Save bitristan/52ae0f981d7b86e0b34f to your computer and use it in GitHub Desktop.
Save bitristan/52ae0f981d7b86e0b34f to your computer and use it in GitHub Desktop.
Send get and post request by golang
//发送get请求
func get(url string) string {
response, err := http.Get(url)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
return string(contents)
}
return ""
}
// 发送post请求
func post(url string, jsonData string) string {
var jsonStr = []byte(jsonData)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
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)
return string(body)
}
@marcuxyz
Copy link

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment