Golang

 

Introduction

A Basic Authentication System is a fundamental security mechanism used for verifying the identity of a user. It is often employed in web applications to ensure that only authorized individuals can access certain features. In this tutorial, we will build a simple authentication system using the Go programming language. We will cover both user registration and login functionality, storing user credentials in memory (simulating a database).

Objective

The goal of this project is to create a simple authentication system that allows users to register by providing a username and password, and log in using their credentials. This will help demonstrate how to implement basic security features and manage user authentication in a Go application.

Go Program Code

package main

import (
    "fmt"
    "log"
    "net/http"
    "strings"
)

var users = make(map[string]string)

func register(w http.ResponseWriter, r *http.Request) {
    if r.Method == http.MethodPost {
        username := r.FormValue("username")
        password := r.FormValue("password")
        if username == "" || password == "" {
            http.Error(w, "Username and Password cannot be empty", http.StatusBadRequest)
            return
        }
        users[username] = password
        fmt.Fprintf(w, "Registration successful! You can now log in.")
    } else {
        http.ServeFile(w, r, "register.html")
    }
}

func login(w http.ResponseWriter, r *http.Request) {
    if r.Method == http.MethodPost {
        username := r.FormValue("username")
        password := r.FormValue("password")
        storedPassword, exists := users[username]
        if !exists || storedPassword != password {
            http.Error(w, "Invalid username or password", http.StatusUnauthorized)
            return
        }
        fmt.Fprintf(w, "Login successful! Welcome, %s.", username)
    } else {
        http.ServeFile(w, r, "login.html")
    }
}

func main() {
    http.HandleFunc("/register", register)
    http.HandleFunc("/login", login)

    fmt.Println("Server is running on http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Explanation of the Program

This program defines a simple HTTP server using the Go standard library. It handles two main routes:

  • /register: Allows users to register by providing a username and password. The credentials are stored in the users map, simulating a database.
  • /login: Allows users to log in using the username and password they registered with. If the login is successful, a welcome message is shown. If not, an error message is returned.

The program uses the http package to handle HTTP requests and responses. The register.html and login.html files should contain simple HTML forms to collect the user input. Here is a sample HTML form for registration:

<!-- register.html -->
<html>
  <body>
    <h2>Register</h2>
    <form action="/register" method="post">
      <label>Username: </label><input type="text" name="username"><br>
      <label>Password: </label><input type="password" name="password"><br>
      <input type="submit" value="Register">
    </form>
  </body>
</html>

Similarly, you can create a simple login.html form for user login.

How to Run the Program

  1. Ensure you have Go installed on your machine. If not, download and install it from here.
  2. Create a new directory for your project and create a Go file, e.g., main.go.
  3. Copy and paste the Go code provided above into main.go.
  4. Create the register.html and login.html files in the same directory.
  5. Open a terminal or command prompt, navigate to the project directory, and run the command: go run main.go.
  6. Open a web browser and go to http://localhost:8080/register to start the registration process.
  7. After registration, you can log in at http://localhost:8080/login.
© 2025 Learn Programming. All Rights Reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)