This Golang tutorial help to create http rest call using mux package. I am not using any framework, Its use only core golang programming to create http rest call.

I am creating a rest call that will take id as parameters and return as a json data, Next tutorial will have how to handle JSON data with Golang http package.

The MUX package is the powerful URL router and dispatcher for golang application. I have already shared How To Consume Restful APIs with Echo Golang. They are using ECHO web framework but this tutorial do not use any framework.

We are using core go package like "net/http" and "mux" to create HTTP rest call.

Step 1: We will create main.go package file, Now import packages into top of the file.

"net/http"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"

We have included http package for HTTP client and server implementations, Which also supports Get, Head, Post, and PostForm make HTTP (or HTTPS) requests.

The MUX package for URL router and dispatcher.Logrus package help for structured logger in Go.

Step 2: We will create mux package instance and handler.

routes := mux.NewRouter()
routes.HandleFunc("/employee/{id}", HomeHandler).Methods("GET")

Step 3: We will create HomeHandler method to handle http request.

func HomeHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
fmt.Println("hello, I am home controller!")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Employee: %v\n", vars["id"])
}

Step 4: Added Http handle method handle mux dispatcher.

http.Handle("/", routes)

Genislab Technologies

NexGeneration complete end-2-end software testing & modern development operations tooling & solutions

Do you want to discuss your testing requirements with us? please don’t hesitate to hit the contact us button below, and we will get back to you at our earliest..