Posts

Showing posts from June, 2022

27. Go - Environment Files

Get the library to read/load environment variables from a .env file. https://github.com/joho/godotenv

26. Go - Timers and Tickers

Times are like channels. Timer execute once in the future. variable := time.NewTimer(2*time.Second) // creates a new timer < - variable.C // timer's channel. any code under timer will run when timer runs out. variable.Stop() // stops a timer Tickers execute once every interval. Example: package main import (     "fmt"     "time" ) func main() {     ticker := time.NewTicker(500 * time.Millisecond) // creates a ticker     done := make(chan bool) // creates a channel that takes bool     go func() {         for { // infinite loop             select {             case <-done: // if done chan receive true bool, then return                 return             case t := <-ticker.C: // if ticker chan gets a tick, then print                 fmt.Println("Tick at", t)             }         }     }()     time.Sleep(1600 * time.Millisecond) // stops program at 1600 millisecond     ticker.Stop() // stops ticker     done <- true // send done chan a true boo

25. Go - Wait Sync

Wait provides a method to prevent application from closing prematurely while using goroutines. var wg sync.WaitGroup // creates a sync waitgroup wg.Add() // add how many waitgroups there are. takes in an int defer wg.Done() // finishes a waitgroup. it is deferred so will be called when function finishes. wg.Done() // also works by itself without defer wg.Wait() // a method that waits for the waitgroups to finish. Example: package main import ( "fmt" "sync" ) var wg sync.WaitGroup func main() { wg.Add(2) go count() go count() wg.Wait() } func count() { defer wg.Done() for i := 0; i < 10; i++ { fmt.Println(i) } }