R
R
Red1zko2019-09-10 18:08:09
go
Red1zko, 2019-09-10 18:08:09

The web server on go does not return an image in the template. What's wrong?

There is a simple web server that should render the page according to the html template.
Its code is

package main

import (
  "fmt"
  "net/http"
)

type msg string

func (m msg) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
  fmt.Fprint(resp, m)
}

func main() {
  fs := http.FileServer(http.Dir("static"))
  http.Handle("/", fs)
  http.HandleFunc("/index", func(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "static/template/index.html")
  })
  fmt.Println("Server is started")
  http.ListenAndServe("localhost:8081", nil)
}

Well, actually the template itself
<!DOCTYPE html>
<head>
    <title>welcome</title>
    <script src="/js/bootstrap.min.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
</head>
<body>
    <div>
        <div class="row">
            <div class="col">1 of 4</div>
            <div class="col"><img src="/static/images/one.png" alt="img"></div>
        </div>
        <div class="row">
            <div class="col">3 of 4</div>
            <div class="col">4 of 4</div>
        </div>
    </div>
</body>
<footer>
    <p>this is the end</p>
</footer>

There is a .png file in a separate static folder.
In the browser, after starting the server, I see this
GET localhost:8081/static/images/one.png 404 (Not Found)
Moreover, if I open the template from the file system, everything shows fine.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Red1zko, 2019-09-11
@Red1zko

The error lurked in the incorrect description of absolute paths to static files.
Decision:

<!DOCTYPE html>
<head>
    <title>welcome</title>
    <script src="/js/bootstrap.min.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
</head>
<body>
    <div>
        <div class="row">
            <div class="col">1 of 4</div>
            <div class="col"><img src="/images/one.png" alt="img"></div>
        </div>
        <div class="row">
            <div class="col">3 of 4</div>
            <div class="col">4 of 4</div>
        </div>
    </div>
</body>
<footer>
    <p>this is the end</p>
</footer>

H
hOtRush, 2019-09-10
@hOtRush

I'll just assume that the path to the image is relative, relative to /index, i.e. instead of /static/images/one.png it tries to /index/static/images/one.png and gets 404

I
igorzakhar, 2019-09-11
@igorzakhar

...
<div class="col"><img src="/images/one.png" alt="img"></div>
...

5d78c5c77c57b092229910.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question