What Is The "Best" Way To Get Data From A HTTP Request

Hello mates, I am getting data like the following below using Regex, nevertheless I think that is not the best way to get these infos.

{"transactions": [{
    "bytes":null,
    "length":1,
    "time":"1653228731.000000",
    "name":"Test",
    "status":"success",
    "transfers":[{
          "id":"3",
          "amount":3930,
          "approval":false
      }
}

Using GetXML to get the data as a string, and after selecting each specific info using Regex.

func getXML(url string) (string, error) {
	resp, err := http.Get(url)
	if err != nil {
		return "", fmt.Errorf("GET error: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("Status error: %v", resp.StatusCode)
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("Read body: %v", err)
	}

	return string(data), nil
}

Example of Regex: regexp.MustCompile(`"name":"\s*(.*?)\s*"`)

Well, I feel that is not the most common and efficient manner to get these infos. Probably exist something similar to GetEnv(“name”) that do this for http requests.

Anyone could help me?

  1. The example doesn’t look as if it was XML, but JSON instead
  2. We’d use encoding/xml and encoding/json respectively to get the data into a struct.
4 Likes

The way that I wrote it in fact is looking like a json, but when I get the string from the http it is like that (with no jumped lines and spaces):

{"transactions",[{"bytes":null,"length":1,"time":"1653228731.000000","name":"Test","status":"success","transfers":[{"id":"3","amount":3930,"approval":false}}

Looks still like valid JSON to me…

2 Likes

Yes, you are right! I misunderstood the meaning of XML and JSON. Thank you

XML looks like XHTML:

<?xml version="1.0" encoding="UTF-8"?>
<transactions>
    <length value="1"/>
    <bytes/>
    <time value="1653228731.000000"/>
    ...
</transactions>

JSON looks like:

{key: "value", key2: "value2", key3: [1, 2, 3, 4]}
1 Like