Home > Uncategorized > Make an authenticated #HTTP Get request and parse #JSON in #Golang

Make an authenticated #HTTP Get request and parse #JSON in #Golang

1-br-Z8sy61DQ6l5FmG129OQ

Go is a programming language developed by Google, and with a name like that behind it, it’s worth learning a little about it, so, here’s a quick code example that make a HTTP get request, with basic authentication, and parses the response as a Json object.

package main

import “net/http”
import “fmt”
import “io/ioutil”
import “encoding/base64”
import “encoding/json”

func basicAuth(username, password string) string {
auth := username + “:” + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}

func australia_lookup(registration_number, state, username, password string) interface{} {

url := string(“https://www.regcheck.org.uk/api/json.aspx/CheckAustralia/” + registration_number + “/” + state)
return generic_lookup(url, username, password)
}

func usa_lookup(registration_number, state, username, password string) interface{} {

url := string(“https://www.regcheck.org.uk/api/json.aspx/CheckUSA/” + registration_number + “/” + state)
return generic_lookup(url, username, password)
}

func european_lookup(endpoint, registration_number, username, password string) interface{} {

url := string(“https://www.regcheck.org.uk/api/json.aspx/” + endpoint + “/” + registration_number)
return generic_lookup(url, username, password)
}

func generic_lookup(url, username, password string) interface{} {

var client http.Client

req, err := http.NewRequest(“GET”, url, nil)
req.Header.Add(“Authorization”,”Basic “+basicAuth(username,password))

if err != nil {}
resp, err3 := client.Do(req)

if err3 != nil {}

defer resp.Body.Close()

if resp.StatusCode == 200 { // OK
bodyBytes, err2 := ioutil.ReadAll(resp.Body)
bodyString := string(bodyBytes)
var data interface{}
json.Unmarshal([]byte(bodyString), &data)
return data
if err2 != nil {}
}
return nil

}

func main() {

data := european_lookup(“Check”,”SL14MKM”,”***your username***”,”***your password***”)

m := data.(map[string]interface{})
//fmt.Printf(“%+v”, m)
fmt.Println(m[“Description”])
}

The example uses the RegCheck webservice, so you’ll need a username and password to check this out.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: