Go blueprints: code for common tasks
These code examples are intended to help you quickly solve some common everyday tasks in Go. There are also a few oddities that may be nice to have when writing more exotic code.
Access environment variables
Use the Setenv, Getenv, Unsetenv and Environ functions to read and write environment variables.
Access private fields with reflection
Code to read unexported fields in a struct using reflection in Go.
Bitmasks and flags
How to use a bitmask to represent a set of flags in Go.
Check if a number is prime
To check if a number is prime in Go use the ProbablyPrime function from package math/big.
Command-line application (CLI)
Code for a basic command-line (CLI) application in Go.
You can access command-line arguments passed to a Go program through the os.Args variable.
Compute absolute values
Code to compute the absolute value of an int or float in Go.
Compute min and max
Code to compute the minimum and maximum of integer and floating point numeric values in Go.
Convert byte size to human readable format
Code to format 1000 to 1 kB, 1000000 to 1 MB etc. in Go. The code supports both SI and IEC formats.
Create a custom error
How to handle an error and how to create custom error types in Go.
Create a new image
To generate a png image programmatically in Go use the image, image/color, and image/png packages.
Enumeration with string representation
How to declare enums and give them a string representation in Go.
Find build version
Use runtime.Version to find the current Go build version.
Generate all permutations
Code to generate all permutations of a slice or string in Go.
Code for computing hash checksums (MD5, SHA-1, SHA-256) of strings, byte slices and files.
How to sort in Go
Code to sort any type of data in Go using the sort package. All algorithms in the package perform O(n log n) comparisons in the worst case.
HTTP server example
Example code for implementing a basic HTTP web server in Go with client requests and responses.
Implement a FIFO queue
Code to implement a FIFO queue in Go.
Implement a set
Code to implement a hashset in Go.
Implement a stack (LIFO)
Code to implement a stack or LIFO queue in Go.
Code to write iterators and generators in Go.
Maximum value of an int
Code to compute the max and min values of an int and uint in Go.
Round float to 2 decimal places
Code to round a float to a string/float with 2 decimal places in Go.
Round float to integer value
Code to round a float64 to the nearest integer in Go.
Table-driven unit tests
How to write a table-driven unit test for binary search in Go.
See the String handling cheat sheet for all about basic string manipulation in Go.
Share this page: Email | Twitter | Facebook | Reddit