formatting

This commit is contained in:
Hayden 2023-02-17 18:51:11 -09:00
parent 6532ea44a5
commit bd058be1fb
No known key found for this signature in database
GPG key ID: 17CF79474E257545
44 changed files with 20 additions and 95 deletions

View file

@ -50,7 +50,6 @@ func (ctrl *V1Controller) HandleAssetGet() server.HandlerFunc {
} }
} }
items, err := ctrl.repo.Items.QueryByAssetID(r.Context(), ctx.GID, repo.AssetID(assetId), int(page), int(pageSize)) items, err := ctrl.repo.Items.QueryByAssetID(r.Context(), ctx.GID, repo.AssetID(assetId), int(page), int(pageSize))
if err != nil { if err != nil {
log.Err(err).Msg("failed to get item") log.Err(err).Msg("failed to get item")

View file

@ -50,7 +50,6 @@ func (ctrl *V1Controller) HandleAuthLogin() server.HandlerFunc {
loginForm.Password = r.PostFormValue("password") loginForm.Password = r.PostFormValue("password")
case server.ContentJSON: case server.ContentJSON:
err := server.Decode(r, loginForm) err := server.Decode(r, loginForm)
if err != nil { if err != nil {
log.Err(err).Msg("failed to decode login form") log.Err(err).Msg("failed to decode login form")
} }
@ -72,7 +71,6 @@ func (ctrl *V1Controller) HandleAuthLogin() server.HandlerFunc {
} }
newToken, err := ctrl.svc.User.Login(r.Context(), strings.ToLower(loginForm.Username), loginForm.Password) newToken, err := ctrl.svc.User.Login(r.Context(), strings.ToLower(loginForm.Username), loginForm.Password)
if err != nil { if err != nil {
return validate.NewRequestError(errors.New("authentication failed"), http.StatusInternalServerError) return validate.NewRequestError(errors.New("authentication failed"), http.StatusInternalServerError)
} }

View file

@ -26,7 +26,6 @@ import (
// @Router /v1/items [GET] // @Router /v1/items [GET]
// @Security Bearer // @Security Bearer
func (ctrl *V1Controller) HandleItemsGetAll() server.HandlerFunc { func (ctrl *V1Controller) HandleItemsGetAll() server.HandlerFunc {
extractQuery := func(r *http.Request) repo.ItemQuery { extractQuery := func(r *http.Request) repo.ItemQuery {
params := r.URL.Query() params := r.URL.Query()
@ -244,7 +243,6 @@ func (ctrl *V1Controller) HandleGetAllCustomFieldValues() server.HandlerFunc {
// @Security Bearer // @Security Bearer
func (ctrl *V1Controller) HandleItemsImport() server.HandlerFunc { func (ctrl *V1Controller) HandleItemsImport() server.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error { return func(w http.ResponseWriter, r *http.Request) error {
err := r.ParseMultipartForm(ctrl.maxUploadSize << 20) err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
if err != nil { if err != nil {
log.Err(err).Msg("failed to parse multipart form") log.Err(err).Msg("failed to parse multipart form")

View file

@ -82,7 +82,6 @@ func (ctrl *V1Controller) HandleItemAttachmentCreate() server.HandlerFunc {
attachment.Type(attachmentType), attachment.Type(attachmentType),
file, file,
) )
if err != nil { if err != nil {
log.Err(err).Msg("failed to add attachment") log.Err(err).Msg("failed to add attachment")
return validate.NewRequestError(err, http.StatusInternalServerError) return validate.NewRequestError(err, http.StatusInternalServerError)

View file

@ -34,7 +34,6 @@ func (ctrl *V1Controller) HandleLocationTreeQuery() server.HandlerFunc {
WithItems: withItems, WithItems: withItems,
}, },
) )
if err != nil { if err != nil {
log.Err(err).Msg("failed to get locations tree") log.Err(err).Msg("failed to get locations tree")
return validate.NewRequestError(err, http.StatusInternalServerError) return validate.NewRequestError(err, http.StatusInternalServerError)

View file

@ -80,7 +80,6 @@ func (ctrl *V1Controller) HandleUserSelfUpdate() server.HandlerFunc {
actor := services.UseUserCtx(r.Context()) actor := services.UseUserCtx(r.Context())
newData, err := ctrl.svc.User.UpdateSelf(r.Context(), actor.ID, updateData) newData, err := ctrl.svc.User.UpdateSelf(r.Context(), actor.ID, updateData)
if err != nil { if err != nil {
return validate.NewRequestError(err, http.StatusInternalServerError) return validate.NewRequestError(err, http.StatusInternalServerError)
} }

View file

@ -57,7 +57,7 @@ func run(cfg *config.Config) error {
// ========================================================================= // =========================================================================
// Initialize Database & Repos // Initialize Database & Repos
err := os.MkdirAll(cfg.Storage.Data, 0755) err := os.MkdirAll(cfg.Storage.Data, 0o755)
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("failed to create data directory") log.Fatal().Err(err).Msg("failed to create data directory")
} }

View file

@ -15,9 +15,7 @@ type tokenHasKey struct {
key string key string
} }
var ( var hashedToken = tokenHasKey{key: "hashedToken"}
hashedToken = tokenHasKey{key: "hashedToken"}
)
type RoleMode int type RoleMode int

View file

@ -58,5 +58,4 @@ func TestItemService_AddAttachment(t *testing.T) {
bts, err := os.ReadFile(storedPath) bts, err := os.ReadFile(storedPath)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, contents, string(bts)) assert.Equal(t, contents, string(bts))
} }

View file

@ -139,7 +139,6 @@ func (svc *UserService) UpdateSelf(ctx context.Context, ID uuid.UUID, data repo.
// User Authentication // User Authentication
func (svc *UserService) createSessionToken(ctx context.Context, userId uuid.UUID) (UserAuthTokenDetail, error) { func (svc *UserService) createSessionToken(ctx context.Context, userId uuid.UUID) (UserAuthTokenDetail, error) {
attachmentToken := hasher.GenerateToken() attachmentToken := hasher.GenerateToken()
attachmentData := repo.UserAuthTokenCreate{ attachmentData := repo.UserAuthTokenCreate{
UserID: userId, UserID: userId,
@ -173,7 +172,6 @@ func (svc *UserService) createSessionToken(ctx context.Context, userId uuid.UUID
func (svc *UserService) Login(ctx context.Context, username, password string) (UserAuthTokenDetail, error) { func (svc *UserService) Login(ctx context.Context, username, password string) (UserAuthTokenDetail, error) {
usr, err := svc.repos.Users.GetOneEmail(ctx, username) usr, err := svc.repos.Users.GetOneEmail(ctx, username)
if err != nil { if err != nil {
// SECURITY: Perform hash to ensure response times are the same // SECURITY: Perform hash to ensure response times are the same
hasher.CheckPasswordHash("not-a-real-password", "not-a-real-password") hasher.CheckPasswordHash("not-a-real-password", "not-a-real-password")
@ -197,7 +195,6 @@ func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthT
hash := hasher.HashToken(token) hash := hasher.HashToken(token)
dbToken, err := svc.repos.AuthTokens.GetUserFromToken(ctx, hash) dbToken, err := svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
if err != nil { if err != nil {
return UserAuthTokenDetail{}, ErrorInvalidToken return UserAuthTokenDetail{}, ErrorInvalidToken
} }

View file

@ -13,7 +13,7 @@ var Files embed.FS
// It returns an error and a cleanup function. The cleanup function // It returns an error and a cleanup function. The cleanup function
// should be called when the migrations are no longer needed. // should be called when the migrations are no longer needed.
func Write(temp string) error { func Write(temp string) error {
err := os.MkdirAll(temp, 0755) err := os.MkdirAll(temp, 0o755)
if err != nil { if err != nil {
return err return err
} }
@ -33,7 +33,7 @@ func Write(temp string) error {
return err return err
} }
err = os.WriteFile(filepath.Join(temp, f.Name()), b, 0644) err = os.WriteFile(filepath.Join(temp, f.Name()), b, 0o644)
if err != nil { if err != nil {
return err return err
} }

View file

@ -14,9 +14,7 @@ import (
"github.com/hay-kot/homebox/backend/pkgs/pathlib" "github.com/hay-kot/homebox/backend/pkgs/pathlib"
) )
var ( var ErrInvalidDocExtension = errors.New("invalid document extension")
ErrInvalidDocExtension = errors.New("invalid document extension")
)
type DocumentRepository struct { type DocumentRepository struct {
db *ent.Client db *ent.Client
@ -74,7 +72,7 @@ func (r *DocumentRepository) Create(ctx context.Context, gid uuid.UUID, doc Docu
path := r.path(gid, ext) path := r.path(gid, ext)
parent := filepath.Dir(path) parent := filepath.Dir(path)
err := os.MkdirAll(parent, 0755) err := os.MkdirAll(parent, 0o755)
if err != nil { if err != nil {
return DocumentOut{}, err return DocumentOut{}, err
} }

View file

@ -34,7 +34,6 @@ func useDocs(t *testing.T, num int) []DocumentOut {
t.Cleanup(func() { t.Cleanup(func() {
for _, id := range ids { for _, id := range ids {
err := tRepos.Docs.Delete(context.Background(), id) err := tRepos.Docs.Delete(context.Background(), id)
if err != nil { if err != nil {
assert.True(t, ent.IsNotFound(err)) assert.True(t, ent.IsNotFound(err))
} }

View file

@ -76,9 +76,7 @@ type (
} }
) )
var ( var mapToGroupErr = mapTErrFunc(mapToGroup)
mapToGroupErr = mapTErrFunc(mapToGroup)
)
func mapToGroup(g *ent.Group) Group { func mapToGroup(g *ent.Group) Group {
return Group{ return Group{
@ -90,9 +88,7 @@ func mapToGroup(g *ent.Group) Group {
} }
} }
var ( var mapToGroupInvitationErr = mapTErrFunc(mapToGroupInvitation)
mapToGroupInvitationErr = mapTErrFunc(mapToGroupInvitation)
)
func mapToGroupInvitation(g *ent.GroupInvitationToken) GroupInvitation { func mapToGroupInvitation(g *ent.GroupInvitationToken) GroupInvitation {
return GroupInvitation{ return GroupInvitation{
@ -118,7 +114,6 @@ func (r *GroupRepository) StatsLocationsByPurchasePrice(ctx context.Context, GID
return sql.As(sql.Sum(t.C(item.FieldPurchasePrice)), "total") return sql.As(sql.Sum(t.C(item.FieldPurchasePrice)), "total")
}). }).
Scan(ctx, &v) Scan(ctx, &v)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -145,7 +140,6 @@ func (r *GroupRepository) StatsLabelsByPurchasePrice(ctx context.Context, GID uu
return sql.As(sql.Sum(itemTable.C(item.FieldPurchasePrice)), "total") return sql.As(sql.Sum(itemTable.C(item.FieldPurchasePrice)), "total")
}). }).
Scan(ctx, &v) Scan(ctx, &v)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -283,7 +277,6 @@ func (r *GroupRepository) InvitationCreate(ctx context.Context, groupID uuid.UUI
SetExpiresAt(invite.ExpiresAt). SetExpiresAt(invite.ExpiresAt).
SetUses(invite.Uses). SetUses(invite.Uses).
Save(ctx) Save(ctx)
if err != nil { if err != nil {
return GroupInvitation{}, err return GroupInvitation{}, err
} }

View file

@ -68,7 +68,6 @@ func (r *AttachmentRepo) Update(ctx context.Context, itemId uuid.UUID, typ attac
itm, err := r.db.Attachment.UpdateOneID(itemId). itm, err := r.db.Attachment.UpdateOneID(itemId).
SetType(typ). SetType(typ).
Save(ctx) Save(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -58,7 +58,6 @@ func TestAttachmentRepo_Create(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
got, err := tRepos.Attachments.Create(tt.args.ctx, tt.args.itemId, tt.args.docId, tt.args.typ) got, err := tRepos.Attachments.Create(tt.args.ctx, tt.args.itemId, tt.args.docId, tt.args.typ)
if (err != nil) != tt.wantErr { if (err != nil) != tt.wantErr {
t.Errorf("AttachmentRepo.Create() error = %v, wantErr %v", err, tt.wantErr) t.Errorf("AttachmentRepo.Create() error = %v, wantErr %v", err, tt.wantErr)
@ -119,7 +118,6 @@ func TestAttachmentRepo_Update(t *testing.T) {
assert.Equal(t, typ, updated.Type) assert.Equal(t, typ, updated.Type)
}) })
} }
} }
func TestAttachmentRepo_Delete(t *testing.T) { func TestAttachmentRepo_Delete(t *testing.T) {

View file

@ -150,9 +150,7 @@ type (
} }
) )
var ( var mapItemsSummaryErr = mapTEachErrFunc(mapItemSummary)
mapItemsSummaryErr = mapTEachErrFunc(mapItemSummary)
)
func mapItemSummary(item *ent.Item) ItemSummary { func mapItemSummary(item *ent.Item) ItemSummary {
var location *LocationSummary var location *LocationSummary
@ -371,7 +369,6 @@ func (e *ItemsRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q Ite
} }
count, err := qb.Count(ctx) count, err := qb.Count(ctx)
if err != nil { if err != nil {
return PaginationResult[ItemSummary]{}, err return PaginationResult[ItemSummary]{}, err
} }
@ -387,7 +384,6 @@ func (e *ItemsRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q Ite
} }
items, err := mapItemsSummaryErr(qb.All(ctx)) items, err := mapItemsSummaryErr(qb.All(ctx))
if err != nil { if err != nil {
return PaginationResult[ItemSummary]{}, err return PaginationResult[ItemSummary]{}, err
} }
@ -398,7 +394,6 @@ func (e *ItemsRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q Ite
Total: count, Total: count,
Items: items, Items: items,
}, nil }, nil
} }
// QueryByAssetID returns items by asset ID. If the item does not exist, an error is returned. // QueryByAssetID returns items by asset ID. If the item does not exist, an error is returned.
@ -422,7 +417,6 @@ func (e *ItemsRepository) QueryByAssetID(ctx context.Context, gid uuid.UUID, ass
WithLocation(). WithLocation().
All(ctx), All(ctx),
) )
if err != nil { if err != nil {
return PaginationResult[ItemSummary]{}, err return PaginationResult[ItemSummary]{}, err
} }
@ -441,6 +435,7 @@ func (e *ItemsRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]ItemOut,
Where(item.HasGroupWith(group.ID(gid))). Where(item.HasGroupWith(group.ID(gid))).
WithLabel(). WithLabel().
WithLocation(). WithLocation().
WithFields().
All(ctx)) All(ctx))
} }
@ -651,7 +646,6 @@ func (e *ItemsRepository) GetAllCustomFieldValues(ctx context.Context, GID uuid.
Unique(true). Unique(true).
Select(itemfield.FieldTextValue). Select(itemfield.FieldTextValue).
Scan(ctx, &values) Scan(ctx, &values)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get field values: %w", err) return nil, fmt.Errorf("failed to get field values: %w", err)
} }
@ -679,7 +673,6 @@ func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, GID uuid.U
Unique(true). Unique(true).
Select(itemfield.FieldName). Select(itemfield.FieldName).
Scan(ctx, &fields) Scan(ctx, &fields)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get custom fields: %w", err) return nil, fmt.Errorf("failed to get custom fields: %w", err)
} }

View file

@ -125,7 +125,6 @@ func TestItemsRepository_Create(t *testing.T) {
// Cleanup - Also deletes item // Cleanup - Also deletes item
err = tRepos.Locations.Delete(context.Background(), location.ID) err = tRepos.Locations.Delete(context.Background(), location.ID)
assert.NoError(t, err) assert.NoError(t, err)
} }
func TestItemsRepository_Create_Location(t *testing.T) { func TestItemsRepository_Create_Location(t *testing.T) {
@ -222,7 +221,6 @@ func TestItemsRepository_Update_Labels(t *testing.T) {
} }
}) })
} }
} }
func TestItemsRepository_Update(t *testing.T) { func TestItemsRepository_Update(t *testing.T) {

View file

@ -100,7 +100,6 @@ func (r *LabelRepository) Create(ctx context.Context, groupdId uuid.UUID, data L
SetColor(data.Color). SetColor(data.Color).
SetGroupID(groupdId). SetGroupID(groupdId).
Save(ctx) Save(ctx)
if err != nil { if err != nil {
return LabelOut{}, err return LabelOut{}, err
} }

View file

@ -62,9 +62,7 @@ func mapLocationSummary(location *ent.Location) LocationSummary {
} }
} }
var ( var mapLocationOutErr = mapTErrFunc(mapLocationOut)
mapLocationOutErr = mapTErrFunc(mapLocationOut)
)
func mapLocationOut(location *ent.Location) LocationOut { func mapLocationOut(location *ent.Location) LocationOut {
var parent *LocationSummary var parent *LocationSummary
@ -181,7 +179,6 @@ func (r *LocationRepository) Create(ctx context.Context, GID uuid.UUID, data Loc
} }
location, err := q.Save(ctx) location, err := q.Save(ctx)
if err != nil { if err != nil {
return LocationOut{}, err return LocationOut{}, err
} }
@ -322,7 +319,7 @@ func (lr *LocationRepository) Tree(ctx context.Context, GID uuid.UUID, tq TreeQu
} }
func ConvertLocationsToTree(locations []FlatTreeItem) []TreeItem { func ConvertLocationsToTree(locations []FlatTreeItem) []TreeItem {
var locationMap = make(map[uuid.UUID]*TreeItem, len(locations)) locationMap := make(map[uuid.UUID]*TreeItem, len(locations))
var rootIds []uuid.UUID var rootIds []uuid.UUID

View file

@ -31,7 +31,6 @@ func useLocations(t *testing.T, len int) []LocationOut {
t.Cleanup(func() { t.Cleanup(func() {
for _, loc := range out { for _, loc := range out {
err := tRepos.Locations.Delete(context.Background(), loc.ID) err := tRepos.Locations.Delete(context.Background(), loc.ID)
if err != nil { if err != nil {
assert.True(t, ent.IsNotFound(err)) assert.True(t, ent.IsNotFound(err))
} }
@ -74,7 +73,6 @@ func TestLocationRepositoryGetAllWithCount(t *testing.T) {
assert.Equal(t, 1, loc.ItemCount) assert.Equal(t, 1, loc.ItemCount)
} }
} }
} }
func TestLocationRepository_Create(t *testing.T) { func TestLocationRepository_Create(t *testing.T) {

View file

@ -93,7 +93,6 @@ func (r *MaintenanceEntryRepository) GetLog(ctx context.Context, itemID uuid.UUI
Where(maintenanceentry.ItemID(itemID)). Where(maintenanceentry.ItemID(itemID)).
Order(ent.Desc(maintenanceentry.FieldDate)). Order(ent.Desc(maintenanceentry.FieldDate)).
All(ctx) All(ctx)
if err != nil { if err != nil {
return MaintenanceLog{}, err return MaintenanceLog{}, err
} }

View file

@ -61,7 +61,6 @@ func TestMaintenanceEntryRepository_GetLog(t *testing.T) {
// Get the log for the item // Get the log for the item
log, err := tRepos.MaintEntry.GetLog(context.Background(), item.ID) log, err := tRepos.MaintEntry.GetLog(context.Background(), item.ID)
if err != nil { if err != nil {
t.Fatalf("failed to get maintenance log: %v", err) t.Fatalf("failed to get maintenance log: %v", err)
} }

View file

@ -42,7 +42,6 @@ func (r *TokenRepository) GetUserFromToken(ctx context.Context, token []byte) (U
QueryUser(). QueryUser().
WithGroup(). WithGroup().
Only(ctx) Only(ctx)
if err != nil { if err != nil {
return UserOut{}, err return UserOut{}, err
} }
@ -59,7 +58,6 @@ func (r *TokenRepository) GetRoles(ctx context.Context, token string) (*set.Set[
authtokens.Token(tokenHash), authtokens.Token(tokenHash),
)). )).
All(ctx) All(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -80,7 +78,6 @@ func (r *TokenRepository) CreateToken(ctx context.Context, createToken UserAuthT
SetUserID(createToken.UserID). SetUserID(createToken.UserID).
SetExpiresAt(createToken.ExpiresAt). SetExpiresAt(createToken.ExpiresAt).
Save(ctx) Save(ctx)
if err != nil { if err != nil {
return UserAuthToken{}, err return UserAuthToken{}, err
} }
@ -90,7 +87,6 @@ func (r *TokenRepository) CreateToken(ctx context.Context, createToken UserAuthT
SetRole(role). SetRole(role).
SetToken(dbToken). SetToken(dbToken).
Save(ctx) Save(ctx)
if err != nil { if err != nil {
return UserAuthToken{}, err return UserAuthToken{}, err
} }
@ -115,7 +111,6 @@ func (r *TokenRepository) DeleteToken(ctx context.Context, token []byte) error {
// PurgeExpiredTokens removes all expired tokens from the database // PurgeExpiredTokens removes all expired tokens from the database
func (r *TokenRepository) PurgeExpiredTokens(ctx context.Context) (int, error) { func (r *TokenRepository) PurgeExpiredTokens(ctx context.Context) (int, error) {
tokensDeleted, err := r.db.AuthTokens.Delete().Where(authtokens.ExpiresAtLTE(time.Now())).Exec(ctx) tokensDeleted, err := r.db.AuthTokens.Delete().Where(authtokens.ExpiresAtLTE(time.Now())).Exec(ctx)
if err != nil { if err != nil {
return 0, err return 0, err
} }

View file

@ -123,7 +123,6 @@ func (e *UserRepository) DeleteAll(ctx context.Context) error {
func (e *UserRepository) GetSuperusers(ctx context.Context) ([]*ent.User, error) { func (e *UserRepository) GetSuperusers(ctx context.Context) ([]*ent.User, error) {
users, err := e.db.User.Query().Where(user.IsSuperuser(true)).All(ctx) users, err := e.db.User.Query().Where(user.IsSuperuser(true)).All(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -139,7 +139,6 @@ func TestUserRepo_Delete(t *testing.T) {
allUsers, _ = tRepos.Users.GetAll(ctx) allUsers, _ = tRepos.Users.GetAll(ctx)
assert.Equal(t, len(allUsers), 0) assert.Equal(t, len(allUsers), 0)
} }
func TestUserRepo_GetSuperusers(t *testing.T) { func TestUserRepo_GetSuperusers(t *testing.T) {

View file

@ -4,10 +4,9 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"os"
"github.com/ardanlabs/conf/v3" "github.com/ardanlabs/conf/v3"
"os"
) )
const ( const (
@ -55,7 +54,6 @@ func New() (*Config, error) {
const prefix = "HBOX" const prefix = "HBOX"
help, err := conf.Parse(prefix, &cfg) help, err := conf.Parse(prefix, &cfg)
if err != nil { if err != nil {
if errors.Is(err, conf.ErrHelpWanted) { if errors.Is(err, conf.ErrHelpWanted) {
fmt.Println(help) fmt.Println(help)
@ -71,11 +69,9 @@ func New() (*Config, error) {
// This is useful for debugging. If the marshaller errors out, it will panic. // This is useful for debugging. If the marshaller errors out, it will panic.
func (c *Config) Print() { func (c *Config) Print() {
res, err := json.MarshalIndent(c, "", " ") res, err := json.MarshalIndent(c, "", " ")
if err != nil { if err != nil {
panic(err) panic(err)
} }
fmt.Println(string(res)) fmt.Println(string(res))
} }

View file

@ -36,5 +36,4 @@ func Test_MailerReady_Failure(t *testing.T) {
mc.From = "from" mc.From = "from"
assert.True(t, mc.Ready()) assert.True(t, mc.Ready())
} }

View file

@ -5,8 +5,7 @@ import (
"errors" "errors"
) )
type UnauthorizedError struct { type UnauthorizedError struct{}
}
func (err *UnauthorizedError) Error() string { func (err *UnauthorizedError) Error() string {
return "unauthorized" return "unauthorized"

View file

@ -14,7 +14,6 @@ func init() {
// FieldErrors array and returned. // FieldErrors array and returned.
func Check(val any) error { func Check(val any) error {
err := validate.Struct(val) err := validate.Struct(val)
if err != nil { if err != nil {
verrors, ok := err.(validator.ValidationErrors) verrors, ok := err.(validator.ValidationErrors)
if !ok { if !ok {

View file

@ -13,7 +13,6 @@ func Errors(log zerolog.Logger) server.Middleware {
return func(h server.Handler) server.Handler { return func(h server.Handler) server.Handler {
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
err := h.ServeHTTP(w, r) err := h.ServeHTTP(w, r)
if err != nil { if err != nil {
var resp server.ErrorResponse var resp server.ErrorResponse
var code int var code int

View file

@ -76,7 +76,6 @@ func SugarLogger(log zerolog.Logger) server.Middleware {
return func(next server.Handler) server.Handler { return func(next server.Handler) server.Handler {
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
record := &statusRecorder{ResponseWriter: w, Status: http.StatusOK} record := &statusRecorder{ResponseWriter: w, Status: http.StatusOK}
err := next.ServeHTTP(record, r) // Blocks until the next handler returns. err := next.ServeHTTP(record, r) // Blocks until the next handler returns.

View file

@ -7,8 +7,7 @@ import (
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
type Faker struct { type Faker struct{}
}
func NewFaker() *Faker { func NewFaker() *Faker {
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
@ -20,7 +19,6 @@ func (f *Faker) Time() time.Time {
} }
func (f *Faker) Str(length int) string { func (f *Faker) Str(length int) string {
b := make([]rune, length) b := make([]rune, length)
for i := range b { for i := range b {
b[i] = letters[rand.Intn(len(letters))] b[i] = letters[rand.Intn(len(letters))]

View file

@ -20,7 +20,7 @@ func ValidateUnique(values []string) bool {
func Test_GetRandomString(t *testing.T) { func Test_GetRandomString(t *testing.T) {
t.Parallel() t.Parallel()
// Test that the function returns a string of the correct length // Test that the function returns a string of the correct length
var generated = make([]string, Loops) generated := make([]string, Loops)
faker := NewFaker() faker := NewFaker()
@ -36,7 +36,7 @@ func Test_GetRandomString(t *testing.T) {
func Test_GetRandomEmail(t *testing.T) { func Test_GetRandomEmail(t *testing.T) {
t.Parallel() t.Parallel()
// Test that the function returns a string of the correct length // Test that the function returns a string of the correct length
var generated = make([]string, Loops) generated := make([]string, Loops)
faker := NewFaker() faker := NewFaker()
@ -52,8 +52,8 @@ func Test_GetRandomEmail(t *testing.T) {
func Test_GetRandomBool(t *testing.T) { func Test_GetRandomBool(t *testing.T) {
t.Parallel() t.Parallel()
var trues = 0 trues := 0
var falses = 0 falses := 0
faker := NewFaker() faker := NewFaker()
@ -91,5 +91,4 @@ func Test_RandomNumber(t *testing.T) {
t.Errorf("RandomNumber() failed to generate a number between %v and %v", MIN, MAX) t.Errorf("RandomNumber() failed to generate a number between %v and %v", MIN, MAX)
} }
} }
} }

View file

@ -30,14 +30,12 @@ func GetTestMailer() (*Mailer, error) {
} }
return mailer, nil return mailer, nil
} }
func Test_Mailer(t *testing.T) { func Test_Mailer(t *testing.T) {
t.Parallel() t.Parallel()
mailer, err := GetTestMailer() mailer, err := GetTestMailer()
if err != nil { if err != nil {
t.Skip("Error Reading Test Mailer Config - Skipping") t.Skip("Error Reading Test Mailer Config - Skipping")
} }
@ -47,7 +45,6 @@ func Test_Mailer(t *testing.T) {
} }
message, err := RenderWelcome() message, err := RenderWelcome()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }

View file

@ -41,7 +41,6 @@ func DefaultTemplateData() TemplateProps {
func render(tpl string, data TemplateProps) (string, error) { func render(tpl string, data TemplateProps) (string, error) {
tmpl, err := template.New("name").Parse(tpl) tmpl, err := template.New("name").Parse(tpl)
if err != nil { if err != nil {
return "", err return "", err
} }

View file

@ -11,7 +11,6 @@ type Middleware func(Handler) Handler
// handler. The middlewares' Handlers will be executed by requests in the order // handler. The middlewares' Handlers will be executed by requests in the order
// they are provided. // they are provided.
func wrapMiddleware(mw []Middleware, handler Handler) Handler { func wrapMiddleware(mw []Middleware, handler Handler) Handler {
// Loop backwards through the middleware invoking each one. Replace the // Loop backwards through the middleware invoking each one. Replace the
// handler with the new wrapped handler. Looping backwards ensures that the // handler with the new wrapped handler. Looping backwards ensures that the
// first middleware of the slice is the first to be executed by requests. // first middleware of the slice is the first to be executed by requests.

View file

@ -40,7 +40,6 @@ func (s *Server) toHttpHandler(handler Handler, mw ...Middleware) http.HandlerFu
}) })
err := handler.ServeHTTP(w, r.WithContext(ctx)) err := handler.ServeHTTP(w, r.WithContext(ctx))
if err != nil { if err != nil {
if IsShutdownError(err) { if IsShutdownError(err) {
_ = s.Shutdown("SIGTERM") _ = s.Shutdown("SIGTERM")

View file

@ -37,5 +37,4 @@ func Test_Respond_JSON(t *testing.T) {
assert.Equal(t, http.StatusCreated, recorder.Code) assert.Equal(t, http.StatusCreated, recorder.Code)
assert.JSONEq(t, recorder.Body.String(), `{"name":"dummy"}`) assert.JSONEq(t, recorder.Body.String(), `{"name":"dummy"}`)
assert.Equal(t, "application/json", recorder.Header().Get("Content-Type")) assert.Equal(t, "application/json", recorder.Header().Get("Content-Type"))
} }

View file

@ -79,7 +79,6 @@ func (s *Server) Shutdown(sig string) error {
s.wg.Wait() s.wg.Wait()
return nil return nil
} }
func (s *Server) Start() error { func (s *Server) Start() error {

View file

@ -72,7 +72,6 @@ func Test_GracefulServerShutdownWithWorkers(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, isFinished) assert.True(t, isFinished)
} }
func Test_GracefulServerShutdownWithRequests(t *testing.T) { func Test_GracefulServerShutdownWithRequests(t *testing.T) {

View file

@ -10,8 +10,7 @@ type Worker interface {
// the Worker interface and runs all tasks in a go routine without // the Worker interface and runs all tasks in a go routine without
// a pool or que or limits. It's useful for simple or small applications // a pool or que or limits. It's useful for simple or small applications
// with minimal/short background tasks // with minimal/short background tasks
type SimpleWorker struct { type SimpleWorker struct{}
}
func NewSimpleWorker() *SimpleWorker { func NewSimpleWorker() *SimpleWorker {
return &SimpleWorker{} return &SimpleWorker{}

View file

@ -97,5 +97,4 @@ func Disjoint[T key](a, b Set[T]) bool {
} }
} }
return true return true
} }

View file

@ -28,7 +28,6 @@ var (
) )
func TestDiff(t *testing.T) { func TestDiff(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
args args args args