Welcome back to our journey of building a password manager in Go! In this second installment, we'll explore the progress we've made since our initial commit. We've added new features, improved the code structure, and implemented testing. Let's dive in!
Evolving the Project Structure
One of the first changes you'll notice is the improved project structure. We've separated our code into multiple files and packages, following Go's best practices:
This function allows users to use flags like -n to exclude symbols and -c to copy the password to clipboard instead of displaying it.
Improved Password Generation Algorithm
We've refined our password generation function to handle the new customization options:
funcgeneratePassword(lengthint,noSymbolsbool)(string,error){const(uppercaseLetters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"lowercaseLetters="abcdefghijklmnopqrstuvwxyz"digits="0123456789"specialChars="!@#$%^&*()-_=+[]{}|;:'\",.<>/?")allChars:=uppercaseLetters+lowercaseLetters+digitsif!noSymbols{allChars+=specialChars}varpasswordstringfori:=0;i<length;i++{// Generate a random index to select a character from allCharsrandomIndex,err:=rand.Int(rand.Reader,big.NewInt(int64(len(allChars))))iferr!=nil{return"",err}// Append the randomly selected character to the passwordpassword+=string(allChars[randomIndex.Int64()])}returnpassword,nil}
This function now respects the noSymbols flag, allowing for more flexible password generation.
Implementing Tests
We've taken a significant step towards ensuring the reliability of our code by implementing tests. Here's a snippet from our test file:
funcTestPasswordLength(t*testing.T){password,err:=generatePassword(10,true)iferr!=nil{t.Errorf("Expected no error, got %v",err)}else{iflen(password)!=10{t.Errorf("Expected 10 character password, got %d",len(password))}}}funcTestSpecialCharacter10K(t*testing.T){splCharMissing:=0fori:=1;i<=10000;i++{password,err:=generatePassword(10,false)// ... (code to check for special characters)}ifsplCharMissing>0{t.Errorf("Special character was missing in %d / 10000 instances.",splCharMissing)}}
These tests check for correct password length and the inclusion of special characters. Interestingly, our special character test revealed an area for improvement: in 10,000 generated passwords, 234 didn't contain special characters. This gives us a clear direction for our next refinement.
What's Next?
While we've made significant progress, there's still room for improvement:
Refine the password generation algorithm to ensure consistent inclusion of special characters.
Implement password storage functionality.
Add encryption for stored passwords.
Develop search and retrieval features.
Stay tuned for the next part of our series, where we'll tackle these challenges and continue to evolve our password manager!
Remember, the full source code is available on GitHub. Feel free to clone, fork, and contribute to the project. Your feedback and contributions are always welcome!