htmlgogo-html-templatego-httpgo-server

html renderer in Golang without third party imports


I am self-teaching myself go and I have started experimenting with using go as a back end.

I have the following code which renders HTML pages, but I am looking for a solution that doesn't rely on a third party import to get a better grasp of what is going on and what needs to be done.

package main

import (
    "log"
    "net/http"

    "github.com/thedevsaddam/renderer"
)

var rnd *renderer.Render

func init() {
    opts := renderer.Options{
        ParseGlobPattern: "./pages/*.gohtml",
    }
    rnd = renderer.New(opts)
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", home)
    mux.HandleFunc("/about", about)
    port := ":9000"
    log.Println("Listening on port ", port)
    http.ListenAndServe(port, mux)
}

func home(w http.ResponseWriter, r *http.Request) {
    rnd.HTML(w, http.StatusOK, "home", nil)
}

func about(w http.ResponseWriter, r *http.Request) {
    rnd.HTML(w, http.StatusOK, "about", nil)
}

the GOHTML files are:

{{ define "home"}}
<!DOCTYPE html>
<html>
<head>
  <title>Home</title>
</head>
<body>
  <h1>HOME</h1>
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/about">About</a></li>
  </ul>
</body>
</html>
{{ end }}
{{ define "about" }}
<!DOCTYPE html>
<html>
<head>
  <title>About</title>
</head>
<body>
  <h1>ABOUT</h1>
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/about">About</a></li>
  </ul>
</body>
</html>
{{ end }}

Any help is greatly appreciated


Solution

  • Use the html/template package from the standard library. The renderer you are using is just a thin wrapper around that.