Last active
May 22, 2024 18:37
-
-
Save mayankchoubey/da4dbd8654c3de196350056ace006b7c to your computer and use it in GitHub Desktop.
Fiber - HTTP + DB reads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment