-
-
Save timoyuen/6b9ae2739f583ef43a31b590893451fc to your computer and use it in GitHub Desktop.
Send get and post request by golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//发送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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment