Consuming a REST API with Go

Consuming a REST API with Go

I started to learn Go or Golang. It is a fun language; I'm enjoying learning about it. Sometimes for me, it's difficult to find a project to apply a programming language. Not because of information shortage or resources about it. But for the huge amount of it.

My first project using Go is a program that consumes a fruit API. You write the name of a fruit in your console and it gives you something like this:

        {
"genus": "Malus",
"name": "Apple",
"id": 6,
"family": "Rosaceae",
"order": "Rosales",
"nutritions": {
    "carbohydrates": 11.4,
    "protein": 0.3,
    "fat": 0.4,
    "calories": 52,
    "sugar": 10.3
       }
     }

The first thing is to import the packages from the standard library:

    package main

    import (
        "fmt"
        "io/ioutil"
         "log"
         "net/http"
          "os"
          "bufio"
          "strings"
    )

  func main () {

       reader := bufio.NewReader(os.Stdin)  // We bufio package to read from the console.

       fmt.Println("Insert your favorite fruit")

       input, err := reader.ReadString('\n')  // Here we speficifie that it is a string what it will read from the console (our fruit).

       if err != nil {
          fmt.Println("An error occured while reading input. Please try again", err) // In case there is an error reading from the console, this error message will appear.
          return
       }

      fruit := strings.TrimSuffix(input, "\r\n") // Every time that a string is read from the console "\r\n" is added, "strings.TrimSuffix" delete it from our fruit.

      response, err := http.Get("https://www.fruityvice.com/api/fruit/" + fruit) // The "net/http" package to consume the API.

      if err != nil {
           fmt.Print(err.Error())  
           os.Exit(1)
       }

      responseData, err := ioutil.ReadAll(response.Body) // ioutil package to read the HTTP response.

     if err != nil {
        log.Fatal(err)
      }
     fmt.Println(string(responseData)) // The program print the response in the console.

 }