modèle de rendu Golang
package main
import (
"encoding/json"
"html/template"
"log"
"net/http"
"os"
)
type APIResponse struct {
Stat_code int
Stat_msg string
}
func RenderTemplateGlobal() (*template.Template, error) {
tmpl, err := template.ParseGlob("views/*")
return tmpl, err
}
func RenderTemplateFile() *template.Template {
html, err := template.ParseFiles("views/index.html", "views/header.html")
tmpl := template.Must(html, err)
return tmpl
}
func JsonOutput(w http.ResponseWriter, r *http.Request) {
data := APIResponse{Stat_code: 200, Stat_msg: "Testing"}
stringify, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
w.Write(stringify)
}
func HtmlOuput(w http.ResponseWriter, r *http.Request) {
data := APIResponse{Stat_code: 200, Stat_msg: "Hello Wordl"}
html, err := template.ParseFiles("index.html")
if err != nil {
log.Fatal(err)
}
html.Execute(w, data)
}
func HtmlWithCss(w http.ResponseWriter, r *http.Request) {
data := APIResponse{Stat_code: 200, Stat_msg: "Hello Wordl"}
html, err := template.ParseFiles("index.html")
if err != nil {
log.Fatal(err)
}
html.Execute(w, data)
}
func MultipleTemplate(w http.ResponseWriter, r *http.Request) {
html, err := RenderTemplateGlobal()
if err != nil {
log.Fatal(err)
}
html.ExecuteTemplate(w, "index", nil)
}
func InlineTemplate(w http.ResponseWriter, r *http.Request) {
html := `
<html>
<head>
<title> InlineTemplate </title>
</head>
<body>
<h1> {{ .Stat_msg }} </h1>
</body>
</html>
`
parse := template.Must(template.New("basic").Parse(html))
parse.Lookup("basic").Execute(w, APIResponse{Stat_msg: "Inline Template Testing"})
}
func main() {
// mounting static assets
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(os.DirFS("assets")))))
http.HandleFunc("/", HtmlOuput)
http.HandleFunc("/json", JsonOutput)
http.HandleFunc("/css", HtmlWithCss)
http.HandleFunc("/multiple", MultipleTemplate)
http.HandleFunc("/inline", InlineTemplate)
http.ListenAndServe(":3000", nil)
}
Restu Wahyu Saputra