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

Fix linter issues #129

Closed
Closed
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
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
22 changes: 12 additions & 10 deletions echo-mysql/main.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Package main initializes and starts a URL shortening service using Echo framework,
// connecting to a MySQL database and providing endpoints for shortening and resolving URLs
package main

import (
Expand All @@ -19,7 +21,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 +35,8 @@ 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 +52,10 @@ 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 +68,11 @@ 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
1 change: 1 addition & 0 deletions echo-mysql/uss/short.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package uss provides utility functions for generating short, unique URL links by hashing and encoding input URLs
package uss

import (
Expand Down
27 changes: 15 additions & 12 deletions echo-mysql/uss/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,20 @@ import (
"gorm.io/gorm"
)

var MetaStore *Store

type ShortCodeInfo struct {
UID uint64 `json:"id" sql:"AUTO_INCREMENT" gorm:"primary_key"`
ShortCode string `json:"shortcode" gorm:"uniqueIndex"`
URL string `json:"url"`
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 +51,32 @@ 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.Fatalf("%s", fmt.Sprintf("Failed to create/update db tables with error %s", err.Error()))
}

return nil
}

func (s *USSStore) Close() {
func (s *Store) Close() {
db, _ := s.db.DB()
db.Close()
err := db.Close()
if err != nil {
log.Fatalf("%s", 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
}
}

var MetaStore *USSStore
urlInfo := infos[0]
return &urlInfo
}
24 changes: 13 additions & 11 deletions fasthttp-postgres/internal/app/app.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Package app initializes and runs the web server, sets up the database connection,
// and handles graceful shutdown of the server.
package app

import (
Expand All @@ -11,19 +13,19 @@ import (
"time"

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

"github.com/valyala/fasthttp"
)

func InitApp() {
func InitApp(db *sql.DB) {
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)
}
defer db.Close() // Close the database connection when the application exits

// Close the database connection when the application exits
defer func() {
if err := db.Close(); err != nil {
log.Fatalf("%s", err)
}
}()

repo := repository.NewRepository(db)
ctrl := handlers.NewHandler(repo)
Expand All @@ -32,8 +34,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 Down
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 structures (models) for the application,
package entity

type Author struct {
Expand Down
22 changes: 12 additions & 10 deletions fasthttp-postgres/internal/handlers/handler.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Package handlers contains the HTTP handlers for managing authors and books.
// It communicates with the repository layer to retrieve and manipulate data for the API endpoints.
package handlers

import (
Expand All @@ -17,8 +19,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 +49,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
10 changes: 6 additions & 4 deletions fasthttp-postgres/internal/repository/repository.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Package repository provides functions to interact with the database for authors and books.
// It includes methods to fetch, create, and manage data related to authors and books.
package repository

import (
Expand Down Expand Up @@ -49,9 +51,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 +69,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

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
24 changes: 22 additions & 2 deletions fasthttp-postgres/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
// Package main initializes and starts the application by calling the InitApp function
package main

import "fasthttp-postgres/internal/app"
import (
"database/sql"
"fasthttp-postgres/internal/app"
"log"

_ "github.com/lib/pq"
)

var (
db *sql.DB
err error
)

func init() {
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)
}
}

func main() {
app.InitApp()
app.InitApp(db)
}
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
13 changes: 8 additions & 5 deletions gin-redis/server/server.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
// Package server manages the HTTP server setup and graceful shutdown.
// It initializes the server, starts it, and ensures it shuts down properly when receiving interrupt signals.
package server

import (
"time"
"github.com/keploy/gin-redis/routes"
"os"
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"

"github.com/keploy/gin-redis/routes"
)

func Init() {
time.Sleep(2 * time.Second)
r := routes.NewRouter()
port := "3001"
srv := &http.Server{
Addr: ":" + port,
Addr: ":" + port,
Handler: r,
}
go func() {
Expand All @@ -42,4 +45,4 @@ func GracefulShutdown(srv *http.Server) {
}

fmt.Println("Server exiting")
}
}
4 changes: 3 additions & 1 deletion go-grpc/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,5 +327,7 @@ func main() {
r.DELETE("/users/stream", deleteUsersStream)

// Start Gin server
r.Run(":8080")
if err := r.Run(":8080"); err != nil {
log.Fatalf("%s", err)
}
}
Loading