Skip to content

Instantly share code, notes, and snippets.

@t0nyandre
Last active April 1, 2016 12:18
Show Gist options
  • Save t0nyandre/fedd3d58079bea03aac48ca8793c2359 to your computer and use it in GitHub Desktop.
Save t0nyandre/fedd3d58079bea03aac48ca8793c2359 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/csv"
"fmt"
"io/ioutil"
"os"
"runtime"
"strconv"
"strings"
)
// This directory will be watched for incoming files to fetch.
const watchedDir = "./watch"
func main() {
// It's really not necessary to assign more CPU cores to this small application
// but this line gives the application a possibillity to use 4 cores.
runtime.GOMAXPROCS(4)
fmt.Println("Waiting for a product to be added.\n" +
"You can use the \"./watch\" directory to put .csv files with the info about" +
"the product you want added and I will process it automaticly to the DB.\n\n" +
"Thanks.\n\n-------------------")
// Infinite loop (often called while in other languages.)
for {
d, _ := os.Open(watchedDir)
// I'm giving it a negative number to return as many files as it can find
// if I was to give it a positive number x it would've given me x files.
files, _ := d.Readdir(-1)
// A for loop that will lopp through the files found
for _, fi := range files {
filePath := watchedDir + "/" + fi.Name()
// We will open the file
f, _ := os.Open(filePath)
// And extract the content from the file before ...
data, _ := ioutil.ReadAll(f)
// ... closing the file :)
f.Close()
// After we have read and extracted info from the file - we delete it from
// the watch folder
os.Remove(filePath)
// This is how we define a goroutine in Googles Golang (more info in the
// handin about goroutines).
go func(data string) {
reader := csv.NewReader(strings.NewReader(data))
records, _ := reader.ReadAll()
for _, r := range records {
skis := new(Skis)
skis.Brand = r[0]
skis.Name = r[1]
skis.SkiType = r[2]
skis.Gender = r[3]
// Parsing a int from a string using the strconv package
skis.Length, _ = strconv.Atoi(r[4])
// Parsing a float64 from a string using the strconv package.
skis.Price, _ = strconv.ParseFloat(r[5], 64)
fmt.Printf("%v %v\n\tType: %v\n\tGender: %v\n"+
"\tLength: %vcm\nPrice: £%.2f\n-------------------\n", skis.Brand, skis.Name, skis.SkiType,
skis.Gender, skis.Length, skis.Price)
}
}(string(data))
}
}
}
// Skis is the structure of our product. In other languages this could
// be called a object.
type Skis struct {
Brand string
Name string
SkiType string
Gender string
Length int
Price float64
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment