A simple GET request can be made like this:
package main import ( "net/http" "ioutil" ) func main() { // Make a get request rs, err := http.Get("https://google.com") // Process response if err != nil { panic(err) // More idiomatic way would be to print the error and die unless it's a serious error } defer rs.Body.Close() bodyBytes, err := ioutil.ReadAll(rs.Body) if err != nil { panic(err) } bodyString := string(bodyBytes) }
POST request:
import ( "bytes" ) func main() { body := []byte("key1=val1&key2=val2") rs, err := http.Post("http://someurl.com", "body/type", bytes.NewBuffer(body)) // Code to process response (written in Get request snippet) goes here // Simulating a form post is done like this: rs, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}}) // Code to process response (written in Get request snippet) goes here }
If more control is needed, like specifying headers, cookies, etc:
// ... client := &http.Client{} req, err := http.NewRequest("GET", "http://example.com", nil) req.Header.Add("If-None-Match", `some value`) resp, err := client.Do(req) // Code to process response
Leave a Reply