#generic SQL connection middleware for gin api functions

13 messages · Page 1 of 1 (latest)

plain grove
#

using a middleware function
you mean trough reqeust context? yeah dont do that. inject it to your type instead.
but that basically has to be unique for each endpoint function
what do you mean by it has tobe unique?
is there a way I can create this wrapper function so that it can be generically used for multiple different endpoint handlers?
you dont need wrapper, just pass it as argument or inject it to your handler type

vocal lion
#
type Database = *pgx.Conn

var DB Database

func ConnectDatabase() *pgx.Conn{
cctx := context.Background()
    conn, err := pgx.Connect(cctx, ConnectionString)
DB=conn 
}``` i am actually doing this for postgresql, just make a global variable and use it here and there.
#

Dunno how safe it is, like use this as the latest solution in the world.

granite dock
#

dont do that

#

its not horrible but its just not a good practice

plain grove
#

something like

type handlerX struct{
  db *sql.DB
}

func (h*handlerX) ServeHTTP(c*gin.Context) {
  // h.db.QueryXXXXX
}

or

func newHandlerX(db *sql.DB)  gin.HandlerFunc {
  return func (c *gin.Context) {
    // you can use db from here
  }
}
vocal lion
plain grove
#

oh yah, i forgot gin.HandlerFunc has different signature from http.HandlerFunc

vocal lion
#

Yeah it works now.

#

Sample:

#
func UploadFiles(c *pgx.Conn) gin.HandlerFunc {
    return func(c *gin.Context) {
        file, _ := c.FormFile("file")
        fmt.Println(file.Filename)
        dst := "./pdfFiles/" + file.Filename
        c.SaveUploadedFile(file, dst)
    }
} 
func main() {
    type Database = *pgx.Conn
    var DB Database
    router := gin.Default()
    router.MaxMultipartMemory = 8 << 20 // 8 MiB
    router.Handle("POST", "/upload", UploadFiles(DB))
    router.Run(":8080")
}
granite dock
#

i personally dont rly like that solution

#

i prefer using a method as a handler function but i dont think thats good practice lol