Skip to content

Instantly share code, notes, and snippets.

@jeremeamia
Last active January 24, 2020 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremeamia/75c0a6ae43b2f0d29cd360deadee0852 to your computer and use it in GitHub Desktop.
Save jeremeamia/75c0a6ae43b2f0d29cd360deadee0852 to your computer and use it in GitHub Desktop.
Golang support for "path" struct tag fro resolving URLs
package main
import (
"fmt"
"reflect"
"strings"
)
type MyUrlParams struct {
UserId string `path:"user",json:"-"`
OrgId string `path:"org"`
Foo string
}
func main() {
params := MyUrlParams{
UserId: "abc123",
OrgId: "xyz789",
Foo: "bar",
}
uri := "/api/v1/users/{user}/orgs/{org}"
fmt.Println(resolvePath(uri, params))
}
func resolvePath(uri string, params interface{}) string {
for search, replace := range getPathParams(params) {
uri = strings.Replace(uri, "{"+search+"}", replace, 1)
}
return uri
}
func getPathParams(params interface{}) map[string]string {
p := map[string]string{}
v := reflect.ValueOf(params)
for i := 0; i < v.NumField(); i++ {
val := v.Field(i).String()
tag := v.Type().Field(i).Tag.Get("path")
if tag != "" {
p[tag] = val
}
}
return p
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment