Использование API с Golang
Я начал изучать Go или Golang. Это забавный язык; Мне нравится узнавать об этом. Иногда мне сложно найти проект по применению языка программирования. Не из-за нехватки информации или ресурсов об этом. Но за огромное количество.
Мой первый проект с использованием Go — это программа, использующая фруктовый API. Вы пишете название фрукта в консоли, и он выдает что-то вроде этого:
{
"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
}
}
Первым делом нужно импортировать пакеты из стандартной библиотеки:
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.
}