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)
})`
select *you need to set the scanning order of struct props to that of order of column of tables. Better way is use namedselect id, title, ...