currency/main.go
Michael 6c112b65f9 removed dependance on external library
Signed-off-by: Michael <michael.lindman@gmail.com>
2022-03-22 19:58:24 +00:00

62 lines
1.2 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
)
const url = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/"
func request(url string) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return body, nil
}
return nil, fmt.Errorf("request: %s - %d %s", url, resp.StatusCode, http.StatusText(resp.StatusCode))
}
func main() {
from, to, value := ui()
body, err := request(url + from + "/" + to + ".json")
if err != nil {
log.Fatal(err)
}
var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil {
log.Fatal(err)
}
v, ok := result[to].(float64)
if !ok {
log.Fatal("invalid conversion")
}
fmt.Printf("%.2f %s\n", v*value, to)
}
func ui() (from, to string, value float64) {
if len(os.Args) < 4 {
os.Exit(1)
}
val, err := strconv.ParseFloat(os.Args[3], 64)
if err != nil {
log.Fatal(err)
}
return os.Args[1], os.Args[2], val
}