I'm facing 2 different issues here:
w.Header().Add("Content-Type", "text/event-stream")
w.Header().Add("Cache-Control", "no-cache")
w.Header().Add("Connection", "keep-alive")
the styles disappears from the website automatically and appears on the browser like this
// for {
// time.Sleep(20 * time.Second)
// welcome.Time = time.Now().Format(time.Stamp)
// if err := templates.ExecuteTemplate(w, "body", welcome); err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// }
// //fmt.Fprintf(w, "data: %s\n", in.Text())
// flusher.Flush()
// }
The moment I uncomment it, rather than updating the same section on the web page, template started repeating like this
Welcome Anonymous, it is Jun 16 13:09:19Jun 16 13:09:39Jun 16 13:09:59
I would be grateful if someone help me here please.
The structure of my project is:
Project
|_ _client
|_ _ welcome-template.css
|_ _ background.jpeg
|_ _ main.go
Main.go
package main
import (
"fmt"
"html/template"
"net/http"
"time"
)
type Welcome struct {
Name string
Time string
}
func main() {
htm := `{{define "layout"}}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/client/welcome-template.css">
<title>Welcome {{.Name}}</title>
</head>
<body>
<div class="welcome center">Welcome {{.Name}}, it is {{template "body" .}}</div>
</body>
</html>
{{end}}`
tim := `{{define "body"}}{{.Time}}{{end}}`
welcome := Welcome{"Anonymous", time.Now().Format(time.Stamp)}
templates := template.Must(template.New("layout").Parse(htm))
templates = template.Must(templates.Parse(tim))
http.Handle("/client/", http.StripPrefix("/client/", http.FileServer(http.Dir("client"))))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// flusher, ok := w.(http.Flusher)
// if !ok {
// http.Error(w, "Streaming not supported", http.StatusInternalServerError)
// return
// }
w.Header().Add("Content-Type", "text/event-stream")
w.Header().Add("Cache-Control", "no-cache")
w.Header().Add("Connection", "keep-alive")
if name := r.FormValue("name"); name != "" {
welcome.Name = name
}
if err := templates.ExecuteTemplate(w, "layout", welcome); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// for {
// time.Sleep(20 * time.Second)
// welcome.Time = time.Now().Format(time.Stamp)
// if err := templates.ExecuteTemplate(w, "body", welcome); err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// }
// //fmt.Fprintf(w, "data: %s\n", in.Text())
// flusher.Flush()
// }
})
fmt.Println("Listening")
fmt.Println(http.ListenAndServe(":8080", nil))
}
Welcome-Template.css
body {
min-height:100%;
background-image: url("/client/background.jpeg"), linear-gradient(rgba(0,0,0,0.2),rgba(0,0,0,0.3));
background-blend-mode: overlay;
background-size:cover;
}
.welcome {
font-family: 'Segoe UI', 'Tahoma', 'Geneva', 'Verdana', 'sans-serif';
font-size: 3rem;
color: aliceblue;
}
.center {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}