#instalation
just copy and paste the code in your code editor, and run
go mod init <project-name>
go mod tidy
package main | |
import ( | |
"html/template" | |
"io" | |
"log" | |
"net/http" | |
"github.com/labstack/echo/v4" | |
) | |
// TemplateRenderer is a custom html/template renderer for Echo framework | |
type TemplateRenderer struct { | |
templates *template.Template | |
} | |
// Render renders a template document | |
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error { | |
// Add global methods if data is a map | |
if viewContext, isMap := data.(map[string]interface{}); isMap { | |
viewContext["reverse"] = c.Echo().Reverse | |
} | |
return t.templates.ExecuteTemplate(w, name, data) | |
} | |
func main() { | |
e := echo.New() | |
// e.Use(middleware.Logger()) | |
// e.Use(middleware.Recover()) | |
renderer := &TemplateRenderer{ | |
templates: template.Must(template.ParseGlob("*.html")), | |
} | |
e.Renderer = renderer | |
e.GET("users", func(c echo.Context) error { | |
out := getUsers() | |
return c.Render(http.StatusOK, "user.html", out) | |
}) | |
e.POST("users", func(c echo.Context) error { | |
user := new(User) | |
if err := c.Bind(user); err != nil { | |
return err | |
} | |
inputUser(user) | |
out := getUsers() | |
return c.Render(http.StatusOK, "user.html", out) | |
}) | |
e.Logger.Fatal(e.Start(":8000")) | |
} | |
//user | |
type User struct { | |
Name string `form:"name"` | |
Age int64 `form:"age"` | |
} | |
var dataUsers []User | |
func getUsers() (users []User) { | |
return dataUsers | |
} | |
func inputUser(in *User) User { | |
dataUsers = append(dataUsers, *in) | |
return *in | |
} |
<!doctype html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<script src="https://cdn.tailwindcss.com"></script> | |
<script | |
src="https://unpkg.com/[email protected]" | |
integrity="sha384-QWGpdj554B4ETpJJC9z+ZHJcA/i59TyjxEPXiiUgN2WmTyV5OEZWCD6gQhgkdpB/" | |
crossorigin="anonymous" | |
></script> | |
</head> | |
<body> | |
<h1 class="text-3xl font-bold underline">Hello world!</h1> | |
<form action="/users" method="post" class="my-4"> | |
<label for="name">Name</label> | |
<input | |
class="form-input border" | |
type="text" | |
id="name" | |
name="name" | |
/><br /><br /> | |
<label for="age">Age</label> | |
<input class="form-input border" type="text" name="age" id="age" /> | |
<button type="submit">save</button> | |
</form> | |
<table class="p-4 border-collapse border border-slate-500"> | |
<thead> | |
<tr> | |
<th class="px-4 border border-slate-600">Name</th> | |
<th class="px-4 border border-slate-600">Age</th> | |
</tr> | |
</thead> | |
<tbody> | |
{{- range . }} | |
<tr> | |
<td class="px-4 border border-slate-700">{{ .Name }}</td> | |
<td class="px-4 border border-slate-700">{{ .Age }}</td> | |
</tr> | |
{{ end -}} | |
</tbody> | |
</table> | |
</body> | |
</html> |