S
S
Sergio_Hunter2016-12-08 18:29:55
go
Sergio_Hunter, 2016-12-08 18:29:55

What is the correct way to use sort in Go?

Hello. Please tell me, I need to sort by date before uploading to csv. How do I use the sort package in my case. What exactly to use sort.String or sort.Sort and the Len, Less, and Swap methods? Thank you.

package main

import (
  "bytes"
  "compress/zlib"
  "database/sql"
  "encoding/csv"
  "encoding/json"
  "fmt"
  _ "github.com/go-sql-driver/mysql"
  "io/ioutil"
  "log"
  "os"
  "strconv"
)

type UserStatsData struct {
  Dates map[string]Info `json:"d"`
}

type Info struct {
  Date    string  `json:"-"`
  Gold    int     `json:"g"`
  Revenue float64 `json:"r"`
  H       []Info  `json:"h"`
}

func main() {
  var data []byte

  db, err := sql.Open("mysql", "name:[email protected](127.0.0.1:9011)/database")
  if err != nil {
    panic(err.Error())
  }
  defer db.Close()

  rows, err := db.Query(`SELECT data FROM user_stats ORDER BY created_at DESC LIMIT 1000`)
  if err != nil {
    log.Fatal(err)
  }
  defer rows.Close()

  file, err := os.Create("result.csv")
  if err != nil {
    fmt.Println(err)
  }
  defer file.Close()

  writer := csv.NewWriter(file)
  var record []string
  record = append(record, "Date")
  record = append(record, "Gold")
  record = append(record, "Revenue")
  writer.Write(record)

  var userStatsDataArr []UserStatsData
  for rows.Next() {
    err := rows.Scan(&data)
    if err != nil {
      log.Fatal(err)
    }

    var userStatsData UserStatsData
    err = json.Unmarshal(data, &userStatsData)
    if err != nil {
      r, err := zlib.NewReader(bytes.NewReader(data))
      if err != nil {
        log.Panicf("\nCannot read archive %v", err)
      }
      r.Close()
      data, _ = ioutil.ReadAll(r)

      err = json.Unmarshal(data, &userStatsData)
      if err != nil {
        panic(err.Error())
      }

    }

    userStatsDataArr = append(userStatsDataArr, userStatsData)

  }
  parsed := make(map[string]Info)
  for _, user := range userStatsDataArr {
    for k, v := range user.Dates {
      if item, ok := parsed[k]; ok {
        item.Gold += v.Gold
        item.Revenue += v.Revenue
        parsed[k] = item
      } else {
        parsed[k] = v
      }
      for _, val := range v.H {
        if item, ok := parsed[val.Date]; ok {
          item.Gold += val.Gold
          item.Revenue += val.Revenue
          parsed[val.Date] = item
        } else {
          parsed[k] = val
        }

      }

    }

  }

  for k, v := range parsed {
    var record []string
    record = append(record, k)
    record = append(record, strconv.Itoa(v.Gold))
    record = append(record, fmt.Sprintf("%.2f", v.Revenue))
    writer.Write(record)
  }

  writer.Flush()

}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question