Created
March 17, 2017 01:55
-
-
Save shautzin/19d8126aa46093d760f952e74abc75ba to your computer and use it in GitHub Desktop.
Http Get&Post Request by Golang
This file contains 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
type Resp struct { | |
status string // http status | |
response []byte // http response | |
err error // err | |
} | |
func get(u string, param map[string]string) *Resp { | |
queryValues := url.Values{} | |
for k, v := range param { | |
queryValues[k] = []string{v} | |
} | |
u = strings.Join([]string{u, queryValues.Encode()}, "?") | |
resp, err := http.Get(u) | |
if err != nil { | |
return &Resp{"", nil, err} | |
} | |
buf, err := ioutil.ReadAll(resp.Body) | |
resp.Body.Close() | |
if err != nil { | |
return &Resp{resp.Status, nil, err} | |
} | |
return &Resp{resp.Status, buf, nil} | |
} | |
func post(u string, param map[string]string) *Resp { | |
formValues := url.Values{} | |
for k, v := range param { | |
formValues[k] = []string{v} | |
} | |
resp, err := http.PostForm(u, formValues) | |
if err != nil { | |
return &Resp{"", nil, err} | |
} | |
buf, err := ioutil.ReadAll(resp.Body) | |
resp.Body.Close() | |
if err != nil { | |
return &Resp{resp.Status, nil, err} | |
} | |
return &Resp{resp.Status, buf, nil} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment