Web Dev With Go 2

Web Dev With Go - Section 3

package main

import (
	"fmt"
	"net/http"

	"github.com/go-chi/chi/v5"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	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:example@example.test\"> exampke@example.test </a>.")
}

func faqHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(w, `<h1>  FAG Page </h1><p> Why blah bla bla blah? When yada, yada, yada.. </a>.
	`)
}

func main() {

	r := chi.NewRouter()
	r.Get("/", homeHandler)
	r.Get("/contact", contactHandler)
	r.Get("/faq", faqHandler)
	r.NotFound(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "Page Not Found", http.StatusNotFound)
	})

	fmt.Println("Starting the server on :3000...")
	http.ListenAndServe(":3000", r)

}

Notes

  • Here I used the Chi library. Before being able to actually call anything from the library, it was necessary to “go get” this within the go module, here is how it looks:
go get -u github.com/go-chi/chi/v5
go: downloading github.com/go-chi/chi/v5 v5.0.8
go: downloading github.com/go-chi/chi v1.5.4
go: added github.com/go-chi/chi/v5 v5.0.8
  • The previous command just added this to the go module, and then I could invoke their router. Pretty much the same than in previous sections of the course.

 Share!

 
comments powered by Disqus