Step 1: Creating the Go Module
Start by navigating to your workspace directory and creating a new directory for your module:go.mod file with content similar to:
The
go.mod file defines your module’s dependencies and version. Ensure that the module path is aligned with your repository.Step 2: Building the Encrypt Package
Next, create the directory for the encrypt package and add a new file namedalgorithm.go:
algorithm.go, begin by declaring the package:
Implementing the Encryption Function
We’ll implement a function that processes an input string by adding three to the ASCII value of each character. The function will:- Take a string as input.
- Iterate over every character.
- Shift the ASCII code by three.
- Append the modified character to an output string.
- Return the encrypted string.
Step 3: Setting Up the Main Application
Return to the root directory of your module to create the primary application file,main.go. This file will test the encryption function from the encrypt package.
Create main.go and add the following content:
encrypt package using its module path. The function encrypt.Nimbus("KodekLoud") is called to process the string. The parameter is passed directly without the need for the str: label, and the uppercase N in Nimbus makes it accessible outside its package.
Remember, functions that need to be accessible from other packages must start with an uppercase letter.
Step 4: Running Your Go Application
With everything set up, compile and run the application from the module’s root directory:"KodekLoud" has been shifted by three ASCII positions (e.g., K becomes N, O becomes R, etc.), which verifies that the encryption algorithm is functioning correctly.
Conclusion
In this lesson, you learned how to:- Create and initialize a Go module using
go mod init. - Organize module components into separate packages for encryption and decryption.
- Implement and export an encryption function by capitalizing its name.
- Utilize the exported function in a
main.gofile to run your application.