Add /user/{userId} (#24)
Closes #9 Reviewed-on: #24
This commit was merged in pull request #24.
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
@@ -30,18 +31,36 @@ func getUsers(c *gin.Context) {
|
||||
c.IndentedJSON(http.StatusOK, users)
|
||||
}
|
||||
|
||||
func main() {
|
||||
config := ServerConfig{
|
||||
Datasource: os.Getenv("DB_PATH"),
|
||||
func getUser(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
log.Printf("Invalid user ID: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
|
||||
return
|
||||
}
|
||||
start(context.Background(), &config)
|
||||
|
||||
user, err := db.GetUser(userId)
|
||||
if err != nil {
|
||||
log.Printf("Error getting user: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
|
||||
return
|
||||
}
|
||||
if user == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.IndentedJSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
func start(ctx context.Context, config *ServerConfig) {
|
||||
db = NewDb(config.Datasource)
|
||||
defer db.db.MustClose()
|
||||
|
||||
router := gin.Default()
|
||||
router.GET("/api/users", getUsers)
|
||||
router.GET("/api/user/:userId", getUser)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":" + config.Port,
|
||||
@@ -61,3 +80,10 @@ func start(ctx context.Context, config *ServerConfig) {
|
||||
log.Fatalf("Server forced to shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
config := ServerConfig{
|
||||
Datasource: os.Getenv("DB_PATH"),
|
||||
}
|
||||
start(context.Background(), &config)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user