-2

I'm using a template in a Go web application which should show an image depending on which country the visitor is from.

For the images I use the FileServer

http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images"))))

In the template the variable country is passed so the application knows which flag to show.

<img id='flag' src='images/{{ .Country}}.png'>

However, for some reason the string I pass adds %0a which causes the src of the img to be wrong.

<img id='flag' src='images/BE%0A.png'>

The expected output should be

<img id='flag' src='images/BE.png'>

The following code is used to grab the country string

resp3, err := http.Get("https://ipinfo.io/country")
if err != nil {
    fmt.Println(err)
}
bytes3, _ := ioutil.ReadAll(resp3.Body)
country := string(bytes3)

Could anyone help me resolve this issue?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
joske123
  • 35
  • 3
  • 4
    Most likely the value of `.Country` already contains the trailing `\x0a` character (which is a newline `\n`). Print it like `fmt.Printf("%q", country)` to verify. If so, you have to strip them off with e.g. `strings.TrimSpace()`. – icza Jan 09 '19 at 14:13
  • Thx, this solved it! – joske123 Jan 09 '19 at 14:18

1 Answers1

1

the string I pass adds %0a which causes the src of the img to be wrong.

<img id='flag' src='images/BE%0A.png'>

The expected output should be

<img id='flag' src='images/BE.png'>

Trim the newline (0x0A or "\n"). For example,

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    resp3, err := http.Get("https://ipinfo.io/country")
    if err != nil {
        fmt.Println(err)
    }
    bytes3, err := ioutil.ReadAll(resp3.Body)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%q\n", bytes3)
    country := string(bytes.TrimRight(bytes3, "\n"))
    fmt.Printf("%q\n", country)
}

Output:

"US\n"
"US"
peterSO
  • 158,998
  • 31
  • 281
  • 276