Snippets

Set Default headers via middleware

type Header struct {
	Name  string
	Value string
}
 
func defaultHeaders(headers []Header) echo.MiddlewareFunc {
  return func(next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
      for _, header := range headers {
        c.Response().Header().Set(header.Name, header.Value)
      }
      return next(c)
    }
  }
}
 
// Usage
e.Use(defaultHeaders([]Header{
  {"Cache-Control", "max-age=3600"},
}))
 

Load environment variables

func env(key string, defaultValue string) string {
  value := os.Getenv(key)
  if value == "" {
    return defaultValue
  }
  return value
}
 
// Usage
PORT := env("PORT", "3000")
Link to original

Serving Static Files

Note, the path /src/static is relative to the go.mod file

e.Static("/src/static", "static")