search
HomeBackend DevelopmentGolangBuild an OTP-Based Authentication Server with Go: Part 1

Build an OTP-Based Authentication Server with Go: Part 1

Getting Started

Begin by creating a new folder for your project and initialize a Go module with the following command:

go mod init github.com/vishaaxl/cheershare

Set up the Project Structure

Start by setting up a new Go project with the following folder structure:

my-otp-auth-server/
├── cmd/
│   └── api/
│       └── main.go
│       └── user.go
│       └── token.go
├── internal/
│   └── data/
│       ├── models.go
│       └── user.go
│       └── token.go
├── docker-compose.yml
├── go.mod
└── Makefile

Next, set up your docker-compose.yml file. This configuration will define the services—PostgreSQL and Redis—that you'll be working with throughout this tutorial.

Setting Up Services with Docker Compose

We will start by configuring the services required for our project. For the backend, we need the following:

  • Redis: We'll use the redis:6 image. This service will configure a password for secure access, expose port 6379, and enforce password authentication using the --requirepass flag to secure Redis access.

  • PostgreSQL: We'll use the postgres:13 image. The service will define a default user, password, and database, expose port 5432 for communication, and persist data with a named volume (postgres_data) to ensure durability.

Optional:

  • Main Backend Service: You can define the main backend service here as well, which will interact with both PostgreSQL and Redis.
// docker-compose.yml
services:
  postgres:
    image: postgres:13
    container_name: postgres
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: mysecretpassword
      POSTGRES_DB: cheershare
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:6
    container_name: redis
    environment:
      REDIS_PASSWORD: mysecretpassword
    ports:
      - "6379:6379"
    command: ["redis-server", "--requirepass", "mysecretpassword"]

volumes:
  postgres_data:

Main Backend Service

For routing and handling HTTP requests, we’ll use the github.com/julienschmidt/httprouter package. To install the dependency, run the following command:

go get github.com/julienschmidt/httprouter

Next, create a file at cmd/api/main.go and paste the following code. An explanation for each line is provided in the comments:

//  main.go
package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "time"

    "github.com/julienschmidt/httprouter"
)

/*
config struct:
- Holds application-wide configuration settings such as:
  - `port`: The port number on which the server will listen.
  - `env`: The current environment (e.g., "development", "production").
*/
type config struct {
    port int
    env  string
}

/*
applications struct:
- Encapsulates the application's dependencies, including:
  - `config`: The application's configuration settings.
  - `logger`: A logger instance to handle log messages.
*/
type applications struct {
    config config
    logger *log.Logger
}

func main() {
    cfg := &config{
        port: 4000,
        env:  "development",
    }

    logger := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)

    app := &applications{
        config: *cfg,
        logger: logger,
    }

    router := httprouter.New()

    router.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
        w.WriteHeader(http.StatusOK)
        fmt.Fprintln(w, "Welcome to the Go application!")
    })

    /*
        Initialize the HTTP server
        - Set the server's address to listen on the specified port.
        - Assign the router as the handler.
        - Configure timeouts for idle, read, and write operations.
        - Set up an error logger to capture server errors.
    */
    srv := &http.Server{
        Addr:         fmt.Sprintf(":%d", app.config.port),
        Handler:      router,
        IdleTimeout:  time.Minute,
        ReadTimeout:  10 * time.Second,
        WriteTimeout: 30 * time.Second,
    }

    app.logger.Printf("Starting server on port %d in %s mode", app.config.port, app.config.env)

    err := srv.ListenAndServe()
    if err != nil {
        app.logger.Fatalf("Could not start server: %s", err)
    }
}

Right now, you can test your setup by starting out server using go run ./cmd/api and sending a request to http://localhost:4000, which will return a welcome message. Next, we’ll define three additional routes to implement our core functionality:

  1. /send-otp: This route will handle sending OTPs to users. It will generate a unique OTP, store it in Redis, and deliver it to the user.

  2. /verify-otp: This route will verify the OTP provided by the user. It will check against the value stored in Redis to confirm the user's identity.

  3. /login: This route will handle user login functionality once the OTP is verified and user is successfully created.

But before we continue, we need a way to store user information like phone number and their one-time password for which we need to connect to the services we defined earlier in the docker-compose.yml file.

Defining Helper Functions

Before implementing the routes, let’s define two essential helper functions. These functions will handle connections to the Redis and PostgreSQL servers, ensuring that our backend can interact with these services.

Modify the 'config' struct to store information about the services. These functions are pretty self-explanatory.

my-otp-auth-server/
├── cmd/
│   └── api/
│       └── main.go
│       └── user.go
│       └── token.go
├── internal/
│   └── data/
│       ├── models.go
│       └── user.go
│       └── token.go
├── docker-compose.yml
├── go.mod
└── Makefile

You can use these functions to establish a connection to the PostgreSQL database and Redis server after starting the services with the docker-compose up -d command.

In the next part, we'll start working on those routes we talked about earlier. This is what your main.go file should look like now.

// docker-compose.yml
services:
  postgres:
    image: postgres:13
    container_name: postgres
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: mysecretpassword
      POSTGRES_DB: cheershare
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:6
    container_name: redis
    environment:
      REDIS_PASSWORD: mysecretpassword
    ports:
      - "6379:6379"
    command: ["redis-server", "--requirepass", "mysecretpassword"]

volumes:
  postgres_data:

The above is the detailed content of Build an OTP-Based Authentication Server with Go: Part 1. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Golang vs. Python: Concurrency and MultithreadingGolang vs. Python: Concurrency and MultithreadingApr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Golang and C  : The Trade-offs in PerformanceGolang and C : The Trade-offs in PerformanceApr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Golang vs. Python: Applications and Use CasesGolang vs. Python: Applications and Use CasesApr 17, 2025 am 12:17 AM

ChooseGolangforhighperformanceandconcurrency,idealforbackendservicesandnetworkprogramming;selectPythonforrapiddevelopment,datascience,andmachinelearningduetoitsversatilityandextensivelibraries.

Golang vs. Python: Key Differences and SimilaritiesGolang vs. Python: Key Differences and SimilaritiesApr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang vs. Python: Ease of Use and Learning CurveGolang vs. Python: Ease of Use and Learning CurveApr 17, 2025 am 12:12 AM

In what aspects are Golang and Python easier to use and have a smoother learning curve? Golang is more suitable for high concurrency and high performance needs, and the learning curve is relatively gentle for developers with C language background. Python is more suitable for data science and rapid prototyping, and the learning curve is very smooth for beginners.

The Performance Race: Golang vs. CThe Performance Race: Golang vs. CApr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang vs. C  : Code Examples and Performance AnalysisGolang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AM

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version