Golang URL Router Using Gorilla Mux - Golang Web Development

Опубликовано: 08 Ноябрь 2024
на канале: Maharlikans Code
1,111
15

In this Golang Web Development Series #9, we will learn on how Golang URL router works using Gorilla Mux package with step by step guide here in Golang's Web Development Series.

Get Linode Account:
https://www.linode.com/?r=6aae17162e9...

Maharlikans Code Github:
https://github.com/maharlikanscode/go...

#MaharlikansCode
#GolangWebDevelopment9
#GolangURLRouter
#GolangGorillaMux
#GorillaMux
#GolangTutorial
#LearnGolangWebDevelopment
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper

If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode

Gorilla Mux: https://github.com/gorilla/mux

Stream Dashboard UI Kit (MIT License):
https://htmlstream.com/templates/stre...

Source Codes:
package api

import (
"fmt"
"gowebapp/config"
"html/template"
"net/http"

"github.com/gorilla/csrf"
"github.com/gorilla/mux"
)

// MainRouters are the collection of all URLs for the Main App.
func MainRouters(r *mux.Router) {
r.HandleFunc("/", Home).Methods("GET")
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/product/{product_name}/{id:[0-9]+}", ProductInfo)
}

// contextData are the most widely use common variables for each pages to load.
type contextData map[string]interface{}

// Home function is to render the homepage page.
func Home(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles(config.SiteRootTemplate+"front/index.html", config.SiteHeaderTemplate, config.SiteFooterTemplate))

data := contextData{
"PageTitle": "Welcome to Maharlikans Code Tutorial Series",
"PageMetaDesc": config.SiteSlogan,
"CanonicalURL": r.RequestURI,
"CsrfToken": csrf.Token(r),
"Settings": config.SiteSettings,
}
tmpl.Execute(w, data)
}

// ArticlesCategoryHandler ...
func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\n", vars["category"])
}

// ProductInfo ...
func ProductInfo(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Product Name: %v\n", vars["product_name"])
fmt.Fprintf(w, "Product ID: %v\n", vars["id"])
}