Skip to content

Instantly share code, notes, and snippets.

@ahmagdy
Last active Feb 14, 2021
Embed
What would you like to do?
File Locking In Go
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sync"
"time"
)
var wg sync.WaitGroup
func main() {
wg.Add(2)
go func() {
if err := readerTask("/tmp/test"); err != nil {
fmt.Println(err.Error())
}
}()
go func() {
if err := updateTask("/tmp/test"); err != nil {
fmt.Println(err.Error())
}
}()
wg.Wait()
}
func updateTask(dirName string) error {
defer wg.Done()
dirEntries, err := ioutil.ReadDir(dirName)
if err != nil {
return fmt.Errorf("failed to read dir: %w", err)
}
for _, dirEntry := range dirEntries {
fmt.Println("== " + dirEntry.Name())
srcSubDirName := filepath.Join(dirName, dirEntry.Name())
if dirEntry.IsDir() {
destSubDirName := filepath.Join(dirName, dirEntry.Name()+"_v2")
fmt.Printf("== Moving %s to %s\n", srcSubDirName, destSubDirName)
if err := os.Rename(srcSubDirName, destSubDirName); err != nil {
return err
}
continue
}
if dirEntry.Name() == "c.d" {
if err := os.Remove(srcSubDirName); err != nil {
return nil
}
}
}
return nil
}
func readerTask(dirName string) error {
defer wg.Done()
return read(dirName)
}
func read(dirName string) error {
dirEntries, err := ioutil.ReadDir(dirName)
if err != nil {
return fmt.Errorf("failed to read dir: %w", err)
}
for _, dirEntry := range dirEntries {
filePath := filepath.Join(dirName, dirEntry.Name())
fmt.Println("-- Reading " + filePath)
if dirEntry.IsDir() {
read(filePath)
continue
}
f, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
fmt.Println(string(f))
time.Sleep(1 * time.Second)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment