martos inc.
martos inc.

Reputation: 21

Trying to get an image showed in golang template

Im using golang to set up a server and im executing templates inside of it. Inside of my templates I'm trying to get an image, but for some reason nothing i try works. In the console it says gives that error: 

GET http://localhost:5051/static/photo_2021-06-17_14-18-09.jpg 404 (Not Found)

Go code :

package main

import (
    "html/template"
    "net/http"
    // "io/ioutil"
)


func main() {
    http.HandleFunc("/a", indexHandler)
    http.ListenAndServe(":5051", nil)

    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("templates/main.html")
    t.ExecuteTemplate(w, "main", struct{}{})
}

Template code:

{{ define "main" }}
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div>
            <img src="../static/photo_2021-06-17_14-18-09.jpg">
        </div>
    </body>
</html>
{{ end }}

Thanks!

Upvotes: 1

Views: 1274

Answers (1)

Damian Chrzanowski
Damian Chrzanowski

Reputation: 479

Move the http.ListenAndServe line below the static handler.

Upvotes: 2

Related Questions