Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func updateExchangeRate(code string)error{
- var rate float64
- switch (code){
- case "USD", "EUR", "CHF":
- resp, err := http.Get("http://currency-api.appspot.com/api/GBP/"+code+".json?key="+currency_api_key)
- if err != nil{
- return err
- }
- defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return err
- }
- var data struct{
- Success bool
- Source string
- Target string
- Rate float64
- Message string
- }
- err = json.Unmarshal(body, data)
- if err != nil {
- return err
- }
- if data.Success != true {
- err = errors.New(data.Message)
- return err
- }
- rate = data.Rate
- break
- default:
- err := errors.New("Unsupported currency code")
- return err
- }
- CurrencyRates[code] = rate_obj{
- Rate: rate,
- Expiry: time.Now().Unix() + (12*60*60),//12 hour expiry
- }
- return nil
- }
- func GetExchangeRate(code string)(float64, error){
- if CurrencyRates[code].Rate == 0 || CurrencyRates[code].Expiry >= time.Now().Unix() {
- err := updateExchangeRate(code)
- return 0, err
- }
- return CurrencyRates[code].Rate, nil
- }
- func ConvertCurrency(source, target string, value float64) (amount float64, err error){
- var src_rate, tgt_rate float64
- if source != "GBP"{
- src_rate, err = GetExchangeRate(source)
- if err != nil {
- return
- }
- }else{
- src_rate = 1.0
- }
- if target != "GBP"{
- tgt_rate, err = GetExchangeRate(source)
- if err != nil {
- return
- }
- }else{
- tgt_rate = 1.0
- }
- amount = value * (1/src_rate) * tgt_rate
- return
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement