I'm new to Go and have a simple case of running a pgsql query using PGX when the API endpoint is called and returning the data. I haven't been able to get the results into a struct and return it. At the same time, I'm looking for a straightforward method without having to run nested loops to try to fetch the query contents.
package main
import (
"context"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4/pgxpool"
"log"
"net/http"
)
type Names struct {
ID int `json:"id"`
name string `json:"name"`
email string `json:"email"`
}
func main() {
router := gin.Default()
router.GET("/", getAll)
router.Run("localhost:8083")
}
func getAll(c *gin.Context) {
var alldata []Names
databaseUrl := "postgres://admin:admin@localhost:5432/golang"
dbPool, err := pgxpool.Connect(context.Background(), databaseUrl)
err := dbPool.Query(context.Background(), "select * from public.table1").Scan(&alldata)
if err != nil {
log.Printf("Error while getting all rows, Reason: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": http.StatusInternalServerError,
"message": "Something went wrong",
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"message": "All Names:",
"data": alldata,
})
return
defer dbPool.Close()
}
I'm getting the following errors with my code:
./main.go:33:6: no new variables on left side of :=
./main.go:33:21: multiple-value dbPool.Query() in single-value context
I tried the following and that doesn't work either:
rows, err := dbPool.Query(context.Background(), "select * from public.table1")
err = rows.Scan(&alldata)