Golang gin rest api post and get

With golang gin rest api I create title, body, date, titles and contents fields, send to postman and save database. The post operation is running successfully, but when I receive the data, I get an error like this: “error”: “failed to import jobs” get doesn’t work but post works code parts are as follows

main.go:

type Job struct {
    ID       int       `db:"id" json:"id"`
    Title    string    `db:"title" json:"title"`
    Body     string    `db:"body" json:"body"`
    Date     time.Time `db:"date" json:"date"`
    Titles   [4]string `db:"titles" json:"titles"`
    Contents [4]string `db:"contents" json:"contents"`
}

func main() {
r.POST("/job", func(c *gin.Context) {
    var job Job
    if err := c.ShouldBindJSON(&job); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    // insert job into database
    query := "INSERT INTO table (title, body,  titles, contents ,date) VALUES ($1, $2, $3,  $4, $5) RETURNING id"
    var id int
    err := db.QueryRow(query, job.Title, job.Body, pq.Array(job.Titles), pq.Array(job.Contents), time.Now()).Scan(&id)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create job"})
        return
    }

    job.ID = id

    c.JSON(http.StatusOK, job)
})

r.GET("/jobs", func(c *gin.Context) {
    // retrieve all jobs from database
    rows, err := db.Query("SELECT * FROM table")
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve jobs"})
        return
    }
    defer rows.Close()

    // iterate over rows and store in slice of Jobs
    jobs := []Job{}
    for rows.Next() {
        var job Job
        err := rows.Scan(&job.ID, &job.Title, &job.Body, &job.Date, &job.Titles, &job.Contents)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve jobs"})
            return
        }
        jobs = append(jobs, job)
    }

    c.JSON(http.StatusOK, jobs)
})`

You should log the err somewhere so you know the underlying cause.

1 Like

This error comes in error section : " failed to retrieve jobs"

jobs := []Job{}
for rows.Next() {
var job Job
err := rows.Scan(&job.ID, &job.Title, &job.Body, &job.Date, &job.Titles, &job.Contents)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{“error”: “failed to retrieve jobs”})
return
}
jobs = append(jobs, job)

// Debugging statements
fmt.Printf("Retrieved job with ID %d\n", job.ID)
fmt.Printf("Title: %s\n", job.Title)
fmt.Printf("Body: %s\n", job.Body)
fmt.Printf("Date: %s\n", job.Date)
fmt.Printf("Titles: %v\n", job.Titles)
fmt.Printf("Contents: %v\n", job.Contents)

}

What I mean is your select statement returns rows and an err. That err likely has information in it explaining why your SQL statement failed. When you check if err != nil, you should log err itself so you know what the problem is:

rows, err := db.Query("SELECT * FROM table")
if err != nil {
    c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve jobs"})
    // Returning a general "failed to retrieve jobs" message here
    // is fine for your API, but you should log `err` itself
    // somewhere in here:
    //
    // TODO: import "log"
    log.Print("error getting jobs: %v", err)
    return
}

it works but the values ​​are empty

Can you clarify which values are empty?

Values ​​are not coming when I get it, blank page but 200 freezes

Sorry, @Coding_Yaz, I’m having a hard time understanding:

The log.Print change I suggested wasn’t to fix an issue, it was just to get more information about the cause of the SQL statement failing. Did you see an error and make a change to address it, or are you saying that after adding a call to log.Print, now you’re not getting an error, but the site is somehow hanging? Are you getting any output to your console when you run your Go program?

I’m not sure what you mean here: Are you getting a blank page and/or a 200 response, or is the page “freezing?” I would think “freezing” means that you’re not getting a response at all; is that happening? Or are you perhaps running some client-side javascript that’s supposed to do something with the response but it’s freezing?

sorry i just saw this in debugging

2023/03/21 17:25:21 Error scanning job from database: sql: Scan error on column index 3, name “titles”: unsupported Scan, storing driver.Value type string into type *time.Time

That error seems to indicate that you’re scanning your titles column into your &job.Date field. I would recommend instead of writing select * from ... that you select the columns explicitly so that adding/removing/reordering columns in the future is less likely to produce errors like these.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.