Refactor: cache use generics

This commit is contained in:
yaling888
2022-04-05 23:29:52 +08:00
committed by Meta
parent 673541e2a8
commit baa9e02af6
5 changed files with 49 additions and 47 deletions

View File

@ -15,7 +15,7 @@ import (
"github.com/Dreamacro/clash/log"
)
func HandleConn(c net.Conn, in chan<- C.ConnContext, cache *cache.Cache) {
func HandleConn(c net.Conn, in chan<- C.ConnContext, cache *cache.Cache[string, bool]) {
client := newClient(c.RemoteAddr(), in)
defer client.CloseIdleConnections()
@ -98,7 +98,7 @@ func HandleConn(c net.Conn, in chan<- C.ConnContext, cache *cache.Cache) {
conn.Close()
}
func authenticate(request *http.Request, cache *cache.Cache) *http.Response {
func authenticate(request *http.Request, cache *cache.Cache[string, bool]) *http.Response {
authenticator := authStore.Authenticator()
if authenticator != nil {
credential := parseBasicProxyAuthorization(request)
@ -108,13 +108,13 @@ func authenticate(request *http.Request, cache *cache.Cache) *http.Response {
return resp
}
var authed any
if authed = cache.Get(credential); authed == nil {
var authed bool
if authed = cache.Get(credential); !authed {
user, pass, err := decodeBasicProxyAuthorization(credential)
authed = err == nil && authenticator.Verify(user, pass)
cache.Put(credential, authed, time.Minute)
}
if !authed.(bool) {
if !authed {
log.Infoln("Auth failed from %s", request.RemoteAddr)
return responseWith(request, http.StatusForbidden)

View File

@ -40,9 +40,9 @@ func NewWithAuthenticate(addr string, in chan<- C.ConnContext, authenticate bool
return nil, err
}
var c *cache.Cache
var c *cache.Cache[string, bool]
if authenticate {
c = cache.New(time.Second * 30)
c = cache.New[string, bool](time.Second * 30)
}
hl := &Listener{

View File

@ -16,7 +16,7 @@ import (
type Listener struct {
listener net.Listener
addr string
cache *cache.Cache
cache *cache.Cache[string, bool]
closed bool
}
@ -45,7 +45,7 @@ func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
ml := &Listener{
listener: l,
addr: addr,
cache: cache.New(30 * time.Second),
cache: cache.New[string, bool](30 * time.Second),
}
go func() {
for {
@ -63,7 +63,7 @@ func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
return ml, nil
}
func handleConn(conn net.Conn, in chan<- C.ConnContext, cache *cache.Cache) {
func handleConn(conn net.Conn, in chan<- C.ConnContext, cache *cache.Cache[string, bool]) {
conn.(*net.TCPConn).SetKeepAlive(true)
bufConn := N.NewBufferedConn(conn)