github.com/grafana/pyroscope@v1.18.0/public/execute_template.go (about) 1 package public 2 3 import ( 4 "bytes" 5 "net/url" 6 "strings" 7 "text/template" 8 ) 9 10 type Params struct { 11 BasePath string 12 } 13 14 // ExecuteTemplate executes a template using parameters 15 // It will transform each parameter as needed 16 func ExecuteTemplate(file []byte, params Params) ([]byte, error) { 17 var err error 18 params.BasePath, err = prepareBasePath(params.BasePath) 19 if err != nil { 20 return nil, err 21 } 22 23 tmpl, err := template.New("").Parse(string(file)) 24 if err != nil { 25 return nil, err 26 } 27 28 var buf bytes.Buffer 29 if err = tmpl.Execute(&buf, map[string]string{ 30 "BaseURL": params.BasePath, 31 }); err != nil { 32 return nil, err 33 } 34 35 return buf.Bytes(), nil 36 } 37 38 func prepareBasePath(basepath string) (string, error) { 39 u, err := url.Parse(basepath) 40 if err != nil { 41 return "", err 42 } 43 44 u.Path = strings.TrimSpace(u.Path) 45 46 if !strings.HasSuffix(u.Path, "/") { 47 u.Path = u.Path + "/" 48 } 49 50 if !strings.HasPrefix(u.Path, "/") { 51 u.Path = "/" + u.Path 52 } 53 54 return u.String(), nil 55 }