Adding Contact Page With Go Handler

Adding Another Page With Go Handlers

To add another page, we added another “handler”.

Notice how each path is associated with a “handler”:

/ = homeHandler

/contact = contactHandler


Here is the source code:

package main

import (
	"fmt"
	"net/http"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Add("Fake", "my fake header")
	fmt.Fprint(w, "<h1> Welcome to my site </h1>")
}

func contactHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(w, "<h1>  Contact Page </h1><p> To get in touch, email me at <a href=\"mailto:rabocse@alexrabocse.me\"> rabocse@alexrabocse.me </a>.")
}

func main() {

	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/contact", contactHandler)
	fmt.Println("Starting the server on :3000...")
	http.ListenAndServe(":3000", nil)

}

Here is a quick verification with “curl”:

❯ curl localhost:3000/contact
<h1>  Contact Page </h1><p> To get in touch, email me at <a href="mailto:rabocse@alexrabocse.me"> rabocse@alexrabocse.me </a>.

❯ curl localhost:3000/
<h1> Welcome to my site </h1>

 Share!

 
comments powered by Disqus