Foreword: The first section answers the original question (encode array to Base64). If you just want individual string fields to appear as Base64 strings in the output, see the 2nd section.


Encoding a []string into Base64 format

Base64 is an encoding, a function used to convert an arbitrary sequence of bytes to a text using a small, well defined set of characters.

So you have to decide / come up with a way to convert your []string array or slice to a sequence of bytes.

An easy and convenient way is to convert your []string to JSON text which will also take care of escaping strings having a quotation mark " for example. The result string can be easily encoded using the method you described:

genre := []string{"Pop", "Rock", "Dance", "Opera", "Techno", "Hiphop", "Jazz", "Reggae"}

data, _ := json.Marshal(&genre)
fmt.Println(string(data))
sEnc := base64.StdEncoding.EncodeToString(data)
fmt.Println(sEnc)

Output (try it on the Go Playground):

["Pop","Rock","Dance","Opera","Techno","Hiphop","Jazz","Reggae"]
WyJQb3AiLCJSb2NrIiwiRGFuY2UiLCJPcGVyYSIsIlRlY2hubyIsIkhpcGhvcCIsIkphenoiLCJSZWdnYWUiXQ==

Decoding

Having such Base64 result, you can decode it like this:

data2, err := base64.StdEncoding.DecodeString(sEnc)
if err != nil {
    panic(err)
}
var genre2 []string
if err = json.Unmarshal(data2, &genre2); err != nil {
    panic(err)
}
fmt.Println(genre2)

Output:

[Pop Rock Dance Opera Techno Hiphop Jazz Reggae]

Notes:

Of course you may choose any other transformations to convert []string to a byte sequence. You could convert it to XML, or using the encoding/binary or anything else. I chose JSON because it is a one-liner, compact, fast, and is supported in almost every programming language, so it won't be a problem if another program has to decode it.

Making individual string fields to appear as Base64

You can do this by implementing the Marshaler interface on the type (or enclosing struct) like this:

func (g *Genre) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
    g2 := *g
    g2.Title = base64.StdEncoding.EncodeToString([]byte(g.Title))
    return e.EncodeElement(g2, start)
}

Basically what this does is creates a copy of Genre, changes the value of the Title field (of the copy) to the Base64 representation of its original value and encodes this copy.

Output (partial), try it on the Go Playground:

<GenreArray>
    <item>
        <genre>UG9w</genre>
    </item>
    <item>
        <genre>Um9jaw==</genre>
    </item>
</GenreArray>
Answer from icza on Stack Overflow
๐ŸŒ
Go by Example
gobyexample.com โ€บ base64-encoding
Go by Example: Base64 Encoding
Go provides built-in support for base64 encoding/decoding ยท This syntax imports the encoding/base64 package with the b64 name instead of the default base64. Itโ€™ll save us some space below
Top answer
1 of 1
4

Foreword: The first section answers the original question (encode array to Base64). If you just want individual string fields to appear as Base64 strings in the output, see the 2nd section.


Encoding a []string into Base64 format

Base64 is an encoding, a function used to convert an arbitrary sequence of bytes to a text using a small, well defined set of characters.

So you have to decide / come up with a way to convert your []string array or slice to a sequence of bytes.

An easy and convenient way is to convert your []string to JSON text which will also take care of escaping strings having a quotation mark " for example. The result string can be easily encoded using the method you described:

genre := []string{"Pop", "Rock", "Dance", "Opera", "Techno", "Hiphop", "Jazz", "Reggae"}

data, _ := json.Marshal(&genre)
fmt.Println(string(data))
sEnc := base64.StdEncoding.EncodeToString(data)
fmt.Println(sEnc)

Output (try it on the Go Playground):

["Pop","Rock","Dance","Opera","Techno","Hiphop","Jazz","Reggae"]
WyJQb3AiLCJSb2NrIiwiRGFuY2UiLCJPcGVyYSIsIlRlY2hubyIsIkhpcGhvcCIsIkphenoiLCJSZWdnYWUiXQ==

Decoding

Having such Base64 result, you can decode it like this:

data2, err := base64.StdEncoding.DecodeString(sEnc)
if err != nil {
    panic(err)
}
var genre2 []string
if err = json.Unmarshal(data2, &genre2); err != nil {
    panic(err)
}
fmt.Println(genre2)

Output:

[Pop Rock Dance Opera Techno Hiphop Jazz Reggae]

Notes:

Of course you may choose any other transformations to convert []string to a byte sequence. You could convert it to XML, or using the encoding/binary or anything else. I chose JSON because it is a one-liner, compact, fast, and is supported in almost every programming language, so it won't be a problem if another program has to decode it.

Making individual string fields to appear as Base64

You can do this by implementing the Marshaler interface on the type (or enclosing struct) like this:

func (g *Genre) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
    g2 := *g
    g2.Title = base64.StdEncoding.EncodeToString([]byte(g.Title))
    return e.EncodeElement(g2, start)
}

Basically what this does is creates a copy of Genre, changes the value of the Title field (of the copy) to the Base64 representation of its original value and encodes this copy.

Output (partial), try it on the Go Playground:

<GenreArray>
    <item>
        <genre>UG9w</genre>
    </item>
    <item>
        <genre>Um9jaw==</genre>
    </item>
</GenreArray>
Discussions

Encode []byte as base64 string (to be consistent with stdlib JSON)
The standard library JSON module automatically converts any []byte struct members to base64 encoded strings when marshalling (see https://golang.org/pkg/encoding/json/#Marshal). The YAML library do... More on github.com
๐ŸŒ github.com
3
December 20, 2016
Convert data to base64 encode in go - Stack Overflow
So just apply EncodeToString to ... to []byte suitable for encoding. 2015-06-11T09:00:09.283Z+00:00 ... Save this answer. ... Show activity on this post. You can customise the output of print functions by providing a String() method for your type. Either for the whole Genre or just for the name variable. ... package main import ( "encoding/base64" "fmt" ) type ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Explain why []byte is base64 encoded when marshalled to json?

Base64 is the most widely used text representation of binary data.

More on reddit.com
๐ŸŒ r/golang
6
4
November 21, 2019
Is it a good idea to convert images into base64 string and save them in database?
You will get many people saying don't because if not implemented well it can bite ya. Don't be concerned about "optimal", tell yourself "good enough" and "don't let perfect be the enemy of good". But I have done this for several projects (enterprise, mission critical systems) and it works just fine. From the developer standpoint I love it. When I yank the "byte array" from the DB I can just pass it right to the client as-is, just adding on the mime type, super simple. Right now I have a system that stores photos of students at a university and we serve those out with an API. All done in C# and SQL Server. We have probably 50,000 photos and it is lighting fast. That being said I have also stored files in S3 and just stored the name in the DB. I will usually rename the file so S3 stores it efficiently. I like things like s3 better than a file system since you can dedicate a bucket just to this and some sysadmin won't go mucking around. I agree with you on storing the unstructured binary data along with your structured data for simplicity. I had a project once that wrote images to a filesystem. Years later older images were lost due to some file system cleanup process. Over my 25 years programming I have found you cannot guess where the issues will be. Don't optimize until you measure it. If you can build a proof of concept then hammer it, do it. Write a script that inserts and reads images and loop it for a few hours. See what happens. Also if you implement something and a few years later it starts to falter, then refactor. But you need to monitor! This is another place where people get bit, they do something like this and just let it run in a corner until it "just dies for no reason" one day. You or someone needs to care and feed for it. I am going to assume on-prem Microsoft SQL Server, your usage may vary. Use "VARBINARY(MAX)" for the field type https://docs.microsoft.com/en-us/sql/t-sql/data-types/binary-and-varbinary-transact-sql?view=sql-server-ver15 Put it in a table by itself with an id to look it up. Store filename, and filetype(mime-type) too if needed. Slap an index on the id, reference that id in other tables. Critical: Put the table in its own filegroup separate from the other tables. This will allow for faster restores since you can restore the primary filegroup and get your DB back online ASAP, then as it is up and running restore the filegroup with the images. So instead of the whole DB being down for hours, it is up in minutes with only the images being unavailable for hours. https://docs.microsoft.com/en-us/sql/relational-databases/databases/database-files-and-filegroups?view=sql-server-ver15 As with all DBs the filegroups should not be on the system (C) drive, maybe even put the images table filegroup on its own drive with nothing else. Do set a limit on the incoming filesize in your code. Someone could send in a few Blu-ray ISOs and cripple your system. In .NET code you store the image data in a byte array "byte[] " variable. That byte array is what is stored in the varbinary(max) DB field. It is easy to convert the incoming image/file to byte[], just google around for that there are many easy to do it. Design and implement a cleanup process and purge old unneeded records. No one ever seems to do this and the data grows forever until the system is retired/migrated. For small DBs it's not a problem but for this you must go back to your stakeholder and get in writing when you can delete old records then set an automated process or scheduled manual progress to do it. If they need the data long term maybe older data can be moved out of the online system and to an archive or warehouse. Microsoft has some other methods that I have not used. Check those out. https://docs.microsoft.com/en-us/sql/relational-databases/blob/binary-large-object-blob-data-sql-server?view=sql-server-ver15 -- Good luck More on reddit.com
๐ŸŒ r/dotnet
111
46
April 28, 2022
๐ŸŒ
gosamples
gosamples.dev โ€บ tutorials โ€บ encode a string to base64 in go
๐Ÿ‘‰ Encode a string to Base64 in Go
October 14, 2021 - package main import ( "encoding/base64" "fmt" ) func main() { text := "hello from gosamples.dev base64 encoding example!" encodedText := base64.StdEncoding.EncodeToString([]byte(text)) fmt.Printf("Encoded text: %s\n", encodedText) }
๐ŸŒ
GitHub
gist.github.com โ€บ xeoncross โ€บ e83313ac7157c659416676a6044fcd1e
Base 64 encode and decode a byte array in Golang. https://play.golang.org/p/X4z9zq0nXlW ยท GitHub
Base 64 encode and decode a byte array in Golang. https://play.golang.org/p/X4z9zq0nXlW ... This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
๐ŸŒ
ZetCode
zetcode.com โ€บ golang โ€บ base64
Base64 Encoding and Decoding in Go
July 16, 2026 - The base64.StdEncoding.Encode function encodes a source slice of bytes into a destination slice of bytes using the standard Base64 alphabet.
๐ŸŒ
Golang Docs
golangdocs.com โ€บ home โ€บ base64 encoding and decoding in golang
Base64 Encoding and Decoding in Golang - Golang Docs
July 29, 2022 - The encoding package in Go contains the base64 package. So, we need to import it first.
๐ŸŒ
Golang.cafe
golang.cafe โ€บ blog โ€บ golang-base64-encode-example
Golang base64 Encode Example | Golang.cafe
April 24, 2022 - // The encoder we will use is the base64.StdEncoding // It requires a byte slice so we cast the string to []byte encodedStr := base64.StdEncoding.EncodeToString([]byte(plainStr)) fmt.Println(encodedStr) // Decoding may return an error, in case the input is not well formed decodedStrAsByteSlice, err := base64.StdEncoding.DecodeString(encodedStr) if err != nil { panic("malformed input") } fmt.Println(string(decodedStrAsByteSlice)) }
Find elsewhere
๐ŸŒ
GitHub
github.com โ€บ go-yaml โ€บ yaml โ€บ issues โ€บ 231
Encode []byte as base64 string (to be consistent with stdlib JSON) ยท Issue #231 ยท go-yaml/yaml
December 20, 2016 - The standard library JSON module automatically converts any []byte struct members to base64 encoded strings when marshalling (see https://golang.org/pkg/encoding/json/#Marshal). The YAML library do...
Author: go-yaml
๐ŸŒ
Freshman Tech
freshman.tech โ€บ snippets โ€บ go โ€บ image-to-base64
How to retrieve the base64 encoding for any image in Go
December 3, 2020 - package main import ( "encoding/base64" "fmt" "io/ioutil" "log" "net/http" ) func toBase64(b []byte) string { return base64.StdEncoding.EncodeToString(b) } func main() { // Read the entire file into a byte slice bytes, err := ioutil.ReadFil...
๐ŸŒ
Go
go.dev โ€บ src โ€บ encoding โ€บ base64 โ€บ example_test.go
- The Go Programming Language
6 7 package base64_test 8 9 import ( 10 "encoding/base64" 11 "fmt" 12 "os" 13 ) 14 15 func Example() { 16 msg := "Hello, ไธ–็•Œ" 17 encoded := base64.StdEncoding.EncodeToString([]byte(msg)) 18 fmt.Println(encoded) 19 decoded, err := base64.StdEncoding.DecodeString(encoded) 20 if err != nil { 21 fmt.Println("decode error:", err) 22 return 23 } 24 fmt.Println(string(decoded)) 25 // Output: 26 // SGVsbG8sIOS4lueVjA== 27 // Hello, ไธ–็•Œ 28 } 29 30 func ExampleEncoding_EncodeToString() { 31 data := []byte("any + old & data") 32 str := base64.StdEncoding.EncodeToString(data) 33 fmt.Println(str) 34
๐ŸŒ
Base64 Decode and Encode
base64decode.net โ€บ golang-decodestring
Golang DecodeString() - Base64 Decode
Go lang - func (enc *Encoding) DecodeString(s string) ([]byte, error) - Decode an input String using Base64.
๐ŸŒ
Dot Net Perls
dotnetperls.com โ€บ base64-go
Go - base64 Example: EncodeToString - Dot Net Perls
With the encoding/base64 package, we can use the EncodeToString func in Go to get a string from a byte slice containing the image.
๐ŸŒ
Google Groups
groups.google.com โ€บ g โ€บ golang-nuts โ€บ c โ€บ kXMWIfSTix0
encoding/json treats []byte as b64 encoded. Could it not?
December 14, 2013 - Basically the current behavior is that if you have a struct with a []byte field that you pass into the json marshaler, it will represent that in the output json string as the base64 encoded version of what you put in, and if you're unmarshaling into a []byte it will try to base64 decode the ...
๐ŸŒ
gosamples
gosamples.dev โ€บ tutorials โ€บ decode base64 to a string in go
๐Ÿ‘ˆ Decode Base64 to a string in Go
October 14, 2021 - To get the decoded string, convert the byte slice to a string. Check also how to encode a string to Base64 in Go.
๐ŸŒ
Go Packages
pkg.go.dev โ€บ encoding โ€บ base64
base64 package - encoding/base64 - Go Packages
September 1, 2026 - NewEncoder returns a new base64 stream encoder. Data written to the returned writer will be encoded using enc and then written to w. Base64 encodings operate in 4-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.
๐ŸŒ
Weichou1229
weichou1229.github.io โ€บ posts โ€บ golang-base64-encode-and-decode
Golang | Base64 Encode and Decode | WeiChou
August 11, 2023 - package main import ( "encoding/base64" "fmt" "bytes" "encoding/binary" "math" ) func main() { val := 0.123 valToBytes := Float64ToByte(val) fmt.Println("Convert float", val, "to byte array:", valToBytes) base64EncodedStr := base64.StdEncoding.EncodeToString(valToBytes) fmt.Println("Encoded byte array to base64 string: ",base64EncodedStr) decodedToBytes, _ := base64.StdEncoding.DecodeString(base64EncodedStr) fmt.Println("Decode base64 string to float :",Float64frombytes(decodedToBytes)) } func Float64ToByte(f float64) []byte { var buf bytes.Buffer err := binary.Write(&buf, binary.BigEndian, f) if err != nil { fmt.Println("binary.Write failed:", err) } return buf.Bytes() } func Float64frombytes(bytes []byte) float64 { bits := binary.BigEndian.Uint64(bytes) float := math.Float64frombits(bits) return float }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ go language โ€บ base64-package-in-golang
base64 Package in Golang - GeeksforGeeks
June 22, 2020 - Decoded Bytes: [71 101 101 107 115 102 111 114 71 101 101 107 115] Decoded String: GeeksforGeeks Example 2: ... // Golang program to illustrate // the base64.NewEncoder() function package main import ( "encoding/base64" "fmt" ) func main() { // Input string giveninput := []byte("GeeksforGeeks") // Using EncodeToString() function // Encode the given string result := base64.StdEncoding.EncodeToString(giveninput) fmt.Println("Encoded string: ", result) } Output: