Last active
March 8, 2019 06:26
-
-
Save kholidfu/b018bd3df55025e4f85d70681cf41e3b to your computer and use it in GitHub Desktop.
HTTP request to JSON and parse it
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
// @kholidfu - https://kholidfu.blogspot.com | |
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
) | |
// IP struct | |
type ip struct { | |
IP string `json:"ip"` | |
RejectFascism string `json:"reject-fascism"` | |
} | |
func main() { | |
url := "https://jsonip.com/" | |
// open HTTP request to url | |
r, err := http.Get(url) | |
// check error | |
if err != nil { | |
panic(err.Error()) | |
} | |
defer r.Body.Close() | |
// read the body | |
b, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
panic(err.Error()) | |
} | |
// if HTTP status 200 | |
if r.StatusCode == 200 { | |
// print the response body | |
// fmt.Println(string(b)) | |
ip1 := ip{} | |
err := json.Unmarshal(b, &ip1) | |
if err != nil { | |
panic(err.Error()) | |
} | |
fmt.Println(ip1.IP) | |
fmt.Println(ip1.RejectFascism) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment