github.com/benoitkugler/goacve@v0.0.0-20201217100549-151ce6e55dc8/server/shared/views.go (about)

     1  package shared
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"html/template"
     7  
     8  	"github.com/labstack/echo"
     9  )
    10  
    11  // Empêche le navigateur de mettre en cache
    12  // pour avoir les dernières versions des fichiers statiques
    13  // (essentiellement les builds .js)
    14  func NoCache(next echo.HandlerFunc) echo.HandlerFunc {
    15  	return func(c echo.Context) error {
    16  		c.Response().Header().Set("Cache-Control", "no-store")
    17  		c.Response().Header().Set("Expires", "0")
    18  		return next(c)
    19  	}
    20  }
    21  
    22  func CacheStatic(next echo.HandlerFunc) echo.HandlerFunc {
    23  	return func(c echo.Context) error {
    24  		c.Response().Header().Set("Cache-Control", "max-age=31536000")
    25  		return next(c)
    26  	}
    27  }
    28  
    29  func addPayload(t *template.Template, payload interface{}) ([]byte, error) {
    30  	b, err := json.Marshal(payload)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  	templateArgs := struct{ Payload string }{Payload: string(b)}
    35  	var buf bytes.Buffer
    36  	if err = t.Execute(&buf, templateArgs); err != nil {
    37  		return nil, err
    38  	}
    39  	return buf.Bytes(), nil
    40  }
    41  
    42  // HtmlWithPayload read `file` as an Go template, and replace .Payload
    43  // entries with the json representation of `payload`,
    44  // before emitting the output.
    45  // In case of errror, redirects.
    46  func HtmlWithPayload(c echo.Context, file string, payload interface{}) error {
    47  	t, err := template.ParseFiles(file)
    48  	if err != nil {
    49  		return RedirectError(c, err)
    50  	}
    51  	b, err := addPayload(t, payload)
    52  	if err != nil {
    53  		return RedirectError(c, err)
    54  	}
    55  	return c.HTMLBlob(200, b)
    56  }