Advertisement
Guest User

Untitled

a guest
Apr 14th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.11 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "bufio"
  5. "encoding/csv"
  6. "encoding/json"
  7. "flag"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "log"
  12. "os"
  13. "strconv"
  14. "strings"
  15.  
  16. _ "github.com/go-sql-driver/mysql" // mysql driver
  17. "github.com/jmoiron/sqlx"
  18. "github.com/tokopedia/goal/common/api"
  19. )
  20.  
  21. var baseDir = flag.String("database_dir", "./files/databases/", "SQL files directory")
  22. var host = flag.String("h", "127.0.0.1", "Database host")
  23. var port = flag.String("P", "3306", "Database port")
  24. var user = flag.String("u", "root", "Database user")
  25. var pass = flag.String("p", "root", "Database password")
  26. var dbName = flag.String("db", "tkp_goal", "Database name")
  27.  
  28. func main() {
  29. //os.Exit(Main())
  30. os.Exit(ReadFileCSV("data_reconcile.csv"))
  31. }
  32.  
  33. func executeSQL(db *sqlx.DB, fileName string) error {
  34. content, err := ioutil.ReadFile(fmt.Sprintf("%s%s", *baseDir, fileName))
  35. if err != nil {
  36. return err
  37. }
  38. println(" > Executing file :", fileName)
  39.  
  40. queries := strings.Split(string(content), ";")
  41. for _, query := range queries {
  42. if strings.TrimSpace(query) != "" {
  43. println(">", query)
  44. _, err := db.Exec(query)
  45. if err != nil {
  46. return err
  47. }
  48. }
  49. }
  50.  
  51. return nil
  52. }
  53.  
  54. func Main() int {
  55. flag.Parse()
  56.  
  57. connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true&loc=Local", *user, *pass, *host, *port, *dbName)
  58. db, err := sqlx.Connect("mysql", connectionString)
  59. if err != nil {
  60. log.Fatalln(err)
  61. }
  62.  
  63. err = executeSQL(db, "000_init.sql")
  64. if err != nil {
  65. log.Fatalln(err)
  66. }
  67.  
  68. files, err := ioutil.ReadDir(*baseDir)
  69. if err != nil {
  70. log.Fatalln(err)
  71. }
  72.  
  73. for _, file := range files {
  74. fileName := file.Name()
  75. if fileName == "000_init.sql" || !strings.Contains(fileName, "sql") {
  76. continue
  77. }
  78. err := executeSQL(db, fileName)
  79. if err != nil {
  80. log.Fatalln(fileName, " : ", err.Error())
  81. }
  82. }
  83.  
  84. return 0
  85. }
  86.  
  87. type TransactionSpr struct {
  88. ClientID string `json:"client_id"`
  89. UserID int64 `json:"user_id"`
  90. MerchantOrderID string `json:"merchant_order_id"`
  91. CashAmount int64 `json:"cash_amount"`
  92. PointAmount int64 `json:"point_amount"`
  93. NoteToPayer string `json:"note_to_payer"`
  94. IdempotencyKey string `json:"idempotency_key"`
  95. Currency string `json:"currency"`
  96. }
  97.  
  98. func ReadFileCSV(filePath string) int {
  99. csvFile, _ := os.Open(filePath)
  100. reader := csv.NewReader(bufio.NewReader(csvFile))
  101. var transactionSpr TransactionSpr
  102. var userID, cashAmount, pointAmount int64
  103. if _, err := reader.Read(); err != nil { //read header
  104. log.Fatal(err)
  105. }
  106.  
  107. for {
  108.  
  109. line, error := reader.Read()
  110. if error == io.EOF {
  111. break
  112. } else if error != nil {
  113. log.Fatal(error)
  114. }
  115.  
  116. if userID, error = strconv.ParseInt(line[0], 0, 64); error != nil {
  117. log.Fatal(error)
  118. }
  119.  
  120. if cashAmount, error = strconv.ParseInt(line[2], 0, 64); error != nil {
  121. log.Fatal(error)
  122. }
  123.  
  124. if pointAmount, error = strconv.ParseInt(line[2], 0, 64); error != nil {
  125. log.Fatal(error)
  126. }
  127.  
  128. transactionSpr = TransactionSpr{
  129. ClientID: "G6T6CVTS8bMY",
  130. IdempotencyKey: "abcsd",
  131. Currency: "IDR",
  132. UserID: userID,
  133. MerchantOrderID: line[1],
  134. CashAmount: cashAmount,
  135. PointAmount: pointAmount,
  136. NoteToPayer: line[4],
  137. }
  138. error = doPost(transactionSpr)
  139. if error != nil {
  140. log.Printf("got error : %+v", error)
  141. }
  142.  
  143. }
  144.  
  145. return 0
  146. // transactionJSON, _ := json.Marshal(transactionSpr)
  147. // fmt.Println(string(transactionJSON))
  148. }
  149.  
  150. func doPost(data TransactionSpr) error {
  151. reqBody, err := json.Marshal(data)
  152.  
  153. loggerType := "recon_spring"
  154. if err != nil {
  155. log.Println("[%s] Failed to marshal json when doPostRequest : %+v ", loggerType, data)
  156. return fmt.Errorf("Failed to marshal json when doPostRequest")
  157. }
  158.  
  159. log.Println("marshal data : %s", string(reqBody))
  160.  
  161. // url := "https://goalapi-staging.tokopedia.com/api/v1/payment" //staging
  162. // url := "https://goal.tokopedia.com/api/v1/payment" //production
  163.  
  164. url := "https://localhost:9001/api/v1/payment" //local
  165. request := api.HTTPAPI{
  166. Method: "POST",
  167. URL: url,
  168. Body: reqBody,
  169. Headers: api.HeaderOptions{
  170. "Content-Type": "application/json",
  171. "Tkpd-User-ID": strconv.FormatInt(data.UserID, 10),
  172. },
  173. }
  174. fmt.Println("======= DO REQUEST =============")
  175. resp, err := api.DoRequest(request)
  176.  
  177. if err != nil {
  178. return err
  179. }
  180. fmt.Println("========DEFER ========")
  181. defer resp.Body.Close()
  182.  
  183. //FIXME: change HTTP code 200 to constant
  184. if resp.StatusCode != 200 {
  185. log.Println("[%s] Bad request when hit goal api, request : %+v ", loggerType, request)
  186. return fmt.Errorf("Bad request when hit goal api")
  187. }
  188.  
  189. body, err := ioutil.ReadAll(resp.Body)
  190. if err != nil {
  191. log.Println("[%s]Failed to read response body. Error=", loggerType, err.Error())
  192. return fmt.Errorf("Failed to read response body, Error: %s", err.Error())
  193. }
  194. var respData interface{}
  195.  
  196. err = json.Unmarshal(body, &respData)
  197. if err != nil {
  198. log.Println("[%s]Failed to unmarshal response body. Error=", loggerType, err.Error())
  199. return fmt.Errorf("Failed to unmarshal response body, Error: %s", err.Error())
  200.  
  201. }
  202.  
  203. return nil
  204. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement