Created
July 18, 2020 12:42
-
-
Save pablospizzamiglio/8425e4a1a08865a72fee99738c2fac4f to your computer and use it in GitHub Desktop.
Trying http requests with Go
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
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"time" | |
) | |
func main() { | |
client := http.Client{ | |
Timeout: time.Duration(30 * time.Second), | |
} | |
req, err := http.NewRequest(http.MethodGet, "https://httpbin.org/get", nil) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
res, err := client.Do(req) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer res.Body.Close() | |
var m map[string]interface{} | |
decoder := json.NewDecoder(res.Body) | |
err = decoder.Decode(&m) | |
if err != nil { | |
log.Fatalf("Decoder 1 error: %+v", err) | |
} | |
fmt.Printf("%+v\n", m) | |
i := 0 | |
for i < 5 { | |
res, err = client.Do(req) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer res.Body.Close() | |
var m map[string]interface{} | |
decoder = json.NewDecoder(res.Body) | |
err = decoder.Decode(&m) | |
if err != nil { | |
log.Fatalf("Decoder 2 error: %+v", err) | |
} | |
fmt.Printf("%+v\n", m) | |
i++ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment