Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"reflect"
"net/url"
)
type ExampleType struct {
Name string `url:"name"`
Address string `url:"address"`
City string `url:"city"`
}
func ReadTagAndValue(val interface{}) url.Values {
value := reflect.ValueOf(val) // turns struct type to the reflection interface
params := url.Values{}
for i := 0; i < value.NumField(); i++ { // iterates through every struct type field
tag := value.Type().Field(i).Tag // returns the tag string
field := value.Field(i) // returns the content of the struct type field
params.Set(tag.Get("url"), field.String())
}
return params
}
func main() {
params := ReadTagAndValue(ExampleType{
Name: "Example",
Address: "1234 Apple Street",
City: "New York",
})
fmt.Println(params.Encode())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.