Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Last active May 18, 2024 23:46
Show Gist options
  • Save mayankchoubey/5aacfa928ad4af84ad2b97edb2fed565 to your computer and use it in GitHub Desktop.
Save mayankchoubey/5aacfa928ad4af84ad2b97edb2fed565 to your computer and use it in GitHub Desktop.
Go - Gin, Fiber, and Echo app for database reads
package main
import (
"context"
"database/sql"
"os"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
)
type User struct {
bun.BaseModel `bun:"table:users"`
Email string `bun:"email,pk"`
First string `bun:"first"`
Last string `bun:"last"`
City string `bun:"city"`
County string `bun:"county"`
Age int `bun:"age"`
}
var sqldb = sql.OpenDB(pgdriver.NewConnector(
pgdriver.WithNetwork("tcp"),
pgdriver.WithAddr("localhost:5432"),
pgdriver.WithUser(os.Getenv("dbUser")),
pgdriver.WithPassword(os.Getenv("dbUserPass")),
pgdriver.WithDatabase(os.Getenv("dbName")),
pgdriver.WithInsecure(true),
))
var db = bun.NewDB(sqldb, pgdialect.New())
func init() {
sqldb.SetMaxOpenConns(10)
sqldb.SetMaxIdleConns(10)
}
func GetUser(email string) User {
ctx := context.Background()
var user User
err := db.NewSelect().Model(&user).Where("email = ?", email).Scan(ctx)
if err != nil {
return user
}
return user
}
package main
import (
"net/http"
"github.com/labstack/echo/v4"
)
type RequestBody struct {
Email string `json:"userEmail"`
}
func main() {
e := echo.New()
e.POST("/", func(c echo.Context) error {
var requestBody RequestBody
if err := c.Bind(&requestBody); err != nil {
return err
}
if requestBody.Email == "" {
return echo.NewHTTPError(http.StatusBadRequest)
}
var user = GetUser(requestBody.Email)
return c.JSON(http.StatusOK, user)
})
e.Start(":3000")
}
package main
import (
"log"
"net/http"
"github.com/gofiber/fiber/v2"
)
type RequestBody struct {
Email string `json:"userEmail"`
}
func main() {
app := fiber.New()
port := ":3000"
app.Post("/", func(c *fiber.Ctx) error {
var requestBody RequestBody
if err := c.BodyParser(&requestBody); err != nil {
return c.SendStatus(http.StatusBadRequest)
}
if requestBody.Email == "" {
return c.SendStatus(http.StatusBadRequest)
}
var user = GetUser(requestBody.Email)
return c.JSON(user)
})
log.Fatal(app.Listen(port))
}
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type RequestBody struct {
Email string `json:"userEmail"`
}
func main() {
r := gin.New()
r.POST("/", func(c *gin.Context) {
var requestBody RequestBody
c.BindJSON(&requestBody)
if requestBody.Email == "" {
c.AbortWithStatus(http.StatusBadRequest)
return
}
var user = GetUser(requestBody.Email)
c.JSON(http.StatusOK, user)
})
r.Run(":3000")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment