How to create API using mux in Golang

How to create simple API using golang and mux package


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

Basic setup

To build basic API in Golang we need two packages

go get github.com/gorilla/mux

Mux help us to build API routes . In the main.go file add the following

package main

import  
("github.com/gorilla/mux"
"net/http"
"fmt")

// album represents data about a record album.
type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}

// albums slice to seed record album data.
var albums = []album{
    {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
    {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
    {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
  

func index(w http.ResponseWriter, r *http.Request){
 fmt.Fprint(w,"Hello world!")
}

func getAlbums(w http.ResponseWriter, r *http.Request){
 fmt.Fprint(w,albums)
}
func main(){
	r:=mux.NewRouter()
	r.HandleFunc("/",index).Methods("GET")
	r.HandleFunc("/albums",getAlbums)
	fmt.Println("Server starting")
	http.ListenAndServe(":8080",r)

	 }

Here we create a mux router instance which can be used to create API route. We also define handler function for the API too.

:= is the short hand in Golang for creating variables

Run the project

By using go run . or go run main.go can execute the program.

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.