Skip to content

Instantly share code, notes, and snippets.

@mattcunningham
Created August 3, 2015 07:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mattcunningham/6d812753de40a0eca766 to your computer and use it in GitHub Desktop.
Save mattcunningham/6d812753de40a0eca766 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