Custom Routing (With If statements and Switch) - Go
Here is a basic example about how to do custom routing with if statements:
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 pathHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
homeHandler(w, r)
} else if r.URL.Path == "/contact" {
contactHandler(w, r)
}
}
func main() {
http.HandleFunc("/", pathHandler)
fmt.Println("Starting the server on :3000...")
http.ListenAndServe(":3000", nil)
}
Also, I could acomplish this by using a “switch”:
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 pathHandler(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
homeHandler(w, r)
case "/contact":
contactHandler(w, r)
default:
// Not found error
}
}
func main() {
http.HandleFunc("/", pathHandler)
fmt.Println("Starting the server on :3000...")
http.ListenAndServe(":3000", nil)
}