فهرست منبع

feat: ci lint

zijiren233 9 ماه پیش
والد
کامیت
df5133786c

+ 29 - 0
.github/workflows/check-semgrep.yml

@@ -0,0 +1,29 @@
+# Name of this GitHub Actions workflow.
+name: Check-Semgrep
+
+on:
+  workflow_dispatch:
+  schedule:
+    - cron: 0 0 * * *
+  push:
+    branches: ["main"]
+    paths-ignore:
+      - "**/*.md"
+      - "**/*.yaml"
+  pull_request:
+    branches: ["*"]
+    paths-ignore:
+      - "**/*.md"
+      - "**/*.yaml"
+
+jobs:
+  semgrep:
+    name: Scan
+    runs-on: ubuntu-24.04
+    container:
+      image: semgrep/semgrep:1.109.0
+    continue-on-error: true
+    if: (github.actor != 'dependabot[bot]')
+    steps:
+      - uses: actions/checkout@v4
+      - run: semgrep ci

+ 53 - 0
.github/workflows/ci.yml

@@ -0,0 +1,53 @@
+name: CI
+
+on:
+  workflow_call:
+  workflow_dispatch:
+    inputs:
+      push_mage:
+        description: 'Push images'
+        required: false
+        type: boolean
+  push:
+    branches: [ "main" ]
+    paths-ignore:
+      - "docs/**"
+      - "**/*.md"
+      - "**/*.yaml"
+      - "CONTRIBUTORS"
+      - "CHANGELOG/**"
+      - "controllers/**"
+      - "service/**"
+      - "webhooks/**"
+      - "frontend/**"
+  pull_request:
+    branches: [ "*" ]
+    paths-ignore:
+      - "docs/**"
+      - "CHANGELOG/**"
+      - "**/*.md"
+      - "**/*.yaml"
+      - "CONTRIBUTORS"
+      - "CHANGELOG/**"
+      - "controllers/**"
+      - "service/**"
+      - "webhooks/**"
+      - "frontend/**"
+
+jobs:
+  golangci-lint:
+    runs-on: ubuntu-24.04
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v4
+
+      - name: Setup Golang with cache
+        uses: magnetikonline/action-golang-cache@v5
+        with:
+          go-version: "1.23"
+
+      - name: Run Linter
+        uses: golangci/golangci-lint-action@v6
+        with:
+          version: v1.64.5
+          args: "--out-format colored-line-number --max-issues-per-linter 0 --max-same-issues 0"

+ 81 - 0
.golangci.yml

@@ -0,0 +1,81 @@
+run:
+  go: "1.23"
+  timeout: 5m
+  tests: true
+  modules-download-mode: readonly
+
+issues:
+  exclude-dirs-use-default: true
+
+linters:
+  disable-all: true
+  enable:
+    - gofmt
+    - goimports
+    - revive
+    - stylecheck
+    - gosimple
+    - misspell
+    - whitespace
+    - ineffassign
+    - typecheck
+    - errcheck
+    - govet
+    - staticcheck
+    - unused
+    - nilerr
+    - unconvert
+    - nosprintfhostport
+    - gofumpt
+    - sloglint
+    - unparam
+    - usestdlibvars
+    - usetesting
+    - gocritic
+    - asciicheck
+    - bidichk
+    - gocheckcompilerdirectives
+    - asasalint
+    - durationcheck
+    - exptostd
+    - forbidigo
+    - mirror
+    - errorlint
+    - errchkjson
+    - errname
+    - nilerr
+    - gosec
+    - sqlclosecheck
+    - rowserrcheck
+    - noctx
+    - bodyclose
+    - prealloc
+    - perfsprint
+    - unconvert
+    - gocyclo
+    - testifylint
+    - thelper
+    - testpackage
+    - tparallel
+    - goheader
+    - gomoddirectives
+    - gomodguard
+    - musttag
+    - tagalign
+    - iface
+    - importas
+    - loggercheck
+    - canonicalheader
+    - containedctx
+    - copyloopvar
+    - intrange
+    - makezero
+    - nolintlint
+    - predeclared
+    - wastedassign
+    - ginkgolinter
+    - goprintffuncname
+    - inamedparam
+    - promlinter
+    - protogetter
+    - reassign

+ 15 - 8
common/config/config.go

@@ -23,7 +23,7 @@ var (
 
 var (
 	disableServe                 atomic.Bool
-	logStorageHours              int64 = 0 // default 0 means no limit
+	logStorageHours              int64 // default 0 means no limit
 	saveAllLogDetail             atomic.Bool
 	logDetailRequestBodyMaxSize  int64 = 128 * 1024 // 128KB
 	logDetailResponseBodyMaxSize int64 = 128 * 1024 // 128KB
@@ -94,7 +94,8 @@ func SetModelErrorAutoBanRate(rate float64) {
 }
 
 func GetTimeoutWithModelType() map[int]int64 {
-	return timeoutWithModelType.Load().(map[int]int64)
+	t, _ := timeoutWithModelType.Load().(map[int]int64)
+	return t
 }
 
 func SetTimeoutWithModelType(timeout map[int]int64) {
@@ -157,7 +158,8 @@ func SetDisableServe(disabled bool) {
 }
 
 func GetDefaultChannelModels() map[int][]string {
-	return defaultChannelModels.Load().(map[int][]string)
+	d, _ := defaultChannelModels.Load().(map[int][]string)
+	return d
 }
 
 func SetDefaultChannelModels(models map[int][]string) {
@@ -170,7 +172,8 @@ func SetDefaultChannelModels(models map[int][]string) {
 }
 
 func GetDefaultChannelModelMapping() map[int]map[string]string {
-	return defaultChannelModelMapping.Load().(map[int]map[string]string)
+	d, _ := defaultChannelModelMapping.Load().(map[int]map[string]string)
+	return d
 }
 
 func SetDefaultChannelModelMapping(mapping map[int]map[string]string) {
@@ -179,7 +182,8 @@ func SetDefaultChannelModelMapping(mapping map[int]map[string]string) {
 }
 
 func GetGroupConsumeLevelRatio() map[float64]float64 {
-	return groupConsumeLevelRatio.Load().(map[float64]float64)
+	r, _ := groupConsumeLevelRatio.Load().(map[float64]float64)
+	return r
 }
 
 func GetGroupConsumeLevelRatioStringKeyMap() map[string]float64 {
@@ -207,7 +211,8 @@ func SetGroupMaxTokenNum(num int64) {
 }
 
 func GetGeminiSafetySetting() string {
-	return geminiSafetySetting.Load().(string)
+	s, _ := geminiSafetySetting.Load().(string)
+	return s
 }
 
 func SetGeminiSafetySetting(setting string) {
@@ -225,7 +230,8 @@ func SetBillingEnabled(enabled bool) {
 }
 
 func GetInternalToken() string {
-	return internalToken.Load().(string)
+	t, _ := internalToken.Load().(string)
+	return t
 }
 
 func SetInternalToken(token string) {
@@ -234,7 +240,8 @@ func SetInternalToken(token string) {
 }
 
 func GetNotifyNote() string {
-	return notifyNote.Load().(string)
+	n, _ := notifyNote.Load().(string)
+	return n
 }
 
 func SetNotifyNote(note string) {

+ 2 - 1
common/gin.go

@@ -50,7 +50,8 @@ func GetRequestBody(req *http.Request) ([]byte, error) {
 
 	requestBody := req.Context().Value(RequestBodyKey{})
 	if requestBody != nil {
-		return requestBody.([]byte), nil
+		b, _ := requestBody.([]byte)
+		return b, nil
 	}
 	var buf []byte
 	var err error

+ 4 - 4
common/network/ip.go

@@ -5,7 +5,7 @@ import (
 	"net"
 )
 
-func isValidSubnet(subnet string) error {
+func IsValidSubnet(subnet string) error {
 	_, _, err := net.ParseCIDR(subnet)
 	if err != nil {
 		return fmt.Errorf("failed to parse subnet: %w", err)
@@ -13,7 +13,7 @@ func isValidSubnet(subnet string) error {
 	return nil
 }
 
-func isIPInSubnet(ip string, subnet string) (bool, error) {
+func IsIPInSubnet(ip string, subnet string) (bool, error) {
 	_, ipNet, err := net.ParseCIDR(subnet)
 	if err != nil {
 		return false, fmt.Errorf("failed to parse subnet: %w", err)
@@ -23,7 +23,7 @@ func isIPInSubnet(ip string, subnet string) (bool, error) {
 
 func IsValidSubnets(subnets []string) error {
 	for _, subnet := range subnets {
-		if err := isValidSubnet(subnet); err != nil {
+		if err := IsValidSubnet(subnet); err != nil {
 			return err
 		}
 	}
@@ -32,7 +32,7 @@ func IsValidSubnets(subnets []string) error {
 
 func IsIPInSubnets(ip string, subnets []string) (bool, error) {
 	for _, subnet := range subnets {
-		if ok, err := isIPInSubnet(ip, subnet); err != nil {
+		if ok, err := IsIPInSubnet(ip, subnet); err != nil {
 			return false, err
 		} else if ok {
 			return true, nil

+ 4 - 3
common/network/ip_test.go

@@ -1,8 +1,9 @@
-package network
+package network_test
 
 import (
 	"testing"
 
+	"github.com/labring/aiproxy/common/network"
 	"github.com/smartystreets/goconvey/convey"
 )
 
@@ -11,12 +12,12 @@ func TestIsIpInSubnet(t *testing.T) {
 	ip2 := "125.216.250.89"
 	subnet := "192.168.0.0/24"
 	convey.Convey("TestIsIpInSubnet", t, func() {
-		if ok, err := isIPInSubnet(ip1, subnet); err != nil {
+		if ok, err := network.IsIPInSubnet(ip1, subnet); err != nil {
 			t.Errorf("failed to check ip in subnet: %s", err)
 		} else {
 			convey.So(ok, convey.ShouldBeTrue)
 		}
-		if ok, err := isIPInSubnet(ip2, subnet); err != nil {
+		if ok, err := network.IsIPInSubnet(ip2, subnet); err != nil {
 			t.Errorf("failed to check ip in subnet: %s", err)
 		} else {
 			convey.So(ok, convey.ShouldBeFalse)

+ 2 - 2
common/notify/notify.go

@@ -20,7 +20,7 @@ type Notifier interface {
 
 var (
 	stdNotifier     Notifier = &StdNotifier{}
-	defaultNotifier Notifier = stdNotifier
+	defaultNotifier          = stdNotifier
 )
 
 func SetDefaultNotifier(notifier Notifier) {
@@ -47,7 +47,7 @@ func limitKey(level Level, key string) string {
 	return fmt.Sprintf("notifylimit:%s:%s", level, key)
 }
 
-func NotifyThrottle(level Level, key string, expiration time.Duration, title, message string) {
+func Throttle(level Level, key string, expiration time.Duration, title, message string) {
 	defaultNotifier.NotifyThrottle(level, limitKey(level, key), expiration, title, message)
 }
 

+ 1 - 1
middleware/utils.go

@@ -27,7 +27,7 @@ type errorField struct {
 
 func abortWithMessage(c *gin.Context, statusCode int, message string, fields ...*errorField) {
 	typeName := ErrorTypeAIPROXY
-	var code any = nil
+	var code any
 	if len(fields) > 0 {
 		if fields[0].Type != "" {
 			typeName = fields[0].Type

+ 0 - 1
model/cache.go

@@ -412,7 +412,6 @@ type ModelConfigCache interface {
 }
 
 // read-only cache
-//
 
 type ModelCaches struct {
 	ModelConfig                     ModelConfigCache

+ 2 - 0
relay/adaptor/doubaoaudio/tts.go

@@ -139,7 +139,9 @@ func ConvertTTSRequest(meta *meta.Meta, req *http.Request) (string, http.Header,
 	binary.BigEndian.PutUint32(payloadArr, uint32(len(compressedData)))
 	clientRequest := make([]byte, len(defaultHeader))
 	copy(clientRequest, defaultHeader)
+	//nolint:makezero
 	clientRequest = append(clientRequest, payloadArr...)
+	//nolint:makezero
 	clientRequest = append(clientRequest, compressedData...)
 
 	return http.MethodPost, nil, bytes.NewReader(clientRequest), nil

+ 2 - 0
relay/adaptor/openai/balance.go

@@ -54,6 +54,8 @@ func GetBalance(channel *model.Channel) (float64, error) {
 	if err != nil {
 		return 0, err
 	}
+	defer res2.Body.Close()
+
 	usage := UsageResponse{}
 	err = sonic.ConfigDefault.NewDecoder(res2.Body).Decode(&usage)
 	if err != nil {

+ 2 - 0
relay/controller/dohelper.go

@@ -99,6 +99,8 @@ func DoHelper(
 		return nil, &detail, relayErr
 	}
 
+	defer resp.Body.Close()
+
 	// 4. Handle success response
 	usage, relayErr := handleResponse(a, c, meta, resp, &detail)
 	if relayErr != nil {