use std slices package (#4008)

This commit is contained in:
fatedier 2024-02-20 12:01:41 +08:00 committed by GitHub
parent b6361fb143
commit 3e0c78233a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
22 changed files with 75 additions and 84 deletions

View File

@ -18,6 +18,7 @@ jobs:
- uses: actions/setup-go@v5 - uses: actions/setup-go@v5
with: with:
go-version: '1.22' go-version: '1.22'
cache: false
- name: golangci-lint - name: golangci-lint
uses: golangci/golangci-lint-action@v4 uses: golangci/golangci-lint-action@v4
with: with:

View File

@ -15,19 +15,17 @@
package client package client
import ( import (
"cmp"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"net" "net"
"net/http" "net/http"
"os" "os"
"sort" "slices"
"strconv" "strconv"
"strings"
"time" "time"
"github.com/samber/lo"
"github.com/fatedier/frp/client/proxy" "github.com/fatedier/frp/client/proxy"
"github.com/fatedier/frp/pkg/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/config/v1/validation" "github.com/fatedier/frp/pkg/config/v1/validation"
@ -153,7 +151,7 @@ func NewProxyStatusResp(status *proxy.WorkingStatus, serverAddr string) ProxySta
if status.Err == "" { if status.Err == "" {
psr.RemoteAddr = status.RemoteAddr psr.RemoteAddr = status.RemoteAddr
if lo.Contains([]string{"tcp", "udp"}, status.Type) { if slices.Contains([]string{"tcp", "udp"}, status.Type) {
psr.RemoteAddr = serverAddr + psr.RemoteAddr psr.RemoteAddr = serverAddr + psr.RemoteAddr
} }
} }
@ -190,8 +188,8 @@ func (svr *Service) apiStatus(w http.ResponseWriter, _ *http.Request) {
if len(arrs) <= 1 { if len(arrs) <= 1 {
continue continue
} }
sort.Slice(arrs, func(i, j int) bool { slices.SortFunc(arrs, func(a, b ProxyStatusResp) int {
return strings.Compare(arrs[i].Name, arrs[j].Name) < 0 return cmp.Compare(a.Name, b.Name)
}) })
} }
} }

View File

@ -17,8 +17,8 @@ package sub
import ( import (
"fmt" "fmt"
"os" "os"
"slices"
"github.com/samber/lo"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config" "github.com/fatedier/frp/pkg/config"
@ -55,7 +55,7 @@ func init() {
config.RegisterProxyFlags(cmd, c) config.RegisterProxyFlags(cmd, c)
// add sub command for visitor // add sub command for visitor
if lo.Contains(visitorTypes, v1.VisitorType(typ)) { if slices.Contains(visitorTypes, v1.VisitorType(typ)) {
vc := v1.NewVisitorConfigurerByType(v1.VisitorType(typ)) vc := v1.NewVisitorConfigurerByType(v1.VisitorType(typ))
if vc == nil { if vc == nil {
panic("visitor type: " + typ + " not support") panic("visitor type: " + typ + " not support")

2
go.mod
View File

@ -20,7 +20,7 @@ require (
github.com/prometheus/client_golang v1.16.0 github.com/prometheus/client_golang v1.16.0
github.com/quic-go/quic-go v0.41.0 github.com/quic-go/quic-go v0.41.0
github.com/rodaine/table v1.1.0 github.com/rodaine/table v1.1.0
github.com/samber/lo v1.38.1 github.com/samber/lo v1.39.0
github.com/spf13/cobra v1.8.0 github.com/spf13/cobra v1.8.0
github.com/spf13/pflag v1.0.5 github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.8.4 github.com/stretchr/testify v1.8.4

4
go.sum
View File

@ -125,8 +125,8 @@ github.com/rodaine/table v1.1.0/go.mod h1:Qu3q5wi1jTQD6B6HsP6szie/S4w1QUQ8pq22pz
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM= github.com/samber/lo v1.39.0 h1:4gTz1wUhNYLhFSKl6O+8peW0v2F4BCY034GRpU9WnuA=
github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA= github.com/samber/lo v1.39.0/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=

View File

@ -17,9 +17,9 @@ package auth
import ( import (
"context" "context"
"fmt" "fmt"
"slices"
"github.com/coreos/go-oidc/v3/oidc" "github.com/coreos/go-oidc/v3/oidc"
"github.com/samber/lo"
"golang.org/x/oauth2/clientcredentials" "golang.org/x/oauth2/clientcredentials"
v1 "github.com/fatedier/frp/pkg/config/v1" v1 "github.com/fatedier/frp/pkg/config/v1"
@ -70,7 +70,7 @@ func (auth *OidcAuthProvider) SetLogin(loginMsg *msg.Login) (err error) {
} }
func (auth *OidcAuthProvider) SetPing(pingMsg *msg.Ping) (err error) { func (auth *OidcAuthProvider) SetPing(pingMsg *msg.Ping) (err error) {
if !lo.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) {
return nil return nil
} }
@ -79,7 +79,7 @@ func (auth *OidcAuthProvider) SetPing(pingMsg *msg.Ping) (err error) {
} }
func (auth *OidcAuthProvider) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) { func (auth *OidcAuthProvider) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) {
if !lo.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) {
return nil return nil
} }
@ -135,7 +135,7 @@ func (auth *OidcAuthConsumer) verifyPostLoginToken(privilegeKey string) (err err
} }
func (auth *OidcAuthConsumer) VerifyPing(pingMsg *msg.Ping) (err error) { func (auth *OidcAuthConsumer) VerifyPing(pingMsg *msg.Ping) (err error) {
if !lo.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) {
return nil return nil
} }
@ -143,7 +143,7 @@ func (auth *OidcAuthConsumer) VerifyPing(pingMsg *msg.Ping) (err error) {
} }
func (auth *OidcAuthConsumer) VerifyNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) { func (auth *OidcAuthConsumer) VerifyNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) {
if !lo.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) {
return nil return nil
} }

View File

@ -16,10 +16,9 @@ package auth
import ( import (
"fmt" "fmt"
"slices"
"time" "time"
"github.com/samber/lo"
v1 "github.com/fatedier/frp/pkg/config/v1" v1 "github.com/fatedier/frp/pkg/config/v1"
"github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/util"
@ -43,7 +42,7 @@ func (auth *TokenAuthSetterVerifier) SetLogin(loginMsg *msg.Login) error {
} }
func (auth *TokenAuthSetterVerifier) SetPing(pingMsg *msg.Ping) error { func (auth *TokenAuthSetterVerifier) SetPing(pingMsg *msg.Ping) error {
if !lo.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) {
return nil return nil
} }
@ -53,7 +52,7 @@ func (auth *TokenAuthSetterVerifier) SetPing(pingMsg *msg.Ping) error {
} }
func (auth *TokenAuthSetterVerifier) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) error { func (auth *TokenAuthSetterVerifier) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) error {
if !lo.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) {
return nil return nil
} }
@ -70,7 +69,7 @@ func (auth *TokenAuthSetterVerifier) VerifyLogin(m *msg.Login) error {
} }
func (auth *TokenAuthSetterVerifier) VerifyPing(m *msg.Ping) error { func (auth *TokenAuthSetterVerifier) VerifyPing(m *msg.Ping) error {
if !lo.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) {
return nil return nil
} }
@ -81,7 +80,7 @@ func (auth *TokenAuthSetterVerifier) VerifyPing(m *msg.Ping) error {
} }
func (auth *TokenAuthSetterVerifier) VerifyNewWorkConn(m *msg.NewWorkConn) error { func (auth *TokenAuthSetterVerifier) VerifyNewWorkConn(m *msg.NewWorkConn) error {
if !lo.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) {
return nil return nil
} }

View File

@ -18,9 +18,9 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"slices"
"strings" "strings"
"github.com/samber/lo"
"gopkg.in/ini.v1" "gopkg.in/ini.v1"
legacyauth "github.com/fatedier/frp/pkg/auth/legacy" legacyauth "github.com/fatedier/frp/pkg/auth/legacy"
@ -399,7 +399,7 @@ func (cfg *ClientCommonConf) Validate() error {
} }
} }
if !lo.Contains([]string{"tcp", "kcp", "quic", "websocket", "wss"}, cfg.Protocol) { if !slices.Contains([]string{"tcp", "kcp", "quic", "websocket", "wss"}, cfg.Protocol) {
return fmt.Errorf("invalid protocol") return fmt.Errorf("invalid protocol")
} }

View File

@ -18,6 +18,7 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"slices"
"github.com/samber/lo" "github.com/samber/lo"
@ -29,7 +30,7 @@ func ValidateClientCommonConfig(c *v1.ClientCommonConfig) (Warning, error) {
warnings Warning warnings Warning
errs error errs error
) )
if !lo.Contains(SupportedAuthMethods, c.Auth.Method) { if !slices.Contains(SupportedAuthMethods, c.Auth.Method) {
errs = AppendError(errs, fmt.Errorf("invalid auth method, optional values are %v", SupportedAuthMethods)) errs = AppendError(errs, fmt.Errorf("invalid auth method, optional values are %v", SupportedAuthMethods))
} }
if !lo.Every(SupportedAuthAdditionalScopes, c.Auth.AdditionalScopes) { if !lo.Every(SupportedAuthAdditionalScopes, c.Auth.AdditionalScopes) {
@ -63,7 +64,7 @@ func ValidateClientCommonConfig(c *v1.ClientCommonConfig) (Warning, error) {
warnings = AppendError(warnings, checkTLSConfig("transport.tls.trustedCaFile", c.Transport.TLS.TrustedCaFile)) warnings = AppendError(warnings, checkTLSConfig("transport.tls.trustedCaFile", c.Transport.TLS.TrustedCaFile))
} }
if !lo.Contains(SupportedTransportProtocols, c.Transport.Protocol) { if !slices.Contains(SupportedTransportProtocols, c.Transport.Protocol) {
errs = AppendError(errs, fmt.Errorf("invalid transport.protocol, optional values are %v", SupportedTransportProtocols)) errs = AppendError(errs, fmt.Errorf("invalid transport.protocol, optional values are %v", SupportedTransportProtocols))
} }

View File

@ -16,8 +16,7 @@ package validation
import ( import (
"fmt" "fmt"
"slices"
"github.com/samber/lo"
v1 "github.com/fatedier/frp/pkg/config/v1" v1 "github.com/fatedier/frp/pkg/config/v1"
) )
@ -44,7 +43,7 @@ func ValidatePort(port int, fieldPath string) error {
} }
func validateLogConfig(c *v1.LogConfig) error { func validateLogConfig(c *v1.LogConfig) error {
if !lo.Contains(SupportedLogLevels, c.Level) { if !slices.Contains(SupportedLogLevels, c.Level) {
return fmt.Errorf("invalid log level, optional values are %v", SupportedLogLevels) return fmt.Errorf("invalid log level, optional values are %v", SupportedLogLevels)
} }
return nil return nil

View File

@ -17,9 +17,9 @@ package validation
import ( import (
"errors" "errors"
"fmt" "fmt"
"slices"
"strings" "strings"
"github.com/samber/lo"
"k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation"
v1 "github.com/fatedier/frp/pkg/config/v1" v1 "github.com/fatedier/frp/pkg/config/v1"
@ -33,10 +33,10 @@ func validateProxyBaseConfigForClient(c *v1.ProxyBaseConfig) error {
if err := ValidateAnnotations(c.Annotations); err != nil { if err := ValidateAnnotations(c.Annotations); err != nil {
return err return err
} }
if !lo.Contains([]string{"", "v1", "v2"}, c.Transport.ProxyProtocolVersion) { if !slices.Contains([]string{"", "v1", "v2"}, c.Transport.ProxyProtocolVersion) {
return fmt.Errorf("not support proxy protocol version: %s", c.Transport.ProxyProtocolVersion) return fmt.Errorf("not support proxy protocol version: %s", c.Transport.ProxyProtocolVersion)
} }
if !lo.Contains([]string{"client", "server"}, c.Transport.BandwidthLimitMode) { if !slices.Contains([]string{"client", "server"}, c.Transport.BandwidthLimitMode) {
return fmt.Errorf("bandwidth limit mode should be client or server") return fmt.Errorf("bandwidth limit mode should be client or server")
} }
@ -46,7 +46,7 @@ func validateProxyBaseConfigForClient(c *v1.ProxyBaseConfig) error {
} }
} }
if !lo.Contains([]string{"", "tcp", "http"}, c.HealthCheck.Type) { if !slices.Contains([]string{"", "tcp", "http"}, c.HealthCheck.Type) {
return fmt.Errorf("not support health check type: %s", c.HealthCheck.Type) return fmt.Errorf("not support health check type: %s", c.HealthCheck.Type)
} }
if c.HealthCheck.Type != "" { if c.HealthCheck.Type != "" {
@ -139,7 +139,7 @@ func validateTCPMuxProxyConfigForClient(c *v1.TCPMuxProxyConfig) error {
return err return err
} }
if !lo.Contains([]string{string(v1.TCPMultiplexerHTTPConnect)}, c.Multiplexer) { if !slices.Contains([]string{string(v1.TCPMultiplexerHTTPConnect)}, c.Multiplexer) {
return fmt.Errorf("not support multiplexer: %s", c.Multiplexer) return fmt.Errorf("not support multiplexer: %s", c.Multiplexer)
} }
return nil return nil

View File

@ -16,6 +16,7 @@ package validation
import ( import (
"fmt" "fmt"
"slices"
"github.com/samber/lo" "github.com/samber/lo"
@ -27,7 +28,7 @@ func ValidateServerConfig(c *v1.ServerConfig) (Warning, error) {
warnings Warning warnings Warning
errs error errs error
) )
if !lo.Contains(SupportedAuthMethods, c.Auth.Method) { if !slices.Contains(SupportedAuthMethods, c.Auth.Method) {
errs = AppendError(errs, fmt.Errorf("invalid auth method, optional values are %v", SupportedAuthMethods)) errs = AppendError(errs, fmt.Errorf("invalid auth method, optional values are %v", SupportedAuthMethods))
} }
if !lo.Every(SupportedAuthAdditionalScopes, c.Auth.AdditionalScopes) { if !lo.Every(SupportedAuthAdditionalScopes, c.Auth.AdditionalScopes) {

View File

@ -17,8 +17,7 @@ package validation
import ( import (
"errors" "errors"
"fmt" "fmt"
"slices"
"github.com/samber/lo"
v1 "github.com/fatedier/frp/pkg/config/v1" v1 "github.com/fatedier/frp/pkg/config/v1"
) )
@ -56,7 +55,7 @@ func validateVisitorBaseConfig(c *v1.VisitorBaseConfig) error {
} }
func validateXTCPVisitorConfig(c *v1.XTCPVisitorConfig) error { func validateXTCPVisitorConfig(c *v1.XTCPVisitorConfig) error {
if !lo.Contains([]string{"kcp", "quic"}, c.Protocol) { if !slices.Contains([]string{"kcp", "quic"}, c.Protocol) {
return fmt.Errorf("protocol should be kcp or quic") return fmt.Errorf("protocol should be kcp or quic")
} }
return nil return nil

View File

@ -15,6 +15,8 @@
package nathole package nathole
import ( import (
"cmp"
"slices"
"sync" "sync"
"time" "time"
@ -233,12 +235,12 @@ func (mhr *MakeHoleRecords) Recommand() (mode, index int) {
mhr.mu.Lock() mhr.mu.Lock()
defer mhr.mu.Unlock() defer mhr.mu.Unlock()
maxScore := lo.MaxBy(mhr.scores, func(item, max *BehaviorScore) bool { if len(mhr.scores) == 0 {
return item.Score > max.Score
})
if maxScore == nil {
return 0, 0 return 0, 0
} }
maxScore := slices.MaxFunc(mhr.scores, func(a, b *BehaviorScore) int {
return cmp.Compare(a.Score, b.Score)
})
maxScore.Score-- maxScore.Score--
mhr.LastUpdateTime = time.Now() mhr.LastUpdateTime = time.Now()
return maxScore.Mode, maxScore.Index return maxScore.Mode, maxScore.Index

View File

@ -17,9 +17,8 @@ package nathole
import ( import (
"fmt" "fmt"
"net" "net"
"slices"
"strconv" "strconv"
"github.com/samber/lo"
) )
const ( const (
@ -59,7 +58,7 @@ func ClassifyNATFeature(addresses []string, localIPs []string) (*NatFeature, err
if err != nil { if err != nil {
return nil, err return nil, err
} }
if lo.Contains(localIPs, ip) { if slices.Contains(localIPs, ip) {
natFeature.PublicNetwork = true natFeature.PublicNetwork = true
} }

View File

@ -20,6 +20,7 @@ import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"net" "net"
"slices"
"strconv" "strconv"
"sync" "sync"
"time" "time"
@ -72,7 +73,7 @@ type Session struct {
func (s *Session) genAnalysisKey() { func (s *Session) genAnalysisKey() {
hash := md5.New() hash := md5.New()
vIPs := lo.Uniq(parseIPs(s.visitorMsg.MappedAddrs)) vIPs := slices.Compact(parseIPs(s.visitorMsg.MappedAddrs))
if len(vIPs) > 0 { if len(vIPs) > 0 {
hash.Write([]byte(vIPs[0])) hash.Write([]byte(vIPs[0]))
} }
@ -80,7 +81,7 @@ func (s *Session) genAnalysisKey() {
hash.Write([]byte(s.vNatFeature.Behavior)) hash.Write([]byte(s.vNatFeature.Behavior))
hash.Write([]byte(strconv.FormatBool(s.vNatFeature.RegularPortsChange))) hash.Write([]byte(strconv.FormatBool(s.vNatFeature.RegularPortsChange)))
cIPs := lo.Uniq(parseIPs(s.clientMsg.MappedAddrs)) cIPs := slices.Compact(parseIPs(s.clientMsg.MappedAddrs))
if len(cIPs) > 0 { if len(cIPs) > 0 {
hash.Write([]byte(cIPs[0])) hash.Write([]byte(cIPs[0]))
} }
@ -156,7 +157,7 @@ func (c *Controller) HandleVisitor(m *msg.NatHoleVisitor, transporter transport.
_ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, fmt.Sprintf("xtcp server for [%s] doesn't exist", m.ProxyName))) _ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, fmt.Sprintf("xtcp server for [%s] doesn't exist", m.ProxyName)))
return return
} }
if !lo.Contains(cfg.allowUsers, visitorUser) && !lo.Contains(cfg.allowUsers, "*") { if !slices.Contains(cfg.allowUsers, visitorUser) && !slices.Contains(cfg.allowUsers, "*") {
_ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, fmt.Sprintf("xtcp visitor user [%s] not allowed for [%s]", visitorUser, m.ProxyName))) _ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, fmt.Sprintf("xtcp visitor user [%s] not allowed for [%s]", visitorUser, m.ProxyName)))
return return
} }
@ -327,8 +328,8 @@ func (c *Controller) analysis(session *Session) (*msg.NatHoleResp, *msg.NatHoleR
TransactionID: vm.TransactionID, TransactionID: vm.TransactionID,
Sid: session.sid, Sid: session.sid,
Protocol: protocol, Protocol: protocol,
CandidateAddrs: lo.Uniq(cm.MappedAddrs), CandidateAddrs: slices.Compact(cm.MappedAddrs),
AssistedAddrs: lo.Uniq(cm.AssistedAddrs), AssistedAddrs: slices.Compact(cm.AssistedAddrs),
DetectBehavior: msg.NatHoleDetectBehavior{ DetectBehavior: msg.NatHoleDetectBehavior{
Mode: mode, Mode: mode,
Role: vBehavior.Role, Role: vBehavior.Role,
@ -344,8 +345,8 @@ func (c *Controller) analysis(session *Session) (*msg.NatHoleResp, *msg.NatHoleR
TransactionID: cm.TransactionID, TransactionID: cm.TransactionID,
Sid: session.sid, Sid: session.sid,
Protocol: protocol, Protocol: protocol,
CandidateAddrs: lo.Uniq(vm.MappedAddrs), CandidateAddrs: slices.Compact(vm.MappedAddrs),
AssistedAddrs: lo.Uniq(vm.AssistedAddrs), AssistedAddrs: slices.Compact(vm.AssistedAddrs),
DetectBehavior: msg.NatHoleDetectBehavior{ DetectBehavior: msg.NatHoleDetectBehavior{
Mode: mode, Mode: mode,
Role: cBehavior.Role, Role: cBehavior.Role,

View File

@ -19,12 +19,12 @@ import (
"fmt" "fmt"
"math/rand" "math/rand"
"net" "net"
"slices"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/fatedier/golib/pool" "github.com/fatedier/golib/pool"
"github.com/samber/lo"
"golang.org/x/net/ipv4" "golang.org/x/net/ipv4"
"k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/sets"
@ -212,7 +212,7 @@ func MakeHole(ctx context.Context, listenConn *net.UDPConn, m *msg.NatHoleResp,
} }
} }
detectAddrs = lo.Uniq(detectAddrs) detectAddrs = slices.Compact(detectAddrs)
for _, detectAddr := range detectAddrs { for _, detectAddr := range detectAddrs {
for _, conn := range listenConns { for _, conn := range listenConns {
if err := sendSidMessage(ctx, conn, m.Sid, transactionID, detectAddr, key, m.DetectBehavior.TTL); err != nil { if err := sendSidMessage(ctx, conn, m.Sid, transactionID, detectAddr, key, m.DetectBehavior.TTL); err != nil {
@ -377,7 +377,7 @@ func sendSidMessageToRangePorts(
sendFunc func(*net.UDPConn, string) error, sendFunc func(*net.UDPConn, string) error,
) { ) {
xl := xlog.FromContextSafe(ctx) xl := xlog.FromContextSafe(ctx)
for _, ip := range lo.Uniq(parseIPs(addrs)) { for _, ip := range slices.Compact(parseIPs(addrs)) {
for _, portsRange := range ports { for _, portsRange := range ports {
for i := portsRange.From; i <= portsRange.To; i++ { for i := portsRange.From; i <= portsRange.To; i++ {
detectAddr := net.JoinHostPort(ip, strconv.Itoa(i)) detectAddr := net.JoinHostPort(ip, strconv.Itoa(i))
@ -419,7 +419,7 @@ func sendSidMessageToRandomPorts(
continue continue
} }
for _, ip := range lo.Uniq(parseIPs(addrs)) { for _, ip := range slices.Compact(parseIPs(addrs)) {
detectAddr := net.JoinHostPort(ip, strconv.Itoa(port)) detectAddr := net.JoinHostPort(ip, strconv.Itoa(port))
if err := sendFunc(conn, detectAddr); err != nil { if err := sendFunc(conn, detectAddr); err != nil {
xl.Trace("send sid message from %s to %s error: %v", conn.LocalAddr(), detectAddr, err) xl.Trace("send sid message from %s to %s error: %v", conn.LocalAddr(), detectAddr, err)

View File

@ -20,12 +20,12 @@ import (
"errors" "errors"
"fmt" "fmt"
"net" "net"
"slices"
"strings" "strings"
"sync" "sync"
"time" "time"
libio "github.com/fatedier/golib/io" libio "github.com/fatedier/golib/io"
"github.com/samber/lo"
"github.com/spf13/cobra" "github.com/spf13/cobra"
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
@ -262,7 +262,7 @@ func (s *TunnelServer) parseClientAndProxyConfigurer(_ *tcpipForward, extraPaylo
} }
proxyType := strings.TrimSpace(args[0]) proxyType := strings.TrimSpace(args[0])
supportTypes := []string{"tcp", "http", "https", "tcpmux", "stcp"} supportTypes := []string{"tcp", "http", "https", "tcpmux", "stcp"}
if !lo.Contains(supportTypes, proxyType) { if !slices.Contains(supportTypes, proxyType) {
return nil, nil, helpMessage, fmt.Errorf("invalid proxy type: %s, support types: %v", proxyType, supportTypes) return nil, nil, helpMessage, fmt.Errorf("invalid proxy type: %s, support types: %v", proxyType, supportTypes)
} }
pc := v1.NewProxyConfigurerByType(v1.ProxyType(proxyType)) pc := v1.NewProxyConfigurerByType(v1.ProxyType(proxyType))

View File

@ -1,8 +1,9 @@
package vhost package vhost
import ( import (
"cmp"
"errors" "errors"
"sort" "slices"
"strings" "strings"
"sync" "sync"
) )
@ -58,7 +59,10 @@ func (r *Routers) Add(domain, location, httpUser string, payload interface{}) er
payload: payload, payload: payload,
} }
vrs = append(vrs, vr) vrs = append(vrs, vr)
sort.Sort(sort.Reverse(ByLocation(vrs)))
slices.SortFunc(vrs, func(a, b *Router) int {
return -cmp.Compare(a.location, b.location)
})
routersByHTTPUser[httpUser] = vrs routersByHTTPUser[httpUser] = vrs
r.indexByDomain[domain] = routersByHTTPUser r.indexByDomain[domain] = routersByHTTPUser
@ -130,18 +134,3 @@ func (r *Routers) exist(host, path, httpUser string) (route *Router, exist bool)
} }
return return
} }
// sort by location
type ByLocation []*Router
func (a ByLocation) Len() int {
return len(a)
}
func (a ByLocation) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByLocation) Less(i, j int) bool {
return strings.Compare(a[i].location, a[j].location) < 0
}

View File

@ -15,7 +15,8 @@
package xlog package xlog
import ( import (
"sort" "cmp"
"slices"
"github.com/fatedier/frp/pkg/util/log" "github.com/fatedier/frp/pkg/util/log"
) )
@ -77,8 +78,8 @@ func (l *Logger) AddPrefix(prefix LogPrefix) *Logger {
} }
func (l *Logger) renderPrefixString() { func (l *Logger) renderPrefixString() {
sort.SliceStable(l.prefixes, func(i, j int) bool { slices.SortStableFunc(l.prefixes, func(a, b LogPrefix) int {
return l.prefixes[i].Priority < l.prefixes[j].Priority return cmp.Compare(a.Priority, b.Priority)
}) })
l.prefixString = "" l.prefixString = ""
for _, v := range l.prefixes { for _, v := range l.prefixes {

View File

@ -15,9 +15,10 @@
package server package server
import ( import (
"cmp"
"encoding/json" "encoding/json"
"net/http" "net/http"
"sort" "slices"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/client_golang/prometheus/promhttp"
@ -228,8 +229,8 @@ func (svr *Service) apiProxyByType(w http.ResponseWriter, r *http.Request) {
proxyInfoResp := GetProxyInfoResp{} proxyInfoResp := GetProxyInfoResp{}
proxyInfoResp.Proxies = svr.getProxyStatsByType(proxyType) proxyInfoResp.Proxies = svr.getProxyStatsByType(proxyType)
sort.Slice(proxyInfoResp.Proxies, func(i, j int) bool { slices.SortFunc(proxyInfoResp.Proxies, func(a, b *ProxyStatsInfo) int {
return proxyInfoResp.Proxies[i].Name < proxyInfoResp.Proxies[j].Name return cmp.Compare(a.Name, b.Name)
}) })
buf, _ := json.Marshal(&proxyInfoResp) buf, _ := json.Marshal(&proxyInfoResp)

View File

@ -18,10 +18,10 @@ import (
"fmt" "fmt"
"io" "io"
"net" "net"
"slices"
"sync" "sync"
libio "github.com/fatedier/golib/io" libio "github.com/fatedier/golib/io"
"github.com/samber/lo"
netpkg "github.com/fatedier/frp/pkg/util/net" netpkg "github.com/fatedier/frp/pkg/util/net"
"github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/util"
@ -75,7 +75,7 @@ func (vm *Manager) NewConn(name string, conn net.Conn, timestamp int64, signKey
return return
} }
if !lo.Contains(l.allowUsers, visitorUser) && !lo.Contains(l.allowUsers, "*") { if !slices.Contains(l.allowUsers, visitorUser) && !slices.Contains(l.allowUsers, "*") {
err = fmt.Errorf("visitor connection of [%s] user [%s] not allowed", name, visitorUser) err = fmt.Errorf("visitor connection of [%s] user [%s] not allowed", name, visitorUser)
return return
} }