updated to work with changes to underline api

This commit is contained in:
Michael 2024-12-27 03:48:45 +00:00
parent 6c112b65f9
commit 07a09f3c37
Signed by: michael
GPG Key ID: 523BD9EF68BDD44C
3 changed files with 40 additions and 44 deletions

4
go.mod
View File

@ -1,3 +1,5 @@
module git.0cd.xyz/michael/currency
go 1.17
go 1.23.4
require git.0cd.xyz/michael/request v0.1.1

46
main.go
View File

@ -1,61 +1,21 @@
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))
}
const url = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies"
func main() {
from, to, value := ui()
body, err := request(url + from + "/" + to + ".json")
result, err := req(url, from)
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)
v, ok := result[from].(map[string]interface{})[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
}

34
util.go Normal file
View File

@ -0,0 +1,34 @@
package main
import (
"context"
"encoding/json"
"log"
"os"
"strconv"
"git.0cd.xyz/michael/request"
)
func req(url, from string) (body map[string]interface{}, err error) {
resp, err := request.Get(context.Background(), url+"/"+from+".json", nil)
if err != nil {
return nil, err
}
var result map[string]interface{}
if err := json.Unmarshal(resp.Body, &result); err != nil {
return nil, err
}
return result, nil
}
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
}