how to convert the given code in go templating

Viewed 254

I am using go's text/template. I want to do something like:

method = some_var
path = some_other_var    
if method is "GET" and "ID" in path

How can I do this in a go template? I am doing it like this.

{{- if and eq .Method "GET" contains "AssetID" .OperationId -}}

EDIT:

The thing is I am working with openAPI to generate a server-code boilerplate. So the templates are in that repo. I am doing it something like:

$ go get github.com/deepmap/oapi-codegen/cmd/oapi-codegen
$ oapi-codegen \
    -templates my-templates/ \
    -generate types,server \
    example-expanded.yaml  

above oapi-codegen line is here. my-templates contains the templates I have changed. These are also provided by oapi-codegen. this dir contains them and I have copied and changed a few of them and followed the steps as directed here.

in one of those templates that I changed, I want to use contains. What would be the best way to do this?

1 Answers

There is no builtin contains function in templates, so you have to register your function for that. You may use the strings.Contains() function from the standard lib. For reference, the available builtin template functions are listed here: Functions

And you have to group the params of the eq and contains like this:

{{if and (eq .Method "GET") (contains .AssetID .OperationId)}}
    true
{{else}}
    false
{{end}}

Example code to register the strings.Contains() function, parse the template and execute it:

t := template.Must(template.New("").Funcs(template.FuncMap{
    "contains": strings.Contains,
}).Parse(src))

params := map[string]interface{}{
    "Method":      "GET",
    "AssetID":     "/some/path/123",
    "OperationId": "123",
}
if err := t.Execute(os.Stdout, params); err != nil {
    panic(err)
}

params["OperationId"] = "xxx"
if err := t.Execute(os.Stdout, params); err != nil {
    panic(err)
}

This will output (try it on the Go Playground):

true

false
Related