github.com/blend/go-sdk@v1.20220411.3/stringutil/replace_path_parameters.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package stringutil 9 10 import ( 11 "strings" 12 13 "github.com/blend/go-sdk/ex" 14 ) 15 16 // Error Constants 17 const ( 18 ErrMissingRouteParameters ex.Class = "missing route parameter in params" 19 ) 20 21 // ReplacePathParameters will replace path parameters in a URL path with values 22 // from the passed in `params` map. Path parameters in the format of `:<param_name>`. 23 // Example usage: `ReplacePathParameters("/resource/:resource_id", map[string]string{"resource_id": "1234"})` 24 func ReplacePathParameters(str string, params map[string]string) (string, error) { 25 if params == nil { 26 params = make(map[string]string) 27 } 28 29 parts := strings.Split(str, "/") 30 for i := range parts { 31 if !strings.HasPrefix(parts[i], ":") { 32 continue 33 } 34 pathValue, ok := params[strings.TrimPrefix(parts[i], ":")] 35 if !ok { 36 pathValue, ok = params[parts[i]] 37 if !ok { 38 return "", ex.New(ErrMissingRouteParameters, ex.OptMessagef("Missing %s", parts[i])) 39 } 40 } 41 42 parts[i] = pathValue 43 } 44 45 return strings.Join(parts, "/"), nil 46 }