Basic Authentication in GoLang Rest API

This project will demonstrate how to Use Basic Authentication in GoLang Rest API

  • GoLangRESTfulAPI
    • src
      • apis
        • demoapi
          • api1.api.go
          • api2.api.go
      • middlewares
        • basicauthmiddleware
          • basicauth.middleware.go
      • main.go
package demoapi

import (
    "fmt"
    "net/http"
)

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

import (
    "fmt"
    "net/http"
)

func Demo2API(response http.ResponseWriter, request *http.Request) {
    fmt.Fprint(response, "Demo 2 API")
}
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"
}
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)
    }
}

Screenshots