Make an authenticated #HTTP Get request and parse #JSON in #Golang
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.
When I try to use the basicAuth function defined above I am getting the wrong result. Here is what I have:
func basicAuth(username, password string) string {
auth := username + “:” + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
Inputs used:
user = test
password = 123
Expected result should be: Basic dGVzdDoxMjM=
Actual result was: Basic dGVzdA0KOjEyMw0K
Does anyone have any suggestions on what may be going wrong?
Thanks.
LikeLike