As a frontend developer with years of experience in JavaScript, I decided it was time for a new challenge. This year, I chose to dive into the world of Golang. To test my skills and add a practical tool to my arsenal, I created File Organizer—a command-line tool designed to bring order to the chaos of file management. ?
Imagine you’ve just finished a big project, and your directory is now a chaotic mess of images, audio files, videos, and documents. It’s a bit like having a beautifully decorated house but with all the furniture thrown haphazardly. ? I’ve been there, and it’s no fun at all!
In this first part of our adventure, we’ll focus on the basics of file operations in Go, learning how to sort and organize files into neat folders based on their extensions. Ready to dive in? Let’s go!
Ever felt overwhelmed by a cluttered directory? You’ve got a jumble of image files, audio clips, videos, and documents all mixed together. Sorting through them manually can feel like searching for a needle in a haystack. ?
We’re going to build a tool that transforms this mess into an organized paradise! Our File Organizer will automatically sort files into folders based on their type—images here, audio there, videos over here, and documents neatly tucked away. ?
Here’s how we crafted this file-sorting marvel:
Our journey begins by finding out where our files are hiding:
dir := os.Args[1]
This line is like asking our program, “Hey, where’s the directory full of our files?” ?
Next, we need to peek inside that directory to see what’s in there:
files, err := os.ReadDir(dir) var filesToOrder []string if err != nil { log.Fatal(err) }
We read the contents of the directory, and if something goes wrong—like the directory doesn’t exist—our program will stop and tell us. ?
Now, we need to focus on the files and leave directories behind:
for _, file := range files { if file.IsDir() { continue } filesToOrder = append(filesToOrder, file.Name()) }
Here, we loop through each item. If it’s a directory, we skip it. If it’s a file, we add it to our list of files to be organized. ?️
With our list of files ready, it’s time to sort them into their new homes:
for _, fileName := range filesToOrder { fileType := determineType(fileName) switch fileType { case IMAGE_TYPE: _ = moveToFolder(filepath.Join(dir, fileName), filepath.Join(dir, "images")) case AUDIO_TYPE: _ = moveToFolder(filepath.Join(dir, fileName), filepath.Join(dir, "audio")) case VIDEO_TYPE: _ = moveToFolder(filepath.Join(dir, fileName), filepath.Join(dir, "videos")) case DOCUMENT_TYPE: _ = moveToFolder(filepath.Join(dir, fileName), filepath.Join(dir, "documents")) default: fmt.Printf("Unsupported file type: %s\n", fileName) } }
We loop through each file, figure out what type it is, and send it to the right folder. If we come across a file type we don’t recognize, we let you know. ?
To figure out what kind of file we’re dealing with, we use this handy function:
func determineType(file string) int { for key, value := range ALLOWED_TYPES { for _, ext := range value { if strings.HasSuffix(file, ext) { return key } } } return UNDEFINED_TYPE }
It checks the file’s extension against our list and tells us whether it’s an image, audio, video, or document. ?️♂️
Finally, we move each file to its new folder:
func moveToFolder(src, dest string) error { if _, err := os.Stat(dest); os.IsNotExist(err) { err := os.Mkdir(dest, 0777) if err != nil { return err } } fileName := filepath.Base(src) err := os.Rename(src, filepath.Join(dest, fileName)) if err != nil { return err } return nil }
We check if the destination folder exists and create it if needed. Then we move the file from its old spot to the new one. ?
For files that don’t fit into any category, we let you know:
default: fmt.Printf("Unsupported file type: %s\n", fileName)
We print a message for unsupported file types so you know exactly what didn’t get organized. ?
And that’s a wrap on Part 1! ? We’ve successfully tackled the basics of file operations in Go and sorted our files into neat categories. But here’s a thought—what if you want to add a new category, like “Archives” or “Projects”? Right now, you’d have to dive into the map and tweak the code. ?
This approach is great if you’re the only one using the tool. But imagine sharing this awesome tool with friends who might not know Go. ?️ You’d want to make it easy for everyone to customize without needing to understand the code.
Fear not! In the next part, we’ll dive even deeper into the File Organizer tool and uncover advanced features that address these challenges. ? We’ll make it so that anyone can tweak and enhance the tool without writing a single line of Go code. Intrigued? Stay tuned!
Got any questions or need more details? Drop them below, and let’s chat! ?
The above is the detailed content of My First Project using Golang. For more information, please follow other related articles on the PHP Chinese website!