Skip to content

Instantly share code, notes, and snippets.

@floydkots
Created June 4, 2018 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save floydkots/7358b34bb4b9783b8718653eaad9e028 to your computer and use it in GitHub Desktop.
Save floydkots/7358b34bb4b9783b8718653eaad9e028 to your computer and use it in GitHub Desktop.
Go asynchronous file watcher processing invoices saved as CSV files
package main
import (
"os"
"io/ioutil"
"time"
"encoding/csv"
"strings"
"strconv"
"fmt"
"runtime"
)
const watchedPath = "./source"
func main() {
runtime.GOMAXPROCS(4)
for {
d, _ := os.Open(watchedPath)
files, _ := d.Readdir(-1)
for _, fi := range files {
filePath := watchedPath + "/" + fi.Name()
f, _ := os.Open(filePath)
data, _ := ioutil.ReadAll(f)
f.Close()
os.Remove(filePath)
go func(data string) {
reader := csv.NewReader(strings.NewReader(data))
records, _ := reader.ReadAll()
for _, r := range records {
invoice := new(Invoice)
invoice.Number = r[0]
invoice.Amount, _ = strconv.ParseFloat(r[1], 64)
invoice.PurchaseOrderNumber, _ = strconv.Atoi(r[2])
unixTime, _ := strconv.ParseInt(r[3], 10, 64)
invoice.InvoiceDate = time.Unix(unixTime, 0)
fmt.Printf("Received invoice '%v' for $%.2f and submitted for processing\n",
invoice.Number, invoice.Amount)
}
} (string(data))
}
}
}
type Invoice struct {
Number string
Amount float64
PurchaseOrderNumber int
InvoiceDate time.Time
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment