A
A
Abcdefgk2018-08-03 22:31:06
go
Abcdefgk, 2018-08-03 22:31:06

Why is the data on the page duplicated, duplicated and duplicated, etc.?

Please someone explain this amazing effect to me.
Here is my code that takes a simple table with four fields from the database with the usual SELECT * FROM books query,
sends it to the prepared structure, reads the file with the template, parses it and sends it back to the client with the data, like this (a fragment, of course):

for rows.Next() {
      bk := new(Book)
      err := rows.Scan(&bk.Isbn, &bk.Title, &bk.Author, &bk.Price)
      if err != nil {
        http.Error(w, http.StatusText(500), 500)
        return
      }
      Books.Items = append(Books.Items, bk)
    }

    if err = rows.Err(); err != nil {
      http.Error(w, http.StatusText(500), 500)
      return
    }

    f, err := ioutil.ReadFile("file.tpl")
    if err != nil {
      fmt.Println(err)
    }

    html, err := template.New("books").Parse(string(f))
    if err != nil {
      fmt.Println(err)
    }

    w.Header().Set("Cache-Control", "no-cache")

    html.Execute(w, Books)

such template:
<body>
  {{ range .Items }}
    <div><b>{{ .Isbn }}</b> {{ .Title }} {{ .Author }} {{ .Price }}</div>
  {{else}}
    <div><strong>no rows</strong></div>
  {{end}}
  <br>

and safely displays on the page in the browser, like this:
5b64aac922e59401639998.jpeg
Now if I just refresh the page, then the same five divs will be displayed again, but they will remain from the previous request (i.e. there will be 10 in total), like this:
5b64ab66642d8350188634.jpeg
if I call the page again, then there will be 5x3 = 15 of them, etc.
There is a form on the page, as you can see, with which you can add a row to the database. If I fill in the fields and press the button, the line will be successfully added to the database, the page will naturally reload, and it will contain the past 15 (or more) lines plus the new six now (the former five and the added line in the table).
And what, tell me, is there an explanation for this?
As you can see, I already added the title to the answer Cache-Control - no-cache - which, of course, is useless, but I don't understand.
New request, new response, new page - the data is multiplied.
Like this? What's wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Tsvetkov, 2018-08-03
@Abcdefgk

it looks like Books is declared globally and is not cleared after the request, on each request you push data into it Books.Items = append(Books.Items, bk) hence the result

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question