golang traffic shaving

模擬 time.Sleep(2 * time.Second)模擬server來不及處理這個request 假設 ddos 攻擊runtime.NumGoroutine() 可以做削峰,也可以防止ddos smallPool = make(chan struct{}, 100) 也可為我們的server做buffer

go
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "runtime"
    "strconv"
    "time"
)

var largePool chan struct{}
var smallPool chan struct{}
var a = 0

//http://localhost:8000/?parameter=value&also=another
func main() {
        smallPool = make(chan struct{}, 100)
        http.HandleFunc("/endpoint-1", handler)
        http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    b, err := ioutil.ReadAll(r.Body)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    fmt.Println("all nowgoroutine :", runtime.NumGoroutine())
    go func() {

        smallPool <- struct{}{}
        defer func() { <-smallPool }() // Let everyone that we are done
        fmt.Println("working!")
        time.Sleep(2 * time.Second)

        fmt.Println("work done")
        processImage(b)
    }()

    a += 1
    if runtime.NumGoroutine() < 20 {
        w.Write([]byte("msg" + strconv.Itoa(a)))
        w.WriteHeader(http.StatusAccepted)
    } else {

        w.WriteHeader(http.StatusNotFound)
        return

    }

}