golang to send network requests (get and post)

send get request

func httpGet() {
    resp, err :=   http.Get("http://www.01happy.com/demo/accept.php?id=1")
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
    fmt.Println(string(body))
}
// get request parameters into "net/url"
func basicGetURLParams() {
params := url.Values{}
parseURL, err := url.Parse(requestGetURLNoParams)
if err != nil {
log.Println("err")
}
params.Set("aaa", "aaa")
params.Set("age", "23")
//If there are Chinese parameters in the parameters, this method will URLEncode
parseURL.RawQuery = params.Encode()
urlPathWithParams := parseURL.String()
resp, err := http.Get(urlPathWithParams)
if err != nil {
log.Println("err")
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("err")
}
fmt.Println(string(b))
}
///////////////////////////////
Custom request (add headers, cookies)
// You can set request headers to add cookies
func basicGetHeader() {
client := http.Client{}
req, err := http.NewRequest(http.MethodGet, requestGetURLNoParams, nil)
if err != nil {
log.Println("err")
}
// add request header
req.Header.Add("Content-type", "application/json;charset=utf-8")
req.Header.Add("header", "header😂😂")
// add cookies
cookie1 := &http.Cookie{
Name: "aaa",
Value: "aaa-value",
}
req.AddCookie(cookie1)
	// send request
resp, err := client.Do(req)
if err != nil {
log.Println("err")
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("err")
}
fmt.Println(string(b))
}

send post request

func httpPost() {
    resp, err := http.Post("http://www.01happy.com/demo/accept.php",
        "application/x-www-form-urlencoded",
        strings.NewReader("name=cjb"))
    if err != nil {
        fmt.Println(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
    fmt.Println(string(body))
}

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish