Environmnet
go version go1.11.5 linux/amd64
Directory Structure
/go
└ src/
└ sample/
└ main.go
└ templates/
└ index.html
Source code
main.go
package main
import(
"html/template"
"log"
"net/http"
)
func handlerIndex(w http.ResponseWriter, req *http.Request) {
// If you know parsing template files will be successful, you can skip the error handling by using Must().
t := template.Must(template.ParseFiles("templates/index.html"))
/* or you can code
t, e4t := template.ParseFiles("templates/index.html")
if e4t != nil { log.Fatal(e4t) }
*/
s := "Hello, world."
e := t.ExecuteTemplate(w, "index.html", s)
if e != nil { log.Fatal(e) }
}
func main() {
http.HandleFunc("/", handlerIndex)
http.ListenAndServe(":8080", nil)
}
templates/index.html
<!DOCTYPE html>
<html>
<body>
<!-- variable expansion -->
{{ . }}
</body>
</html>
Build & Run
cd $GOPATH/src/sample/ && go run main.go
Then access to localhost:8080, you can see
If you'd like to use other template for each URI
main.go
package main
import(
"html/template"
"log"
"net/http"
)
func handlerIndex(w http.ResponseWriter, req *http.Request) {
t := template.Must(template.ParseFiles("templates/index.html"))
s := "Hello, world."
e := t.ExecuteTemplate(w, "index.html", s)
if e != nil { log.Fatal(e) }
}
func handlerInfo(w http.ResponseWriter, req *http.Request) {
t := template.Must(template.ParseFiles("templates/info.html"))
s := "This is an information."
e := t.ExecuteTemplate(w, "info.html", s)
if e != nil { log.Fatal(e) }
}
func main() {
http.HandleFunc("/", handlerIndex)
http.HandleFunc("/info", handlerInfo)
http.ListenAndServe(":8080", nil)
}
Refs
https://golang.org/pkg/net/http/#ResponseWriter
https://golang.org/pkg/html/template/
https://golang.org/pkg/text/template/#Must