HUGO

Concatenating token into URL

Hi - I have a shortcode, that uses getJSON to pull some info from a REST interface. I had the REST API token hard coded, but now want to pull the token from the environment instead, and use it in a variable in my code. I’m able to insert the token into the URL I need using delimit (slice...) like this:

{{ $urlPre := "https://mydb.com" }}
{{ $datanote := .Get 0 }}
{{ $token := getenv "TOKEN123" }}
{{ $urlPost1 := delimit (slice "/secure/api/v2/12345/" $token "/Table-Name/View-Name/select.json") "" }}

{{ if eq $.Page.RelPermalink "/slug-01/" }}
  {{ $licdata := getJSON $urlPre $urlPost1 }}
  {{ $updatedata := getJSON $urlPre "/secure/api/v2/12345/8406***60DB/Table-Name/View-Name/select.json?top=1" }}
  <div class="fr f7 pr3">{{ range $updatedata }}{{ with (index . "Updated JP Year Month") }}{{ . }}{{ end }}{{ end }} {{ len $licdata }}名&nbsp;&nbsp; {{$datanote}}</div>

{{ else if eq $.Page.RelPermalink "/slug-02" }}
  {{ $licdata := getJSON $urlPre "/secure/api/v2/12345/8406***60DB/Table-Name/View-Name/select.json" }}
  {{ $updatedata := getJSON $urlPre ... }}
  <div class="fr f7 pr3">{{ range $updatedata }}{{ with (index . "Updated JP Year Month") }}{{ . }}{{ end }}{{ end }} {{ len $licdata }}名&nbsp;&nbsp; {{$datanote}}</div>

{{ else if ...

I tried:

{{ $updatedata := getJSON $urlPre "/secure/api/v2/12345/$token/Table-Name/View-Name/select.json?top=1" }}
...or...
{{ $updatedata := getJSON $urlPre "/secure/api/v2/12345/{{with $token}}{{.}}{{end}}/Table-Name/View-Name/select.json?top=1" }}

… and some variants along those lines, but nothing except the slice method actually worked.

I’d rather not put the full URLs into env vars, because then I need to look them up when troubleshooting.

What I’m wondering is, is there a better way than delimit (slice...) for this kind of situation where you need to insert a token into an URL you’re using to pull data?

{{ printf "foo/%s/bar" $token }} 
1 Like

Oof, much better! Thanks!

Also: it looks like that from 0.84 you can specify headers too, which should clean this up: Data Templates | Hugo

Edit: yes, something like this is working:

{{ $bearertoken := printf "Bearer %s" $token }} 
{{ $data := getJSON "https://theservice.com/api/TableName/ViewName/select.json" (dict "Authorization" $bearertoken)  }}

A benefit to using headers is, the full URL plus token is not in std-out when running hugo with the --verbose switch. Same thing for on any CI side. Probably you can keep the token out of the logs, this way.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.