Write a Golang program that monitors a directory for changes (file creation, modification, deletion) and logs these events to a PostgreSQL database along with timestamps and file metadata.
PLAINFORMAT
package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/fsnotify/fsnotify"
	_ "github.com/lib/pq"
)

const (
	DB_USER     = "your_db_user"
	DB_PASSWORD = "your_db_password"
	DB_NAME     = "your_db_name"
)

func main() {
	// Connect to the database
	dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
		DB_USER, DB_PASSWORD, DB_NAME)
	db, err := sql.Open("postgres", dbinfo)
	checkErr(err)
	defer db.Close()

	// Create table if not exists
	createTableQuery := `
	CREATE TABLE IF NOT EXISTS file_events (
		id SERIAL PRIMARY KEY,
		event_type TEXT NOT NULL,
		file_name TEXT NOT NULL,
		timestamp TIMESTAMP NOT NULL
	)`
	_, err = db.Exec(createTableQuery)
	checkErr(err)

	// Initialize fsnotify watcher
	watcher, err := fsnotify.NewWatcher()
	checkErr(err)
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				log.Println("event:", event)
				if event.Op&fsnotify.Write == fsnotify.Write {
					log.Println("modified file:", event.Name)
					insertEvent(db, "MODIFY", event.Name)
				} else if event.Op&fsnotify.Create == fsnotify.Create {
					log.Println("created file:", event.Name)
					insertEvent(db, "CREATE", event.Name)
				} else if event.Op&fsnotify.Remove == fsnotify.Remove {
					log.Println("deleted file:", event.Name)
					insertEvent(db, "DELETE", event.Name)
				}
			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	dirToWatch := "."
	if len(os.Args) > 1 {
		dirToWatch = os.Args[1]
	}

	err = watcher.Add(dirToWatch)
	checkErr(err)

	<-done
}

func insertEvent(db *sql.DB, eventType string, fileName string) {
	stmt, err := db.Prepare("INSERT INTO file_events(event_type, file_name, timestamp) VALUES($1, $2, $3)")
	checkErr(err)

	_, err = stmt.Exec(eventType, fileName, time.Now())
	checkErr(err)
}

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}