Go provides helpful packages for web development. Templates come with the language and a powerful asset.

Let’s begin by serving a plain http file


//app.go

package main

import "net/http"

func serve(res http.ResponseWriter, req *http.Request){
	 
	http.ServeFile(res, req, "mywebsite.html")

}
			
func main(){
	
	http.HandleFunc("/", serve)
	http.ListenAndServe(":3000", nil)
}

Make sure to create an html file with anything inside it for now.

Run it with go and you’ll see your html file served on localhost:3000.

$ go run app.go


Now let’s create a struct that contains the variables we’ll pass into our templates.

type Variables struct{
	Title string
	Heading string
}

Modify the html file to insert those variables later on.

<!--website.html-->
<head>
	<title> {{ .Title }} </title>
</head>

<h1> {{ .Heading }} </h1>


Import html/template

import "html"/template

Create a new template

var templates = template.Must(template.ParseFiles("mywebsite.html"))

template.Must() Checks your template for syntax errors.

template.ParseFiles() Creates a new template from multiple files. Only one in this case but adding more simply requires including a comma with another filename.


Create a new struct and serve the template using the struct variables.

myVars := Variables{"My Website Title", "My Website Heading"}

templates.ExecuteTemplate(res, "mywebsite.html", myVars)

templates.ExecuteTemplate() Handles combining the variables and the template and then serves it to the client. First parameter is http.ResponseWriter, second is the name of the filename of the template, and third is the struct.


Complete code:

//app.go

package main

import "net/http"
import "html"/template

type Variables struct{
	Title string
	Heading string
}

var templates = template.Must(template.ParseFiles("mywebsite.html"))

func serve(res http.ResponseWriter, req *http.Request){
	 
	myVars := Variables{"My Website Title", "My Website Heading"}
	
	templates.ExecuteTemplate(res, "mywebsite.html", myVars)

}
			
func main(){
	
	http.HandleFunc("/", serve)
	http.ListenAndServe(":3000", nil)
}


Resources: