Web app <img> not working

I am an experienced developer but have written mostly desktop applications. I am writing my first web server using Golang and it is working fine. I run it locally and can call it from a browser on the server or any other computer on my Wifi network I have three request handlers, one of which is called primesRequestHandler() and responds to requests starting with “/primes/”
I wanted to learn to bring in images so I added this line:
Rick
The Rick.jpg file is in the same directory as the main.go file.
The file fails to load and one of my handlers gets called.
So I logged the incoming request:
primesRequestHandler r.URL.Path: /primes/Rick.jpg
I would expect the browser to retrieve the file from the server using something like:
http://192.168.8.7:8080/Rick.jpg but I guess that’s not how it works.

I forgot to mention that I am using a template. I checked what the template is checking and this is how it shows there:
Rick
It seems fine.

This will not work, because Go do not know where to find the image:
<img alt="Rick" width="100" height="80">

You must add the path to the image
<img src="/img/rick.jpg" alt="Rick">

And in main.go you add this line:

func init() {
	tpl = template.Must(template.ParseGlob("public/tmpl/*.html"))
	http.Handle("/img/", http.StripPrefix("/img/", http.FileServer(http.Dir("./public/img"))))
}

Assuming you have this folder structure: Install Go on Your Computer

3 Likes

Weird, somehow when I pasted the HTML into my message, it removed the src part. Maybe if I quote it:
Rick
Anyway your suggestion worked great. Thanks so much.

Wow that didn’t work either. You will have to trust me. the src setting is in there.

If you past your code directly it will appear as
Rick
If you select your code and use the ‘</>’ button it will appear as code:
<img src="/img/rick.jpg" alt="Rick"> (or use backticks `)

<img src="/images/Rick.jpg" alt="Rick" width="100" height="80">

I’ll try it. I figured there must be some way to show code.

1 Like