Convert data to base64 encode in go - go

I am new to go programming language and I'm stock on this scenario on my code.
Here's my example code:
a := genreAPI{Genre{"Pop"}, Genre{"Rock"}}
fmt.Println("Value of a :", a)
The current output is: Value of a : [{Pop} {Rock}]
How can I achieved an output like this:
Value of a : [{UG9w} {Um9jaw==}]
which is a base64 encode?

I am not sure what exactly is not clear from the documentation. Not only it has a clear name which explains states what the method is doing, it also has an example.
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := []byte("Pop")
str := base64.StdEncoding.EncodeToString(data)
fmt.Println(str) // UG9w
}
Go Playground

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.
Example:
package main
import (
"encoding/base64"
"fmt"
)
type Base64String string
func (b Base64String) String() string {
return base64.StdEncoding.EncodeToString([]byte(b))
}
type Genre struct {
Name Base64String
}
func main() {
a := []Genre{Genre{"Pop"}, Genre{"Rock"}}
fmt.Println(a) // prints [{UG9w} {Um9jaw==}]
fmt.Println(string(a[0].Name)) // prints Pop
}

Related

Printf function show struct differently

I am using compile function of regex package which returns pointer of Regexp struct and passing struct in printf function shows me only string not whole struct.
package main
import (
"fmt"
"regexp"
)
func main() {
reg, _ := regexp.Compile(`[0-9a-f]+`)
fmt.Printf("%+v \n", reg)
}
// Output
[0-9a-f]+
But when I created my own struct and initialising with some value and print it then it shows full struct. I am not understanding the concept here.
package main
import (
"fmt"
)
type Exp struct {
a string
b int
}
func main() {
x := &Exp{"akash", 12}
fmt.Printf("%+v \n", x)
}
// Output: &{akash 12}
The regexp.Regexp type implements the fmt.Stringer interface, which is the default verb used in the fmt.Print* methods.
This means that it calls reg.String() when formatting in your first example.
In your second example, your custom type Exp, has no such method, so it uses default Go-formatting of the struct.

Remove elements with empty value when no values

I want to remove elements with empty value in struct. My script is below. Output of this script is {"keyA":{}}. I used omitempty to KeyA and KeyB. But an element with empty value is left. On the other hand KeyB is not shown. I want to show KeyA when it has values. I don't want to show KeyA when it has no values. Is there way to do this?
Script
package main
import (
"encoding/json"
"fmt"
)
type sample struct {
KeyA struct {
Key1 string `json:"keyA1,omitempty"`
Key2 string `json:"keyA2,omitempty"`
} `json:"keyA,omitempty"`
KeyB string `json:"keyB,omitempty"`
}
func main() {
var s sample
response, _ := json.Marshal(s)
fmt.Println(string(response)) // {"keyA":{}}
}
Thank you so much for your time. And I'm sorry for my immature question.
Try this:
package main
import (
"encoding/json"
"fmt"
)
type KeyA struct {
Key1 string `json:"keyA1,omitempty"`
Key2 string `json:"keyA2,omitempty"`
}
type sample struct {
KeyA *KeyA `json:"keyA,omitempty"`
KeyB string `json:"keyB,omitempty"`
}
func main() {
var s sample
response, _ := json.Marshal(s)
fmt.Println(string(response)) // {}
}
output:
{}

main.go:9: use of package str without selector

I have the following in the intepreter of Tour of Go:
package main
import (
"golang.org/x/tour/wc"
str "strings"
)
func WordCount(s string) map[string]int {
results := make(map[str]int)
words := str.Fields(s)
return map[string]int{"x": 1}
}
//func main() {
// wc.Test(WordCount)
//}
This is based on https://tour.golang.org/moretypes/23
My error is
tmp/sandbox169629521/main.go:9: use of package str without selector
Trying
results := make(map[str.string]int)
now fails with
tmp/sandbox424441423/main.go:9: cannot refer to unexported name strings.string
tmp/sandbox424441423/main.go:9: undefined: strings.string
"string" is a builtin. You don't need to do strings.string:
Docs: https://golang.org/pkg/builtin/#string

How can I parse []int JSON data in Go?

I try parse JSON data include integer array. But, I can't get integer array.
package main
import (
"encoding/json"
"fmt"
)
type Anything struct {
A []int `json:"a"`
}
func main() {
s := "{a:[1,2,3]}"
var a Anything
json.Unmarshal([]byte(s), &a)
fmt.Println(a.A)
}
I got empty array.
[]
How can I get [1, 2, 3]?
{a:[1,2,3]} is not valid JSON. Object keys must be double-quoted. Changing it like this works as expected:
s := "{\"a\":[1,2,3]}"
https://play.golang.org/p/qExZAeiRJy
You have an invalid JSON. You should replace it, for example like this: s := [{"a":[1,2,3]}] or maybe like this s := "[{\"a\":[1,2,3]}]".
You can edit your code to something like this:
package main
import (
"encoding/json"
"fmt"
)
type Anything struct {
A []int `json:"a"`
}
func main() {
// note here: `[{"a":[1,2,3]}]`
// or: s := "[{\"a\":[1,2,3]}]"
s := `[{"a":[1,2,3]}]`
var a []Anything
json.Unmarshal([]byte(s), &a)
fmt.Println(a)
}
Output:
[{[1 2 3]}]
You can run it on https://play.golang.org/p/H4GupGFpfP

How do I parse URLs in the format of /id/123 not ?foo=bar

I'm trying to parse an URL like:
http://example.com/id/123
I've read through the net/url docs but it seems like it only parses strings like
http://example.com/blah?id=123
How can I parse the ID so I end up with the value of the id in the first example?
This is not one of my own routes but a http string returned from an openid request.
In your example /id/123 is a path and you can get the "123" part by using Base from the path module.
package main
import (
"fmt"
"path"
)
func main() {
fmt.Println(path.Base("/id/123"))
}
For easy reference, here's the docs on the path module. http://golang.org/pkg/path/#example_Base
You can try using regular expression as follow:
import "regexp"
re, _ := regexp.Compile("/id/(.*)")
values := re.FindStringSubmatch(path)
if len(values) > 0 {
fmt.Println("ID : ", values[1])
}
Here is a simple solution that works for URLs with the same structure as yours (you can improve to suit those with other structures)
package main
import (
"fmt"
"net/url"
)
var path = "http://localhost:8080/id/123"
func getFirstParam(path string) (ps string) {
// ignore first '/' and when it hits the second '/'
// get whatever is after it as a parameter
for i := 1; i < len(path); i++ {
if path[i] == '/' {
ps = path[i+1:]
}
}
return
}
func main() {
u, _ := url.Parse(path)
fmt.Println(u.Path) // -> "/id/123"
fmt.Println(getFirstParam(u.Path)) // -> "123"
}
Or, as #gollipher suggested, use the path package
import "path"
func main() {
u, _ := url.Parse(path)
ps := path.Base(u.Path)
}
With this method it's faster than regex, provided you know before hand the structure of the URL you are getting.

Resources