Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Building a RESTful API in Go Using Mux and Logrus

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 webframework 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)

The post Building a RESTful API in Go Using Mux and Logrus appeared first on Rest Api Example.



This post first appeared on Rest Api Example, please read the originial post: here

Share the post

Building a RESTful API in Go Using Mux and Logrus

×

Subscribe to Rest Api Example

Get updates delivered right to your inbox!

Thank you for your subscription

×