You can do this using the html/template package in the Go standard library.
The basic process here is:
- Write a template (in go/HTML template language)
- Read in the template (using
template.ParseFiles
or similar)
- Listen for requests
- Pass information from relevant requests to your template (using
ExecuteTemplate
or similar)
You can pass a struct to ExecuteTemplate
, which is then accessible in the template you define (see below for an example). For example, if your struct has a field called Name
, then you can access this information in the template with {{ .Name }}
.
Here is a sample:
main.go:
package main
import (
"log"
"encoding/json"
"html/template"
"net/http"
)
var tpl *template.Template
func init() {
// Read your template(s) into the program
tpl = template.Must(template.ParseFiles("index.gohtml"))
}
func main() {
// Set up routes
http.HandleFunc("/endpoint", EndpointHandler)
http.ListenAndServe(":8080", nil)
}
// define the expected structure of payloads
type Payload struct {
Name string `json:"name"`
Hobby string `json:"hobby"`
}
func EndpointHandler(w http.ResponseWriter, r *http.Request) {
// Read the body from the request into a Payload struct
var payload Payload
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
log.Fatal(err)
}
// Pass payload as the data to give to index.gohtml and write to your ResponseWriter
w.Header().Set("Content-Type", "text/html")
tpl.ExecuteTemplate(w, "index.gohtml", payload)
}
index.gohtml:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<span>Your name is</span><span>{{ .Name }}</span>
</div>
<div>
<span>Your hobby is</span><span>{{ .Hobby }}</span>
</div>
</body>
</html>
Sample:
With payload:
{
"name": "Ahmed",
"hobby": "devving"
}
Response:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<span>Your name is</span>
<span>Ahmed</span>
</div>
<div>
<span>Your hobby is</span>
<span>devving</span>
</div>
</body>
</html>
Note this is pretty fragile, so you should definitely add better error and edge-case handling, but hopefully this is a helpful starting point.