//+build linux

package main

import (
	"net"
	"qipai/proxy_gate/log"
	"syscall"

	"github.com/valyala/tcplisten"
	"go.uber.org/zap"
)

var cfg = tcplisten.Config{
	ReusePort: true, DeferAccept: true, FastOpen: true, Backlog: 0,
}

func listen(addr string) (net.Listener, error) {
	err := setMaxConn()
	if err != nil {
		return nil, err
	}

	return cfg.NewListener("tcp4", addr)
}

func setMaxConn() error {
	var RLimit syscall.Rlimit
	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &RLimit)
	if err != nil {
		return err
	}
	log.Info("get setrlimit success", zap.Uint64("cur", RLimit.Cur), zap.Uint64("max", RLimit.Max))
	RLimit.Cur = 800000
	RLimit.Max = 800000
	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &RLimit)
	if err != nil {
		return err
	}
	err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &RLimit)
	if err != nil {
		return err
	}
	log.Info("set setrlimit success", zap.Uint64("cur", RLimit.Cur), zap.Uint64("max", RLimit.Max))
	return nil
}
