Skip to content

Instantly share code, notes, and snippets.

@johnnncodes
Forked from mattcunningham/Tags.go
Created April 30, 2016 04:38
Show Gist options
  • Save johnnncodes/3a39c3eac65b3db4a4c8000bc763b458 to your computer and use it in GitHub Desktop.
Save johnnncodes/3a39c3eac65b3db4a4c8000bc763b458 to your computer and use it in GitHub Desktop.
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