Created
August 20, 2024 11:10
-
-
Save cesarmarinhorj/620185fc9c4cba138db06f0e144dfb1d to your computer and use it in GitHub Desktop.
Simple currency exchanges retrieval script. from USD to BRL,EUR using cli flags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"io" | |
"log" | |
"net/http" | |
"os" | |
) | |
var ( | |
url string | |
path string | |
currencies bool | |
from string | |
to string | |
amount float64 | |
) | |
func checkFlags() { | |
flag.BoolVar(¤cies, "currencies", false, "--currencies=true") | |
flag.StringVar(&from, "from", "USD", "--from=USD") | |
flag.StringVar(&to, "to", "BRL,EUR", "--to=BRL,EUR") | |
flag.Float64Var(&amount, "amount", 0.0, "--amount=1.99") | |
flag.Parse() | |
} | |
func makeRequest(path string) string { | |
fmt.Println("Please wait... ") | |
resp, err := http.Get(path) | |
if err != nil { | |
log.Fatal(err) | |
os.Exit(1) | |
} | |
defer resp.Body.Close() | |
body, err := io.ReadAll(resp.Body) | |
if err != nil { | |
log.Fatal(err) | |
os.Exit(1) | |
} | |
return string(body) | |
} | |
func getCurrencies(url string) string { | |
path = fmt.Sprintf("%v/currencies", url) | |
return makeRequest(path) | |
} | |
func getLatestAmountFromTo(url string, amount float64, from string, to string) string { | |
amountValue := "" | |
if amount > 0 { | |
amountValue = fmt.Sprintf("amount=%v&", amount) | |
} | |
path = fmt.Sprintf("%v/latest?%vfrom=%v&to=%v", url, amountValue, from, to) | |
return makeRequest(path) | |
} | |
func main() { | |
url = "https://api.frankfurter.app" | |
checkFlags() | |
if currencies { | |
fmt.Println(getCurrencies(url)) | |
os.Exit(0) | |
} | |
fmt.Println(getLatestAmountFromTo(url, amount, from, to)) | |
os.Exit(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment