Skip to content

Commit

Permalink
Update convert request with hash and cache
Browse files Browse the repository at this point in the history
  • Loading branch information
meabed committed Sep 26, 2018
1 parent 9146aab commit d1f8511
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions cmd/server/convert.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
package main

import (
"crypto/md5"
"encoding/json"
"fmt"
ex "github.com/me-io/go-swap/pkg/exchanger"
"github.com/me-io/go-swap/pkg/swap"
"math"
"net/http"
"time"
)

func (c convertReqObj) Validate() error {
func (c *convertReqObj) Validate() error {
// todo implement
return nil
}
func (c *convertReqObj) Hash() string {
jsonBytes, _ := json.Marshal(c)
md5Sum := md5.Sum(jsonBytes)
return fmt.Sprintf("%x", md5Sum[:])
}

var Convert = func(w http.ResponseWriter, r *http.Request) {

Expand All @@ -33,8 +40,8 @@ var Convert = func(w http.ResponseWriter, r *http.Request) {
decimalPoint = 4
}

currencyKey := convertReq.From + `/` + convertReq.To
currencyCachedVal := Storage.Get(currencyKey)
currencyCacheKey := convertReq.Hash()
currencyCachedVal := Storage.Get(currencyCacheKey)
currencyCacheTime, _ := time.ParseDuration(convertReq.CacheTime)

if string(currencyCachedVal) == "" {
Expand Down Expand Up @@ -62,7 +69,7 @@ var Convert = func(w http.ResponseWriter, r *http.Request) {
}
Swap.Build()

rate := Swap.Latest(currencyKey)
rate := Swap.Latest(convertReq.From + `/` + convertReq.To)
convertedAmount := math.Round(convertReq.Amount*rate.GetValue()*math.Pow10(decimalPoint)) / math.Pow10(decimalPoint)

convertRes := convertResObj{
Expand All @@ -79,7 +86,7 @@ var Convert = func(w http.ResponseWriter, r *http.Request) {
if currencyCachedVal, err = json.Marshal(convertRes); err != nil {
Logger.Panic(err)
}
Storage.Set(currencyKey, currencyCachedVal, currencyCacheTime)
Storage.Set(currencyCacheKey, currencyCachedVal, currencyCacheTime)
w.Header().Set("X-Cache", "Miss")
} else {
// get from cache
Expand Down

0 comments on commit d1f8511

Please sign in to comment.