Step 1: Install mux package by executing below
command.
go get -u
github.com/gorilla/mux
Step 2: Create App.go with below content.
App.go
package main import ( "net/http" "github.com/gorilla/mux" ) func main() { router := mux.NewRouter() router.HandleFunc("/", HomePageHandler) http.Handle("/", router) http.ListenAndServe(":8080", nil) } // HomePageHandler send Hello World message to the client func HomePageHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") dataToWrite := []byte("Hello World") w.Write(dataToWrite) }
Run App.go
and open the url ‘http://localhost:8080/’ in browser, you can see below screen.
router := mux.NewRouter()
Above
statement gets new router instance. Router is responsible to send given request
to corresponding http handler.
router.HandleFunc("/",
HomePageHandler)
Above
statement maps the home page to HomePageHandler function. 'HomePageHandler'
handler function implemented like below.
func
HomePageHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type",
"text/html")
dataToWrite := []byte("Hello
World")
w.Write(dataToWrite)
}
http.Handle("/", router)
Above
statement register all the requests to the given router.
http.ListenAndServe(":8080",
nil)
Above
statement makes the http application to listen on port 8080.
No comments:
Post a Comment