In Go, you can use the standard library package encoding/csv [docs] to write data to a CSV file. Below is a example that shows you how you can write a slice of user-data relasted strings to a CSV file.
The code creates a new file called users.csv and writes a slice of records to it. Finally, the Flush method is used to flush any buffered data to the underlying io.Writer, which is the file.
packagemainimport("encoding/csv""os""fmt")funcmain(){// Define the data
records:=[][]string{{"John","Doe","35"},{"Jane","Doe","29"},{"Jim","Smith","41"},}filename:="users.csv"// Write it to CSV
err:=WriteToCsv(records,filename)iferr!=nil{panic(err)}fmt.Println("Created file:",filename)}// WriteToCsv accepts a slice of strings to write to a csv file.
funcWriteToCsv(records[][]string,filenamestring)error{file,err:=os.Create(filename)iferr!=nil{returnerr}deferfile.Close()writer:=csv.NewWriter(file)deferwriter.Flush()for_,record:=rangerecords{err:=writer.Write(record)iferr!=nil{returnerr}}returnnil}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.
MD5 Encoding in Golang
–
You can use the crypto/md5 [docs] package in Go to perform MD5 encoding on a string. We have an example function below, it will take your string and write it as a hash. Then convert that binary back into a hexadecimal string using Sprintf.
Note: There are more modern approaches than md5 these days - and it isn’t recommended for many things, but definately not password hashing.
Here’s an example of how to use it:
Get Status Code from HTTP Request
–
We won’t go into too much detail about HTTP status codes themselves, but in this post we will talk about how to use the status code after making a request, how to check them as a range and how to print them as text. This is often important so we can check if something was successful or failed.
You can always get this data if you have a net/http/Response type (spec).
Download a File from a URL
–
This post shows how you can download a file in Go from a URL. We use the std lib (standard library) http.Get() [docs] and io.Copy() [docs] functions to help us with this. This function should be efficient as it will stream the data into the file, as opposed to downloading it all into memory, then to file.
The file will be saved in the same directory as your program.
We also show an alternative below if you want to take the filename from the URL.