Like us on Facebook!

Saturday, 23 July 2016

Currency Converter Client/Server using GO

Currency Converter Client/Server using GO

Today’s experiment involves writing a client/server program that converts currency to ETB.

The server listens on port:12345 to handle client requests.

Function XeCurrencyServer is called whenever a request comes in.

XeCurrencyServer:

Strips out “/” from the request

 * I am only interested in converting USD, GBP and EUR to ETB - strings.Split(req.URL.Path,"/")
  * Builds request URL to fetch - http.Get(currency_requested). 
 * I use xe.com all of the time. 
        * I extract a specific line that has the data that we need - regexp.MustCompile(`\&\w+;`+cur[1]+`\&\w+;=\&\w+;(\d+\.\d+)\&\w+;ETB`) and currencyRegex.FindStringSubmatch(bodyString)
        * Write the result back using w http.ResponseWriter
        * Anything else is ignored.

Code
====
        * src/example/currency/convert.go
        * To install: go install example/currency
        * To run: $GOPATH/bin/currency
        * Url: http://178.62.226.141:12345/GBP 
Git
===
        * https://gitlab.com/baricho/currency-go-example
Docs ==== * https://gobyexample.com/ - covers a lot of things with easy to follow examples * https://golang.org/doc/ - golang doc page * https://golang.org/pkg/ - package info * http://regexr.com/ - regex builder This is something that is very basic but should give you the basic understanding on how to get going with GO.



package main

import (
 "net/http"
 "log"
 "io"
 "fmt"
 "net/http/httputil"
 "regexp"
 "strings"
)

func XeCurrencyServer(w http.ResponseWriter, req *http.Request) {

 cur := strings.Split(req.URL.Path,"/")
 fmt.Fprintf(w, "<html><body><br><br><br>")
 if cur[1] == "USD" || cur[1] == "GBP" || cur[1] == "EUR" {

  currency_requested := ("http://www.xe.com/currencyconverter/convert/?Amount=1&From="+cur[1]+"&To=ETB")
         response, err := http.Get(currency_requested)
 
  var currencyRegex = regexp.MustCompile(`\&\w+;`+cur[1]+`\&\w+;=\&\w+;(\d+\.\d+)\&\w+;ETB`)
         if err != nil {
                 log.Fatal(err)
         } else {
                 defer response.Body.Close()
   dump, err := httputil.DumpResponse(response, true)
   bodyString := string(dump) 
   conversion := currencyRegex.FindStringSubmatch(bodyString)
   for k, v := range conversion {
    if k > 0 {
     fmt.Fprintf(w, "1.00 %s == %s ETB", cur[1], v)
    }
   }
                 if err != nil {
    io.WriteString(w,"Error communicating with xe.com")
                         log.Fatal(err)
                 }
         }
 } else {
  fmt.Fprintf(w, "Currency requested not found: %s", cur[1])
 }
 fmt.Fprintf(w, "</body></html>")
}

func main() {
 http.HandleFunc("/", XeCurrencyServer)
 
 log.Fatal(http.ListenAndServe(":12345", nil))
}


As always do give it a try and provide feedback!

Peace!

No comments:

Post a Comment

Have your say!