Post

Go HandlerFunc() review

A review of Go's http.HandlerFunc adapter, showing how to use it with http.Handle to register handler functions and render templates.

This example revisits http.HandlerFunc in Go. Instead of using http.HandleFunc (which accepts a plain function), this program wraps handler functions with http.HandlerFunc(dogs) and passes them to http.Handle. The handlers render HTML templates using tpl.ExecuteTemplate, demonstrating how to combine template rendering with the Handler interface pattern.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main

import (
	"html/template"
	"net/http"
)

var tpl *template.Template

func init() {
	tpl = template.Must(template.ParseFiles("index.gohtml"))
}

func dogs(w http.ResponseWriter, r *http.Request) {
	// io.WriteString(w, "This is the web about dogs!\n")
	data := `This is the web about dogs!\n`
	w.Header().Set("Content-type", "text/html")
	tpl.ExecuteTemplate(w, "index.gohtml", data)
}

func me(w http.ResponseWriter, r *http.Request) {
	// io.WriteString(w, "This is the web about me!\n")
	data := `This is the web about me!\n`
	tpl.ExecuteTemplate(w, "index.gohtml", data)
}

func about(w http.ResponseWriter, r *http.Request) {
	// io.WriteString(w, "About!\n")
	data := `About me!\n`
	tpl.ExecuteTemplate(w, "index.gohtml", data)
}

func main() {

	// http.HandleFunc("/dogs/", dogs)
	// http.HandleFunc("/me/", me)
	// http.HandleFunc("/", about)
	http.Handle("/dogs/", http.HandlerFunc(dogs))
	http.Handle("/me/", http.HandlerFunc(me))
	http.Handle("/", http.HandlerFunc(about))


	http.ListenAndServe(":8080", nil)

}

This post is licensed under CC BY 4.0 by the author.