How to save data obtained from a custom form in the database?

A problem that all handler s are in a separate package and I would like to know how the functions of the AddUser/GetUserInfo you can add/get data from database or how to ensure the access of these functions to a variable DB to move all the handlers in the package main.
import (
"handlers"
)
func main(){
//...
 //establish connection to postgres
 DB, err = ConnectToDB()
//...
 http.HandleFunc("/adduser/", handlers.AddUser)
 http.HandleFunc("/getinfo/", handlers.GetUserInfo)
 http.ListenAndServe(":8080", nil)
}
April 19th 20 at 12:48
1 answer
April 19th 20 at 12:50
You can do so
package "handlers"

import "database/sql"

type User struct {
 db *sql.DB
}

func NewUser(db *sql.DB) *User {
 return &User{db: db}
}

func (u *User) Add(w http.ResponseWriter, r *http.Request) {
 // u.db - access db
}

func (u *User) GetInfo(w http.ResponseWriter, r *http.Request) {
 // u.db - access db
}


package main

import "handlers"

func main(){
//...
 //establish connection to postgres
 DB, err = ConnectToDB()

 userHandler := handlers.User(DB)

 http.HandleFunc("/adduser/", userHandler.Add)
 http.HandleFunc("/getinfo/", userHandler.GetInfo)
 http.ListenAndServe(":8080", nil)
}

Find more questions by tags Go