Last active
January 24, 2020 00:30
-
-
Save jeremeamia/75c0a6ae43b2f0d29cd360deadee0852 to your computer and use it in GitHub Desktop.
Golang support for "path" struct tag fro resolving URLs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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