Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixes samples-go linter errors #128

Merged
merged 3 commits into from
Jan 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,21 +46,18 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: '1.21'
go-version: '1.23.4'
cache: false
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
# Require: The version of golangci-lint to use.
# When `install-mode` is `binary` (default) the value can be v1.2 or v1.2.3 or `latest` to use the latest version.
# When `install-mode` is `goinstall` the value can be v1.2.3, `latest`, or the hash of a commit.
version: v1.54
version: v1.63.4

# Optional: working directory, useful for monorepos
working-directory: ${{matrix.working-directory}}

# Optional: show only new issues if it's a pull request. The default value is `false`.
only-new-issues: true

# Optional: The mode to install golangci-lint. It can be 'binary' or 'goinstall'.
install-mode: "goinstall"
6 changes: 3 additions & 3 deletions S3-Keploy/bucket/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,13 @@ func (basics Basics) DeleteAllObjects(bucketName string) (message string) {
for _, key := range result.Contents {
objectKeys = append(objectKeys, *key.Key)
}
var objectIds []types.ObjectIdentifier
var objectIDs []types.ObjectIdentifier
for _, key := range objectKeys {
objectIds = append(objectIds, types.ObjectIdentifier{Key: aws.String(key)})
objectIDs = append(objectIDs, types.ObjectIdentifier{Key: aws.String(key)})
}
_, err = basics.S3Client.DeleteObjects(context.TODO(), &s3.DeleteObjectsInput{
Bucket: aws.String(bucketName),
Delete: &types.Delete{Objects: objectIds},
Delete: &types.Delete{Objects: objectIDs},
})
if err != nil {
return "Couldn't delete objects from bucket " + bucketName + " . Here's why: " + err.Error() + "\n"
Expand Down
18 changes: 8 additions & 10 deletions echo-mysql/main.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package main starts the application
package main

import (
Expand All @@ -19,7 +20,7 @@ func main() {
log.Fatalf("Error reading .env file %s", err.Error())
}

uss.MetaStore = &uss.USSStore{}
uss.MetaStore = &uss.Store{}
err = uss.MetaStore.Connect(appConfig)
if err != nil {
log.Fatalf("Failed to connect to db %s", err.Error())
Expand All @@ -33,10 +34,7 @@ func StartHTTPServer() {
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: `${remote_ip} [${time_rfc3339}] "${method} ${uri} HTTP/1.0" ${status} ${latency_human} ${bytes_out} ${error} "${user_agent}"` + "\n",
Skipper: func(c echo.Context) bool {
if c.Request().RequestURI == "/healthcheck" {
return true
}
return false
return c.Request().RequestURI == "/healthcheck"
},
}))
e.Use(middleware.Recover())
Expand All @@ -52,9 +50,9 @@ func StartHTTPServer() {
info := uss.MetaStore.FindByShortCode(code)
if info != nil {
return c.JSON(http.StatusOK, info)
} else {
return c.String(http.StatusNotFound, "Not Found.")
}

return c.String(http.StatusNotFound, "Not Found.")
})

e.POST("/shorten", func(c echo.Context) error {
Expand All @@ -67,10 +65,10 @@ func StartHTTPServer() {
err := uss.MetaStore.Persist(req)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("Failed Persisiting Entity with Error %s", err.Error()))
} else {
req.UpdatedAt = req.UpdatedAt.Truncate(time.Second)
return c.JSON(http.StatusOK, req)
}

req.UpdatedAt = req.UpdatedAt.Truncate(time.Second)
return c.JSON(http.StatusOK, req)
})

// automatically add routers for net/http/pprof e.g. /debug/pprof, /debug/pprof/heap, etc.
Expand Down
2 changes: 2 additions & 0 deletions echo-mysql/uss/short.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Package uss generates short links using SHA-256 and Base58 encoding. Provides methods to connect to and interact with a MySQL database
// for storing and retrieving short URLs.
package uss

import (
Expand Down
26 changes: 15 additions & 11 deletions echo-mysql/uss/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package uss
import (
"fmt"
"log"
"os"
"time"

"gorm.io/driver/mysql"
Expand All @@ -16,11 +17,11 @@ type ShortCodeInfo struct {
UpdatedAt time.Time `json:"updated_at" gorm:"datetime(0);autoUpdateTime"`
}

type USSStore struct {
type Store struct {
db *gorm.DB
}

func (s *USSStore) Connect(config map[string]string) error {
func (s *Store) Connect(config map[string]string) error {
// Open up our database connection.
var err error
mysqlDSN := fmt.Sprintf(
Expand Down Expand Up @@ -49,31 +50,34 @@ func (s *USSStore) Connect(config map[string]string) error {
sqlDB.SetMaxOpenConns(512)

if err = s.db.AutoMigrate(&ShortCodeInfo{}); err != nil {
log.Fatal(fmt.Sprintf("Failed to create/update db tables with error %s", err.Error()))
log.Printf("Failed to create/update db tables with error %s", err.Error())
return err
}

return nil
}

func (s *USSStore) Close() {
func (s *Store) Close() {
db, _ := s.db.DB()
db.Close()
if err := db.Close(); err != nil {
fmt.Fprintf(os.Stderr, "Could not close database connection: %v\n", err)
}
}

func (s *USSStore) Persist(info *ShortCodeInfo) error {
func (s *Store) Persist(info *ShortCodeInfo) error {
s.db.Save(info)
return nil
}

func (s *USSStore) FindByShortCode(shortCode string) *ShortCodeInfo {
func (s *Store) FindByShortCode(shortCode string) *ShortCodeInfo {
var infos []ShortCodeInfo
s.db.Order("updated_at desc").Find(&infos, "short_code = ?", shortCode)
if len(infos) == 0 {
return nil
} else {
urlInfo := infos[0]
return &urlInfo
}

urlInfo := infos[0]
return &urlInfo
}

var MetaStore *USSStore
var MetaStore *Store
26 changes: 18 additions & 8 deletions fasthttp-postgres/internal/app/app.go
Original file line number Diff line number Diff line change
@@ -1,29 +1,37 @@
// Package app initializes the application, sets up database connections, routes, and handles server startup and graceful shutdown.
package app

import (
"database/sql"
"fasthttp-postgres/internal/handlers"
"fasthttp-postgres/internal/repository"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"

"github.com/fasthttp/router"
_ "github.com/lib/pq"
"github.com/valyala/fasthttp"
)

func InitApp() {
func InitApp() error {
time.Sleep(2 * time.Second)
// Database connection initialization
uri := "postgresql://postgres:password@localhost:5432/db?sslmode=disable"
db, err := sql.Open("postgres", uri)
if err != nil {
log.Fatal("Error connecting to database:", err)
log.Print("Error connecting to database:", err)
return err
}
defer db.Close() // Close the database connection when the application exits

defer func() {
// Close the database connection when the application exits
if closeErr := db.Close(); closeErr != nil {
log.Println("Error closing database connection:", closeErr)
}
}()

repo := repository.NewRepository(db)
ctrl := handlers.NewHandler(repo)
Expand All @@ -32,8 +40,8 @@ func InitApp() {
router := router.New()
router.GET("/authors", ctrl.GetAllAuthors)
router.GET("/books", ctrl.GetAllBooks)
router.GET("/books/{id}", ctrl.GetBookById)
router.GET("/authors/{id}", ctrl.GetBooksByAuthorId)
router.GET("/books/{id}", ctrl.GetBookByID)
router.GET("/authors/{id}", ctrl.GetBooksByAuthorID)
router.POST("/books", ctrl.CreateBook)
router.POST("/authors", ctrl.CreateAuthor)

Expand All @@ -46,7 +54,7 @@ func InitApp() {
// Start server in a goroutine
go func() {
log.Println("Starting server: http://localhost:8080")
if err := server.ListenAndServe(":8080"); err != nil {
if err := server.ListenAndServe(":8080"); err != nil && err != http.ErrServerClosed {
log.Fatalf("Error starting server: %s\n", err)
}
}()
Expand All @@ -61,8 +69,10 @@ func InitApp() {

// Attempt to gracefully shut down the server
if err := server.Shutdown(); err != nil {
log.Fatalf("Error shutting down server: %s\n", err)
log.Printf("Error shutting down server: %s\n", err)
return err
}

log.Println("Server gracefully stopped")
return nil
}
1 change: 1 addition & 0 deletions fasthttp-postgres/internal/entity/model.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package entity defines the data models for the application, including authors and books.
package entity

type Author struct {
Expand Down
21 changes: 11 additions & 10 deletions fasthttp-postgres/internal/handlers/handler.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package handlers provides HTTP request handlers for managing authors and books.
package handlers

import (
Expand All @@ -17,8 +18,8 @@ type Handler struct {
type Repository interface {
GetAllAuthors(context.Context) ([]entity.Author, error)
GetAllBooks(context.Context) ([]entity.Book, error)
GetBookById(context.Context, int) ([]entity.Book, error)
GetBooksByAuthorId(context.Context, int) ([]entity.Book, error)
GetBookByID(context.Context, int) ([]entity.Book, error)
GetBooksByAuthorID(context.Context, int) ([]entity.Book, error)
CreateBook(context.Context, entity.Book) error
CreateAuthor(context.Context, entity.Author) error
}
Expand Down Expand Up @@ -47,29 +48,29 @@ func (h *Handler) GetAllBooks(ctx *fasthttp.RequestCtx) {
sendData(ctx, books)
}

func (h *Handler) GetBookById(ctx *fasthttp.RequestCtx) {
bookId := ctx.UserValue("id").(string)
id, err := strconv.Atoi(bookId)
func (h *Handler) GetBookByID(ctx *fasthttp.RequestCtx) {
bookID := ctx.UserValue("id").(string)
id, err := strconv.Atoi(bookID)
if err != nil {
sendError(ctx, nil, http.StatusNotFound)
return
}
books, err := h.repository.GetBookById(ctx, id)
books, err := h.repository.GetBookByID(ctx, id)
if err != nil {
sendError(ctx, nil, http.StatusNotFound)
return
}
sendData(ctx, books[0])
}

func (h *Handler) GetBooksByAuthorId(ctx *fasthttp.RequestCtx) {
authorId := ctx.UserValue("id").(string)
id, err := strconv.Atoi(authorId)
func (h *Handler) GetBooksByAuthorID(ctx *fasthttp.RequestCtx) {
authorID := ctx.UserValue("id").(string)
id, err := strconv.Atoi(authorID)
if err != nil {
sendError(ctx, nil, http.StatusNotFound)
return
}
books, err := h.repository.GetBooksByAuthorId(ctx, id)
books, err := h.repository.GetBooksByAuthorID(ctx, id)
if err != nil {
sendError(ctx, nil, http.StatusNotFound)
return
Expand Down
1 change: 1 addition & 0 deletions fasthttp-postgres/internal/repository/model.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package repository provides functions for converting between entity models and database models.
package repository

import "fasthttp-postgres/internal/entity"
Expand Down
8 changes: 4 additions & 4 deletions fasthttp-postgres/internal/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ func (r *Repository) GetAllBooks(ctx context.Context) ([]entity.Book, error) {
return mm.convert(), nil
}

func (r *Repository) GetBookById(ctx context.Context, id int) ([]entity.Book, error) {
func (r *Repository) GetBookByID(ctx context.Context, id int) ([]entity.Book, error) {
var mm models
rows, err := r.db.QueryContext(ctx, getBookById, id)
rows, err := r.db.QueryContext(ctx, getBookByID, id)
if err != nil {
fmt.Println("1")
return nil, err
Expand All @@ -67,9 +67,9 @@ func (r *Repository) GetBookById(ctx context.Context, id int) ([]entity.Book, er
return mm.convert(), nil
}

func (r *Repository) GetBooksByAuthorId(ctx context.Context, id int) ([]entity.Book, error) {
func (r *Repository) GetBooksByAuthorID(ctx context.Context, id int) ([]entity.Book, error) {
var mm models
rows, err := r.db.QueryContext(ctx, getBooksByAuthorId, id)
rows, err := r.db.QueryContext(ctx, getBooksByAuthorID, id)
if err != nil {
return nil, err
}
Expand Down
6 changes: 3 additions & 3 deletions fasthttp-postgres/internal/repository/statements.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package repository

const (
getAllAuthors = `SELECT * FROM authors`
// getAuthorById = `SELECT * FROM authors WHERE id = $1`
getBookById = `SELECT b.id, b.title, b.year, b.author_id, a.first_name, a.last_name
// getAuthorByID = `SELECT * FROM authors WHERE id = $1`
getBookByID = `SELECT b.id, b.title, b.year, b.author_id, a.first_name, a.last_name
FROM books b
LEFT JOIN authors a on b.author_id=a.id
WHERE b.id = $1;`
getBooksByAuthorId = `SELECT b.id, b.title, b.year, b.author_id, a.first_name, a.last_name
getBooksByAuthorID = `SELECT b.id, b.title, b.year, b.author_id, a.first_name, a.last_name
FROM authors a
LEFT JOIN books b on a.id=b.author_id
WHERE a.id = $1;`
Expand Down
11 changes: 9 additions & 2 deletions fasthttp-postgres/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
// Package main is the entry point of the application.
package main

import "fasthttp-postgres/internal/app"
import (
"fasthttp-postgres/internal/app"
"log"
)

func main() {
app.InitApp()
err := app.InitApp()
if err != nil {
log.Fatalf("Error occured: %s\n", err)
}
}
2 changes: 1 addition & 1 deletion gin-redis/helpers/token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func GenerateToken(value string, secretKey string) (string, error) {
}

func VerifyToken(tokenString string, secretKey string) (*CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(_ *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})

Expand Down
Loading
Loading