Thursday, 16 May 2019

Mux: Path variables


Url pattern can have path variables.

For example, you can define a pattern like "/welcome/{name}" and all the below examples are valid for above pattern.

"/welcome/krishna" : Here name is assigned to value Krishna
"/welcome/Ram" : Here name is assigned to value Ram
"/welcome/Alex" : Here name is assigned to value Alex

How to access the value of path variable?
'mux.Vars' function takes http.Request as argument and return all the route variables.

Example
vars := mux.Vars(request)
userName := vars["name"]

App.go
package main

import (
 "net/http"

 "github.com/gorilla/mux"
)

func main() {
 router := mux.NewRouter()

 router.HandleFunc("/", HomePageHandler)
 router.HandleFunc("/welcome/{name}", WelcomeUser)

 http.Handle("/", router)
 http.ListenAndServe(":8080", nil)
}

// HomePageHandler send Hello World message to the client
func HomePageHandler(writer http.ResponseWriter, request *http.Request) {
 dataToWrite := []byte("Hello World")

 writer.Header().Set("Content-Type", "text/html")
 writer.Write(dataToWrite)
}

//WelcomeUser display welcome message to given user
func WelcomeUser(writer http.ResponseWriter, request *http.Request) {
 vars := mux.Vars(request)

 userName := vars["name"]

 dataToWrite := []byte("Hello " + userName + ", Welcome to Go language")

 writer.Header().Set("Content-Type", "text/html")
 writer.Write(dataToWrite)
}

Run App.go and open the url ‘http://localhost:8080/welcome/Krishna’ in browser, you can see below screen.


Previous                                                 Next                                                 Home

No comments:

Post a Comment