json - Golang slices of struct or newbie trouble building REST -
and need help. wanted build simple api , stuck problem. i've choose gin , database/sql postgres driver
package main import ( "database/sql" "fmt" "github.com/gin-gonic/gin" _ "github.com/lib/pq" ) func main() { router := gin.default() router.get("/search/:text", searchword) router.run(":8080") }
i need make query db , make json out of request.
func checkerr(err error) { if err != nil { panic(err) } } type message struct { ticket_id int `json:"ticket_id"` event string `json:"event"` } func searchword(c *gin.context) { word := c.params.byname("text") db, err := sql.open("postgres", "host=8.8.8.8 user= password= dbname=sample") defer db.close() checkerr(err) rows, err2 := db.query("select ticket_id,event ....$1, word) checkerr(err) rows.next() { var ticket_id int var event string err = rows.scan(&ticket_id, &event) checkerr(err) fmt.printf("%d | %s \n\n", ticket_id, event) } }
this coda working nice, when need make json. need make struct of row
type message struct { ticket_id int `json:"ticket_id"` event string `json:"event"` }
an need create slice , , append every rows.next() loop answer browser json...
c.json(200, messages)
but how that...don't know :(
i'm going cheat little here , fix few things along way:
first: open database connection pool once @ program start-up (and not on every request).
second: we'll use sqlx make easier marshal our database rows our struct.
package main var db *sqlx.db func main() { var err error // sqlx.connect checks connection works. // sql.open "establishes" pool, doesn't ping db. db, err = sqlx.connect("postgres", "postgres:///...") if err != nil { log.fatal(err) } router := gin.default() router.get("/search/:text", searchword) router.run(":8080") } // in_another_file.go type message struct { ticketid int `json:"ticket_id" db:"ticket_id"` event string `json:"event" db:"event"` } func searchword(c *gin.context) { word := c.params.byname("text") // create slice of structs marshal our rows var messages []*message{} // our db connection pool safe use concurrently here err := db.select(&messages, "select ticket_id,event ....$1, word) if err != nil { http.error(c.writer, err.error(), 500) return } // write out using gin-gonic's json writer. c.json(200, messages) }
i hope that's clear. sqlx
takes care of calling rows.close()
you, otherwise leave connections hanging.
Comments
Post a Comment