0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Using html/template package at Golang

Last updated at Posted at 2019-02-17

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

スクリーンショット 2019-02-17 9.04.00.png

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

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?