Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "bufio"
- "encoding/csv"
- "encoding/json"
- "flag"
- "fmt"
- "io"
- "io/ioutil"
- "log"
- "os"
- "strconv"
- "strings"
- _ "github.com/go-sql-driver/mysql" // mysql driver
- "github.com/jmoiron/sqlx"
- "github.com/tokopedia/goal/common/api"
- )
- var baseDir = flag.String("database_dir", "./files/databases/", "SQL files directory")
- var host = flag.String("h", "127.0.0.1", "Database host")
- var port = flag.String("P", "3306", "Database port")
- var user = flag.String("u", "root", "Database user")
- var pass = flag.String("p", "root", "Database password")
- var dbName = flag.String("db", "tkp_goal", "Database name")
- func main() {
- //os.Exit(Main())
- os.Exit(ReadFileCSV("data_reconcile.csv"))
- }
- func executeSQL(db *sqlx.DB, fileName string) error {
- content, err := ioutil.ReadFile(fmt.Sprintf("%s%s", *baseDir, fileName))
- if err != nil {
- return err
- }
- println(" > Executing file :", fileName)
- queries := strings.Split(string(content), ";")
- for _, query := range queries {
- if strings.TrimSpace(query) != "" {
- println(">", query)
- _, err := db.Exec(query)
- if err != nil {
- return err
- }
- }
- }
- return nil
- }
- func Main() int {
- flag.Parse()
- connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true&loc=Local", *user, *pass, *host, *port, *dbName)
- db, err := sqlx.Connect("mysql", connectionString)
- if err != nil {
- log.Fatalln(err)
- }
- err = executeSQL(db, "000_init.sql")
- if err != nil {
- log.Fatalln(err)
- }
- files, err := ioutil.ReadDir(*baseDir)
- if err != nil {
- log.Fatalln(err)
- }
- for _, file := range files {
- fileName := file.Name()
- if fileName == "000_init.sql" || !strings.Contains(fileName, "sql") {
- continue
- }
- err := executeSQL(db, fileName)
- if err != nil {
- log.Fatalln(fileName, " : ", err.Error())
- }
- }
- return 0
- }
- type TransactionSpr struct {
- ClientID string `json:"client_id"`
- UserID int64 `json:"user_id"`
- MerchantOrderID string `json:"merchant_order_id"`
- CashAmount int64 `json:"cash_amount"`
- PointAmount int64 `json:"point_amount"`
- NoteToPayer string `json:"note_to_payer"`
- IdempotencyKey string `json:"idempotency_key"`
- Currency string `json:"currency"`
- }
- func ReadFileCSV(filePath string) int {
- csvFile, _ := os.Open(filePath)
- reader := csv.NewReader(bufio.NewReader(csvFile))
- var transactionSpr TransactionSpr
- var userID, cashAmount, pointAmount int64
- if _, err := reader.Read(); err != nil { //read header
- log.Fatal(err)
- }
- for {
- line, error := reader.Read()
- if error == io.EOF {
- break
- } else if error != nil {
- log.Fatal(error)
- }
- if userID, error = strconv.ParseInt(line[0], 0, 64); error != nil {
- log.Fatal(error)
- }
- if cashAmount, error = strconv.ParseInt(line[2], 0, 64); error != nil {
- log.Fatal(error)
- }
- if pointAmount, error = strconv.ParseInt(line[2], 0, 64); error != nil {
- log.Fatal(error)
- }
- transactionSpr = TransactionSpr{
- ClientID: "G6T6CVTS8bMY",
- IdempotencyKey: "abcsd",
- Currency: "IDR",
- UserID: userID,
- MerchantOrderID: line[1],
- CashAmount: cashAmount,
- PointAmount: pointAmount,
- NoteToPayer: line[4],
- }
- error = doPost(transactionSpr)
- if error != nil {
- log.Printf("got error : %+v", error)
- }
- }
- return 0
- // transactionJSON, _ := json.Marshal(transactionSpr)
- // fmt.Println(string(transactionJSON))
- }
- func doPost(data TransactionSpr) error {
- reqBody, err := json.Marshal(data)
- loggerType := "recon_spring"
- if err != nil {
- log.Println("[%s] Failed to marshal json when doPostRequest : %+v ", loggerType, data)
- return fmt.Errorf("Failed to marshal json when doPostRequest")
- }
- log.Println("marshal data : %s", string(reqBody))
- // url := "https://goalapi-staging.tokopedia.com/api/v1/payment" //staging
- // url := "https://goal.tokopedia.com/api/v1/payment" //production
- url := "https://localhost:9001/api/v1/payment" //local
- request := api.HTTPAPI{
- Method: "POST",
- URL: url,
- Body: reqBody,
- Headers: api.HeaderOptions{
- "Content-Type": "application/json",
- "Tkpd-User-ID": strconv.FormatInt(data.UserID, 10),
- },
- }
- fmt.Println("======= DO REQUEST =============")
- resp, err := api.DoRequest(request)
- if err != nil {
- return err
- }
- fmt.Println("========DEFER ========")
- defer resp.Body.Close()
- //FIXME: change HTTP code 200 to constant
- if resp.StatusCode != 200 {
- log.Println("[%s] Bad request when hit goal api, request : %+v ", loggerType, request)
- return fmt.Errorf("Bad request when hit goal api")
- }
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- log.Println("[%s]Failed to read response body. Error=", loggerType, err.Error())
- return fmt.Errorf("Failed to read response body, Error: %s", err.Error())
- }
- var respData interface{}
- err = json.Unmarshal(body, &respData)
- if err != nil {
- log.Println("[%s]Failed to unmarshal response body. Error=", loggerType, err.Error())
- return fmt.Errorf("Failed to unmarshal response body, Error: %s", err.Error())
- }
- return nil
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement