SoFunction
Updated on 2025-03-03

Golang implements IP access restrictions and number of submissions

In web applications, it is usually necessary to limit IP access and control the number of submissions to prevent malicious attacks (such as brute force, DoS attacks, API abuse, etc.). To achieve this function, we can combine Golang's features to use middleware or caching services such as Redis to control IP restrictions and number of submissions.

Implementation steps

  • IP access restrictions: Limit the access frequency of each IP, for example, each IP can only access a certain interface 10 times per minute. After the limit is exceeded, an error message is returned (for example, 429 Too Many Requests).
  • Submission limit: Prevent brute-force cracking or abuse of interfaces by limiting the number of submissions of a certain IP within a certain time period.
  • Redis (or other storage system) as a counter: To better achieve this limitation, cache systems such as Redis can be used to store IP access records, number of submissions, etc., because Redis's performance and ease of use make it an ideal choice.

Core concept

  • Rate Limiting (current limit): Limit the number of visits within a certain period of time according to IP.
  • Count of requests: Count each IP and determine whether the limit is exceeded based on the count.
  • Time Window: Set a certain time window (such as one minute or five minutes) to count the number of IP accesses during this time period.

Use Golang and Redis to implement IP access restrictions and submission restrictions

Here we use Redis to store and control the number of accesses, and combine Go to implement a simple IP access restriction middleware.

Dependency library

You can use Redis's official Go clientgo-redisto connect Redis to operate. Install this library first:

go get /go-redis/redis/v8

Implement code

The following code demonstrates how to use Redis to implement IP access restrictions and submission restrictions.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	"/go-redis/redis/v8"
)

// Redis client
var rdb *

// Initialize the Redis clientfunc initRedis() {
	rdb = (&{
		Addr:     "localhost:6379", // Redis Address		Password: "",               // Redis password (if any)		DB:       0,                // Used Redis database	})
}

// Get the client's IP addressfunc getIP(r *) string {
	// Try to get the real IP from X-Forwarded-For or X-Real-IP	ip := ("X-Forwarded-For")
	if ip == "" {
		ip = ("X-Real-IP")
	}
	if ip == "" {
		ip = 
	}
	return ip
}

// Middleware: IP access restrictionsfunc rateLimitMiddleware(next )  {
	return func(w , r *) {
		ctx := ()
		ip := getIP(r)
		key := "rate_limit:" + ip

		// Get the number of visits in Redis		count, err := (ctx, key).Result()
		if err ==  {
			// If there is no record, set the count to 1 and set the expiration time			err := (ctx, key, 1, ).Err() // 1 minute limit			if err != nil {
				(w, "Redis error", )
				return
			}
		} else if err != nil {
			(w, "Redis error", )
			return
		} else {
			// Convert accesses to integers			countInt, _ := (count)
			if countInt >= 10 { // Assume that the limit is up to 10 times per minute				(w, "Too Many Requests", )
				return
			}

			// Increment count			(ctx, key)
		}

		(w, r)
	}
}

// Sample Processor: Submit Processingfunc submitHandler(w , r *) {
	(w, "Request successful")
}

func main() {
	// Initialize Redis	initRedis()

	// Create an HTTP server and add middleware	("/submit", rateLimitMiddleware(submitHandler))

	("Server is running on port 8080...")
	(":8080", nil)
}

Code parsing

Redis client initialization

  • use()Initialize the Redis client.
  • pass()and()To operate the counter in Redis.

IP acquisition

passgetIP()The function gets the requested client IP address. The function tries toX-Forwarded-FororX-Real-IPGet the real IP. If not, useRemoteAddr

Rate Limiting Middleware

  • rateLimitMiddleware()It is the core middleware function, responsible for limiting the number of accesses per IP. It uses Redis to store access counts and current limit time windows for each IP (set to 1 minute here).
  • When the number of IP accesses exceeds the limit, the HTTP status code is returned429 Too Many Requests

Processing a request

  • submitHandler()is a simple example processor that handles successful requests.
  • access/submitWhen the middleware restriction is passed, it returns "Request successful" under normal circumstances.

Improvements and extensions

  • Dynamic adjustment of current limiting strategy: The current limiting strategy can be dynamically adjusted according to different user types and different API paths. For example, VIP users may have higher access frequency.
  • IP blacklist: Maintain a blacklist through Redis or other storage systems. If you encounter IPs in the blacklist, you can directly reject the request.
  • Current limiting algorithm by time window: You can use more complex current limiting algorithms such as sliding windows, leaky bucket algorithms, and token bucket algorithms to achieve more flexible control.
  • Using the Redis Expire feature: Used in RedisSetEX(key setting with expiration time) orTTLTo ensure that the counter can be reset automatically and avoid manual management.
  • Logging and alarm: You can combine the log system to record logs or send alarm information when a certain IP frequently triggers restrictions.

The combination of Golang and Redis allows easy control of IP access restrictions and submission counts. Redis's high performance features make it ideal for use as storage for current limiting counters. In practical applications, the solution can be expanded as needed, such as using different current limiting algorithms, combining IP blacklists, etc.

This is the article about Golang's implementation of IP access restrictions and number of submissions. For more related content on Golang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!