Skip to content

Instantly share code, notes, and snippets.

@Franco-Poveda
Created September 16, 2017 00:34
Show Gist options
  • Save Franco-Poveda/e12ab214cc8bf4d6e831642659432b4a to your computer and use it in GitHub Desktop.
Save Franco-Poveda/e12ab214cc8bf4d6e831642659432b4a to your computer and use it in GitHub Desktop.
paid vaucher files chewer
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"os"
"strings"
"github.com/Jeffail/gabs"
"github.com/streadway/amqp"
)
type Configuration struct {
ValidCommerceIds []string
AMQPuri []string
}
func main() {
config, _ := os.Open(os.Args[1])
decoder := json.NewDecoder(config)
configuration := Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
fmt.Println("error:", err)
}
file, err := os.Open(os.Args[2])
if err != nil {
log.Fatal(err)
}
defer file.Close()
fileScanner := bufio.NewScanner(file)
lineCount := 0
for fileScanner.Scan() {
line := strings.Fields(fileScanner.Text())
if stringInArray(line[0], configuration.ValidCommerceIds) {
lineCount++
}
}
fmt.Println(lineCount)
conn, err := amqp.Dial(configuration.AMQPuri[0])
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
q, err := ch.QueueDeclare(
"cupon", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
file2, err := os.Open(os.Args[2])
if err != nil {
log.Fatal(err)
}
defer file2.Close()
scanner := bufio.NewScanner(file2)
scanner.Scan()
headers := strings.Fields(scanner.Text())
current := 0
for scanner.Scan() {
entry := strings.Fields(scanner.Text())
if stringInArray(entry[0], configuration.ValidCommerceIds) {
if len(entry[9]) < 6 {
entry[9] = PadLeft(entry[9], "0", 6)
//fmt.Println(entry[9], " : ", padded)
}
jsonObj := gabs.New()
for i, v := range entry {
jsonObj.Set(v, headers[i])
}
current++
jsonObj.Set(lineCount, "total")
jsonObj.Set(current, "seq")
//Publicamos el mensaje:
body := jsonObj.String()
err = ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})
fmt.Println(current)
failOnError(err, "Failed to publish a message")
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
func stringInArray(str string, list []string) bool {
for _, v := range list {
if v == str {
return true
}
}
return false
}
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
panic(fmt.Sprintf("%s: %s", msg, err))
}
}
func PadLeft(str, pad string, lenght int) string {
for {
str = pad + str
if len(str) >= lenght {
return str[0:lenght]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment