golang实现http的ip限流代码

代码语言:golang

所属分类:其他

代码描述:golang实现http的ip限流代码,完全有chatgpt编写和修复bug异常,按照你的指令自动生成代码。

代码标签: chatgpt golang http 代码 ip 限流

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

package main

import (
	"fmt"
	"net"
	"net/http"
	"sync"
	"time"
)

type IPCounter struct {
	mu      sync.Mutex
	counter map[string]int
}

func (c *IPCounter) Incr(ip string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.counter[ip]++
}

func (c *IPCounter) Count(ip string) int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.counter[ip]
}

func main() {
	counter := &IPCounter{counter: make(map[string]int)}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		ip, _, err := net.SplitHostPort(r.RemoteAddr)
		if err != nil {
			http.Error(.........完整代码请登录后点击上方下载按钮下载查看

网友评论0