Skip to content

Instantly share code, notes, and snippets.

@kholidfu
Last active March 8, 2019 06:26
Show Gist options
  • Save kholidfu/b018bd3df55025e4f85d70681cf41e3b to your computer and use it in GitHub Desktop.
Save kholidfu/b018bd3df55025e4f85d70681cf41e3b to your computer and use it in GitHub Desktop.
HTTP request to JSON and parse it
// @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