New lint rules

This commit is contained in:
Jamie Curnow
2024-11-21 19:07:36 +10:00
parent 4e6d65645f
commit 152b7666d8
85 changed files with 385 additions and 259 deletions

View File

@ -3,17 +3,17 @@ package handler
import (
"encoding/json"
"net/http"
h "npm/internal/api/http"
"npm/internal/errors"
"npm/internal/logger"
"slices"
"time"
c "npm/internal/api/context"
h "npm/internal/api/http"
"npm/internal/entity/auth"
"npm/internal/entity/setting"
"npm/internal/entity/user"
"npm/internal/errors"
njwt "npm/internal/jwt"
"npm/internal/logger"
"gorm.io/gorm"
)

View File

@ -151,7 +151,7 @@ func getCertificateFromRequest(w http.ResponseWriter, r *http.Request) *certific
// fillObjectFromBody has some reusable code for all endpoints that
// have a certificate id in the url. it will write errors to the output.
func fillObjectFromBody(w http.ResponseWriter, r *http.Request, validationSchema string, o interface{}) bool {
func fillObjectFromBody(w http.ResponseWriter, r *http.Request, validationSchema string, o any) bool {
bodyBytes, _ := r.Context().Value(c.BodyCtxKey).([]byte)
if validationSchema != "" {
@ -176,10 +176,10 @@ func fillObjectFromBody(w http.ResponseWriter, r *http.Request, validationSchema
return true
}
func configureCertificate(c certificate.Model) {
func configureCertificate(cert certificate.Model) {
err := jobqueue.AddJob(jobqueue.Job{
Name: "RequestCertificate",
Action: c.Request,
Action: cert.Request,
})
if err != nil {
logger.Error("ConfigureCertificateError", err)

View File

@ -2,6 +2,7 @@ package handler
import (
"net/http"
h "npm/internal/api/http"
"npm/internal/config"
)

View File

@ -2,6 +2,7 @@ package handler
import (
"net/http"
"npm/internal/acme"
h "npm/internal/api/http"
"npm/internal/config"

View File

@ -56,7 +56,7 @@ func getQueryVarInt(r *http.Request, varName string, required bool, defaultValue
}
func getURLParamInt(r *http.Request, varName string) (uint, error) {
var defaultValue uint = 0
var defaultValue uint
required := true
paramStr := chi.URLParam(r, varName)

View File

@ -3,9 +3,10 @@ package handler
import (
"net/http"
"net/http/httptest"
"npm/internal/model"
"testing"
"npm/internal/model"
"github.com/stretchr/testify/assert"
)

View File

@ -192,7 +192,7 @@ func GetHostNginxConfig(format string) func(http.ResponseWriter, *http.Request)
return
}
if format == "text" {
h.ResultResponseText(w, r, http.StatusOK, content)
h.ResultResponseText(w, http.StatusOK, content)
return
}
h.ResultResponseJSON(w, r, http.StatusOK, content)
@ -202,11 +202,11 @@ func GetHostNginxConfig(format string) func(http.ResponseWriter, *http.Request)
}
}
func configureHost(h host.Model) {
func configureHost(hst host.Model) {
err := jobqueue.AddJob(jobqueue.Job{
Name: "NginxConfigureHost",
Action: func() error {
return nginx.ConfigureHost(h)
return nginx.ConfigureHost(hst)
},
})
if err != nil {

View File

@ -12,7 +12,7 @@ import (
"npm/internal/config"
"npm/internal/logger"
jsref "github.com/jc21/jsref"
"github.com/jc21/jsref"
"github.com/jc21/jsref/provider"
)
@ -24,7 +24,7 @@ var (
// Schema simply reads the swagger schema from disk and returns is raw
// Route: GET /schema
func Schema() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, string(getSchema()))
@ -42,8 +42,8 @@ func getSchema() []byte {
swaggerSchema = []byte(strings.ReplaceAll(string(swaggerSchema), "{{VERSION}}", config.Version))
// Dereference the JSON Schema:
var schema interface{}
if err := json.Unmarshal(swaggerSchema, &schema); err != nil {
var sch any
if err := json.Unmarshal(swaggerSchema, &sch); err != nil {
logger.Error("SwaggerUnmarshalError", err)
return nil
}
@ -55,7 +55,7 @@ func getSchema() []byte {
logger.Error("SchemaProviderError", err)
}
result, err := resolver.Resolve(schema, "", []jsref.Option{jsref.WithRecursiveResolution(true)}...)
result, err := resolver.Resolve(sch, "", []jsref.Option{jsref.WithRecursiveResolution(true)}...)
if err != nil {
logger.Error("SwaggerResolveError", err)
} else {

View File

@ -95,7 +95,7 @@ func CreateUpstream() func(http.ResponseWriter, *http.Request) {
}
}
// UpdateHost updates a host
// UpdateUpstream updates a stream
// Route: PUT /upstreams/{upstreamID}
func UpdateUpstream() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
@ -167,7 +167,7 @@ func DeleteUpstream() func(http.ResponseWriter, *http.Request) {
}
}
// GetHostNginxConfig will return a Host's nginx config from disk
// GetUpstreamNginxConfig will return a Host's nginx config from disk
// Route: GET /upstreams/{upstreamID}/nginx-config
// Route: GET /upstreams/{upstreamID}/nginx-config.txt
func GetUpstreamNginxConfig(format string) func(http.ResponseWriter, *http.Request) {
@ -191,7 +191,7 @@ func GetUpstreamNginxConfig(format string) func(http.ResponseWriter, *http.Reque
return
}
if format == "text" {
h.ResultResponseText(w, r, http.StatusOK, content)
h.ResultResponseText(w, http.StatusOK, content)
return
}
h.ResultResponseJSON(w, r, http.StatusOK, content)

View File

@ -21,19 +21,19 @@ var (
// Response interface for standard API results
type Response struct {
Result interface{} `json:"result"`
Error interface{} `json:"error,omitempty"`
Result any `json:"result"`
Error any `json:"error,omitempty"`
}
// ErrorResponse interface for errors returned via the API
type ErrorResponse struct {
Code interface{} `json:"code"`
Message interface{} `json:"message"`
Invalid interface{} `json:"invalid,omitempty"`
Code any `json:"code"`
Message any `json:"message"`
Invalid any `json:"invalid,omitempty"`
}
// ResultResponseJSON will write the result as json to the http output
func ResultResponseJSON(w http.ResponseWriter, r *http.Request, status int, result interface{}) {
func ResultResponseJSON(w http.ResponseWriter, r *http.Request, status int, result any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
@ -77,7 +77,7 @@ func ResultSchemaErrorJSON(w http.ResponseWriter, r *http.Request, errs []jsonsc
}
// ResultErrorJSON will format the result as a standard error object and send it for output
func ResultErrorJSON(w http.ResponseWriter, r *http.Request, status int, message string, extended interface{}) {
func ResultErrorJSON(w http.ResponseWriter, r *http.Request, status int, message string, extended any) {
errorResponse := ErrorResponse{
Code: status,
Message: message,
@ -98,7 +98,7 @@ func NotFound(w http.ResponseWriter, r *http.Request) {
}
// ResultResponseText will write the result as text to the http output
func ResultResponseText(w http.ResponseWriter, r *http.Request, status int, content string) {
func ResultResponseText(w http.ResponseWriter, status int, content string) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(status)
fmt.Fprint(w, content)

View File

@ -21,7 +21,7 @@ func TestResultResponseJSON(t *testing.T) {
tests := []struct {
name string
status int
given interface{}
given any
want string
}{
{
@ -34,9 +34,9 @@ func TestResultResponseJSON(t *testing.T) {
name: "detailed response",
status: http.StatusBadRequest,
given: user.Model{
ModelBase: model.ModelBase{ID: 10},
Email: "me@example.com",
Name: "John Doe",
Base: model.Base{ID: 10},
Email: "me@example.com",
Name: "John Doe",
},
want: "{\"result\":{\"id\":10,\"created_at\":0,\"updated_at\":0,\"name\":\"John Doe\",\"email\":\"me@example.com\",\"is_disabled\":false,\"gravatar_url\":\"\"}}",
},
@ -118,7 +118,7 @@ func TestResultErrorJSON(t *testing.T) {
name string
status int
message string
extended interface{}
extended any
want string
}{
{
@ -180,9 +180,8 @@ func TestResultResponseText(t *testing.T) {
defer goleak.VerifyNone(t, goleak.IgnoreAnyFunction("database/sql.(*DB).connectionOpener"))
t.Run("basic test", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/anything", nil)
w := httptest.NewRecorder()
ResultResponseText(w, r, http.StatusOK, "omg this works")
ResultResponseText(w, http.StatusOK, "omg this works")
res := w.Result()
defer res.Body.Close()
body, err := io.ReadAll(res.Body)

View File

@ -15,7 +15,7 @@ func TestAccessControl(t *testing.T) {
// goleak is used to detect goroutine leaks
defer goleak.VerifyNone(t, goleak.IgnoreAnyFunction("database/sql.(*DB).connectionOpener"))
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})

View File

@ -18,6 +18,6 @@ func AuthCacheInit() {
}
// AuthCacheSet will store the item in memory for the expiration time
func AuthCacheSet(k string, x interface{}) {
func AuthCacheSet(k string, x any) {
AuthCache.Set(k, x, cache.DefaultExpiration)
}

View File

@ -26,7 +26,7 @@ func TestBodyContext(t *testing.T) {
rr := httptest.NewRecorder()
// Create a test handler that checks the context for the body data
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
bodyData := r.Context().Value(c.BodyCtxKey).([]byte)
assert.Equal(t, body, bodyData)
})

View File

@ -15,7 +15,7 @@ func TestCors(t *testing.T) {
r := chi.NewRouter()
r.Use(middleware.Cors(r))
r.Get("/test", func(w http.ResponseWriter, r *http.Request) {
r.Get("/test", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("test"))
})
@ -48,7 +48,7 @@ func TestOptions(t *testing.T) {
r := chi.NewRouter()
r.Use(middleware.Options(r))
r.Get("/test", func(w http.ResponseWriter, r *http.Request) {
r.Get("/test", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("test"))
})

View File

@ -5,11 +5,11 @@ import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
"npm/internal/api/middleware"
"npm/internal/config"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
)
func TestEnforceSetup(t *testing.T) {
@ -37,7 +37,7 @@ func TestEnforceSetup(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
config.IsSetup = tt.isSetup
handler := middleware.EnforceSetup()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler := middleware.EnforceSetup()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))

View File

@ -23,7 +23,7 @@ func TestExpansion(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
expand := middleware.GetExpandFromContext(r)
assert.Equal(t, []string{"item1", "item2"}, expand)
})
@ -39,7 +39,7 @@ func TestExpansion(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
expand := middleware.GetExpandFromContext(r)
assert.Nil(t, expand)
})

View File

@ -21,7 +21,7 @@ import (
// and the sort parameter is valid as well.
// After we have determined what the Filters are to be, they are saved on the Context
// to be used later in other endpoints.
func ListQuery(obj interface{}) func(http.Handler) http.Handler {
func ListQuery(obj any) func(http.Handler) http.Handler {
schemaData := tags.GetFilterSchema(obj)
filterMap := tags.GetFilterMap(obj, "")
@ -29,13 +29,13 @@ func ListQuery(obj interface{}) func(http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx, statusCode, errMsg, errors := listQueryFilters(r, ctx, schemaData)
ctx, statusCode, errMsg, errors := listQueryFilters(ctx, r, schemaData)
if statusCode > 0 {
h.ResultErrorJSON(w, r, statusCode, errMsg, errors)
return
}
ctx, statusCode, errMsg = listQuerySort(r, filterMap, ctx)
ctx, statusCode, errMsg = listQuerySort(ctx, r, filterMap)
if statusCode > 0 {
h.ResultErrorJSON(w, r, statusCode, errMsg, nil)
return
@ -47,9 +47,9 @@ func ListQuery(obj interface{}) func(http.Handler) http.Handler {
}
func listQuerySort(
ctx context.Context,
r *http.Request,
filterMap map[string]model.FilterMapValue,
ctx context.Context,
) (context.Context, int, string) {
var sortFields []model.Sort
@ -99,10 +99,10 @@ func listQuerySort(
}
func listQueryFilters(
r *http.Request,
ctx context.Context,
r *http.Request,
schemaData string,
) (context.Context, int, string, interface{}) {
) (context.Context, int, string, any) {
reservedFilterKeys := []string{
"limit",
"offset",

View File

@ -53,7 +53,7 @@ func TestListQuery(t *testing.T) {
ctx = context.WithValue(ctx, c.FiltersCtxKey, tags.GetFilterSchema(testObj))
rr := httptest.NewRecorder()
handler := middleware.ListQuery(testObj)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler := middleware.ListQuery(testObj)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))

View File

@ -33,7 +33,6 @@ func CheckRequestSchema(ctx context.Context, schemaData string, payload []byte)
func EnforceRequestSchema(schemaData string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get content from context
bodyBytes, _ := r.Context().Value(c.BodyCtxKey).([]byte)

View File

@ -29,7 +29,7 @@ import (
// NewRouter returns a new router object
func NewRouter() http.Handler {
// Cors
cors := cors.New(cors.Options{
corss := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Requested-With"},
@ -42,7 +42,7 @@ func NewRouter() http.Handler {
middleware.AccessControl,
middleware.Cors(r),
middleware.Options(r),
cors.Handler,
corss.Handler,
chiMiddleware.RealIP,
chiMiddleware.Recoverer,
chiMiddleware.Throttle(5),

View File

@ -18,7 +18,7 @@ func CreateDNSProvider() string {
allSchemasWrapped := make([]string, 0)
for providerName, provider := range allProviders {
schema, err := provider.GetJsonSchema()
schema, err := provider.GetJSONSchema()
if err != nil {
logger.Error("ProviderSchemaError", eris.Wrapf(err, "Invalid Provider Schema for %s: %v", provider.Title, err))
} else {

View File

@ -3,9 +3,10 @@ package schema
import (
"bytes"
"encoding/json"
"npm/internal/entity/certificate"
"testing"
"npm/internal/entity/certificate"
"github.com/stretchr/testify/assert"
)

View File

@ -1,6 +1,6 @@
package schema
// UpdateHostTemplate is the schema for incoming data validation
// UpdateNginxTemplate is the schema for incoming data validation
func UpdateNginxTemplate() string {
return `
{