Basic Authentication in GoLang RESTful Web API

Make sure Git is installed on your machine and in your system’s PATH. Install the packages to your $GOPATH with the go tool from shell:

$ go get -u github.com/gorilla/mux
$ go get -u github.com/gorilla/handlers




In src folder, create new folder named apis. In this folder, create new web folder named demoapi. In demoapi folder, create new apis as below:

In demoapi folder, create new go file named api1.api.go as below:

package demoapi

import (
	"fmt"
	"net/http"
)

func Demo1API(response http.ResponseWriter, request *http.Request) {
	fmt.Fprint(response, "Demo 1 API")
}

In demoapi folder, create new go file named api2.api.go as below:

package demoapi

import (
	"fmt"
	"net/http"
)

func Demo2API(response http.ResponseWriter, request *http.Request) {
	fmt.Fprint(response, "Demo 2 API")
}




In src folder, create new folder named middlewares. In this folder, create new middlewares as below:

In middlewares folder, create new folder named basicauthmiddleware. In basicauthmiddleware folder, create new go file named basicauth.middleware.go as below:

package basicauthmiddleware

import (
	"fmt"
	"net/http"
)

func BasicAuthMiddleware(handler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		user, pass, ok := r.BasicAuth()
		fmt.Println("username: ", user)
		fmt.Println("password: ", pass)
		if !ok || !checkUsernameAndPassword(user, pass) {
			w.Header().Set("WWW-Authenticate", `Basic realm="Please enter your username and password for this site"`)
			w.WriteHeader(401)
			w.Write([]byte("Unauthorised.\n"))
			return
		}
		handler(w, r)
	}
}

func checkUsernameAndPassword(username, password string) bool {
	return username == "abc" && password == "123"
}




In src folder, create new file named main.go as below and use go run main.go command to run program:

package main

import (
	"apis/demoapi"
	"fmt"
	"middlewares/basicauthmiddleware"
	"net/http"

	"github.com/gorilla/mux"
)

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

	router.Handle("/api/demo/demo1", basicauthmiddleware.BasicAuthMiddleware(http.HandlerFunc(demoapi.Demo1API))).Methods("GET")

	router.HandleFunc("/api/demo/demo2", demoapi.Demo2API).Methods("GET")

	err := http.ListenAndServe(":3000", router)
	if err != nil {
		fmt.Println(err)
	}
}




Use PostMan Tool test api 1 web api with url: http://localhost:3000/api/demo/demo1 and use No Auth option as below:

Use PostMan Tool test api 1 web api with url: http://localhost:3000/api/demo/demo1 and use Basic Auth option with incorrect account as below:

Use PostMan Tool test api 1 web api with url: http://localhost:3000/api/demo/demo1 and use Basic Auth option with correct account as below:

Use PostMan Tool test api 2 web api with url: http://localhost:3000/api/demo/demo2