github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/25_ants/http_use/main.go (about)

     1  package main
     2  
     3  import (
     4  	"github.com/panjf2000/ants/v2"
     5  	"io/ioutil"
     6  	"net/http"
     7  )
     8  
     9  type Request struct {
    10  	Param  []byte
    11  	Result chan []byte
    12  }
    13  
    14  func poolfunc(payload interface{}) {
    15  	request, ok := payload.(*Request)
    16  	if !ok {
    17  		return
    18  	}
    19  	reverseParam := func(s []byte) []byte {
    20  		for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
    21  			s[i], s[j] = s[j], s[i]
    22  		}
    23  		return s
    24  	}(request.Param)
    25  
    26  	request.Result <- reverseParam
    27  }
    28  func main() {
    29  
    30  	//ants.NewPool(100)
    31  	pool, _ := ants.NewPoolWithFunc(1, poolfunc, ants.WithPreAlloc(true))
    32  
    33  	defer pool.Release()
    34  	//pool.Tune(10)
    35  	http.HandleFunc("/reverse", func(w http.ResponseWriter, r *http.Request) {
    36  		param, err := ioutil.ReadAll(r.Body)
    37  		if err != nil {
    38  			http.Error(w, "request error", http.StatusInternalServerError)
    39  		}
    40  		defer r.Body.Close()
    41  
    42  		request := &Request{Param: param, Result: make(chan []byte)}
    43  
    44  		// Throttle the requests traffic with ants pool. This process is asynchronous and
    45  		// you can receive a result from the channel defined outside.
    46  		if err := pool.Invoke(request); err != nil {
    47  			http.Error(w, "throttle limit error", http.StatusInternalServerError)
    48  		}
    49  
    50  		w.Write(<-request.Result)
    51  	})
    52  	_ = http.ListenAndServe(":8080", nil)
    53  }