👨‍💻
Dokumentasi Golang (PT Phincon)
  • 🚀Dokumentasi Bootcamp (PT Phincon)
  • Command di Golang
  • Static Type di Golang
  • Variable and Constant
    • Variable daI Constant
    • Deklarasi Variabel
    • Iota (Auto Increment)
    • Blank Identifier (Variable Underscore)
    • Access Modifier (Public or Private)
  • Tipe Data Primitif
    • Integer dan Unsigned Integer
    • Float dan Complex
    • String
    • Boolean
  • Tipe Data Aggregate
    • Array
    • Struct
  • Tipe Data Reference
    • Slice
    • Map
    • Function in Golang
      • Function
      • Function vs Method
      • Function vs Procedure
      • Private vs Public Function
      • Function Init dan Main
      • Function dengan Return Multiple Value
      • Variadic Function
      • Function sebagai Parameter
      • Anonymous Function
      • Input Function dari CLI
      • Exercise (Function)
  • Default Value setiap Tipe Data
  • Type Declaration di Golang
    • Type Declaration
    • Type Declaration Built-In di Golang
  • Kebab Case, Camel Case, Snake Case & Pascal Case di Golang
  • Konversi Tipe Data
  • If-Else dan Switch
    • If Else
    • Switch
    • Exercise
  • Looping
    • Looping For
    • Looping for range
    • Infinite Looping
    • Penerapan Looping pada Sorting
  • Operator di Golang
    • Arithmetic Operator
    • Assignment Operator
    • Relational Operator
    • Logic Operator
  • Interface
  • Interface Kosong atau Any
  • Nil
  • Pointer
    • Pass By Value dan Pass By Reference
    • Pointer (Pass By Reference)
    • Operator Address (& dan *)
    • Default Value Pointer
    • Tricky Case
    • Pointer pada Parameter di Function
    • Pointer pada Method
  • Package
    • Fmt
    • Rand
    • Os
    • Strings
      • To Lower
      • Contains
      • Split
      • Trim
      • Atoi
      • Itoa
      • EqualFold
    • Random Generator
    • Time
      • Get Current Time By Location
      • Time Sleep
      • Time Since
      • Timer & After
      • AfterFunc
      • Ticker & Tick
  • Go dan JSON
    • JSON vs XML
    • Unmarshal vs Marshal
    • Marshal (Go Object -> JSON)
    • Unmarshal (JSON -> Go Object)
    • Streaming Decoder & Encoder
    • Tag
    • JSON Go Return Byte
  • Go dan CSV
    • Insert Data ke File CSV
    • Insert 1.000.000 Data ke File CSV
  • Goroutine
    • Concurrency vs Parrarel
    • Go Routine Sederhana
    • Go Routine vs Synchronous
    • Wait Group
    • Defer
    • Channel
    • Buffered Channel
    • Select Channel
    • Deadlock - All goroutines are asleep
    • Race Condition
    • Mutex (Mutual Exclusion)
    • RW Mutex vs Mutex
    • Once
    • Pool
    • Atomic
    • Go Max Procs
    • Exit
    • Exercise 1 : Go Routine + Context + Channel
    • Exercise 2 : Worker (Go Routine + Channel + Context)
    • Exercise 3 : Random Worker (Go Routine + Channel + Context)
    • Exercise : Implementasi Goroutine dan Channel pada File CSV
  • Go Context
    • Pengenalan Context
    • Context Background & TODO
    • Context With Value
    • Context WithDeadline dan Context WithTimeout
    • Context WithCancel dan Context Done
  • Pengenalan HTTP
  • Go Native HTTP
    • HTTP Server
    • HTTP Server Multi Handler
    • HTTP Server dengan Serve Mux
    • HTTP Response Writer
    • HTTP Test
    • Routing
    • Konsep Middleware
    • Middleware
    • Get Query Parameter
    • Get Path Parameter
    • Request JSON
    • Request Form
    • Get dan Set Header
    • Get dan Set Cookie
    • Redirect
    • Serve File
    • Upload File
    • Download File
    • Hit Endpoint dengan Curl di Terminal
  • Go Gin Framework
    • HTTP Server
    • Router
    • Middleware
    • Get Query Parameter
    • Get Path Parameter
    • Request JSON
    • Request Form
    • Get dan Set Header
    • Get dan Set Cookie
    • Redirect
    • Serve File
    • Upload File
    • Download File
  • Golang dan Database
    • Instalasi MySQL dengan Docker Desktop
    • Instalasi PostgreSQL dengan Docker
    • Basic SQL
    • SQL Join
    • SQL Relation
    • Golang Database Driver
    • Golang dan SQL
  • Go Unit Test
    • Method di Package Testing
    • Package Assert & Require
    • Running Sub Test
    • Table Test
    • Generate Coverage Unit Testing dalam Bentuk HTML
  • Sonar Qube dan Sonar Scanner
  • Logging
  • Golang dan Redis
  • Golang dan RabbitMQ
    • Instalasi RabbitMQ dengan Docker
    • Instalasi Package RabbitMQ di Golang
    • Publisher dan Consumer
    • Publisher dan Multi Consumer
    • Setting RabbitMQ (Durable, Auto Delete dan Ack)
  • Git Command
  • Git Clone dengan SSH
  • Anotasi dan Package di Java Spring Boot
Powered by GitBook
On this page
  1. Go dan CSV

Insert 1.000.000 Data ke File CSV

PreviousInsert Data ke File CSVNextGoroutine

Last updated 1 year ago

Berikut adalah contoh code penggunaan package "encoding/csv" untuk membuat file comment.csv dan insert 1.000.000 data ke file tersebut.

main.go
package main

import (
	"encoding/csv"
	"fmt"
	"log"
	"math/rand"
	"os"
	"sync"
	"time"
)

var wg sync.WaitGroup
var m sync.Mutex
var rw sync.RWMutex

type userComment struct {
	name    string
	comment string
}

func main() {
	start := time.Now()
	totalWorker := 3
	userCommentChannel := make(chan userComment, 100)

	// generate data
	sliceName := []string{"Adli", "Bagus", "Rafli", "Lutfi"}
	go func() {
		for i := 1; i <= 1000; i++ {
			userComment := userComment{
				name:    sliceName[rand.Intn(4)],
				comment: randomString(20),
			}
			userCommentChannel <- userComment
			if i == 1000000 {
				close(userCommentChannel)
			}
		}
	}()

	csvfile, err := os.Create("file/comment.csv")
	if err != nil {
		log.Panicln("Error create data :", err)
	}
	for i := 0; i < totalWorker; i++ {
		wg.Add(1)
		// index := i
		go func() {		
			csvwriter := csv.NewWriter(csvfile)
			for userComment := range userCommentChannel {
				var temp = []string{userComment.name, userComment.comment}
				m.Lock()
				if err := csvwriter.Write(temp); err != nil {
					log.Fatalln("Error writing data :", err)
				}
				m.Unlock()
				// fmt.Printf("worker-%d - %v\n", index+1, userComment)
			}
			defer csvwriter.Flush()
			wg.Done()
		}()
		wg.Wait()
	}

	defer func() {
		fmt.Println("Duration", time.Since(start).Seconds())
		if err := csvfile.Close(); err != nil {
			log.Panicln("Error closing file :", err)
		}
	}()

	log.Print("Start read")
	csvfile2, err := os.Open("file/comment.csv")
	if err != nil {
		log.Panicln("Error open data", err)
	}
	csvreader := csv.NewReader(csvfile2)
	ReadAllData(csvreader)
}

func randomString(length int) string {
	// randomizer := rand.New(rand.NewSource(time.Now().Unix()))
	letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

	b := make([]rune, length)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}

	return string(b)
}

func ReadAllData(csvreader *csv.Reader) {
	if data, err := csvreader.ReadAll(); err != nil {
		log.Fatalln("Error cant read data from csv :", err)
	} else{
		for i:=0; i<100; i++ {
			fmt.Println("Name :", data[i][0])
			fmt.Println("Comment :", data[i][1])
			fmt.Println()
		}
	}
}

File comment.csv akan ter-generate setelah code di atas di jalankan.