Answer the question
In order to leave comments, you need to log in
How to store the data received from the user form in the database?
Such a problem is that all handlers are in a separate package and I would like to know how you can add / get data from the database from the AddUser / GetUserInfo functions or how to properly provide access from these functions to the DB variable so as not to move all handlers to package main.
import (
"handlers"
)
func main(){
//...
//установление соединения к postgres
DB, err = ConnectToDB()
//...
http.HandleFunc("/adduser/", handlers.AddUser)
http.HandleFunc("/getinfo/", handlers.GetUserInfo)
http.ListenAndServe(":8080", nil)
}
Answer the question
In order to leave comments, you need to log in
Can you do it like this
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 - доступ к db
}
func (u *User) GetInfo(w http.ResponseWriter, r *http.Request) {
// u.db - доступ к db
}
package main
import "handlers"
func main(){
//...
//установление соединения к postgres
DB, err = ConnectToDB()
userHandler := handlers.NewUser(DB)
http.HandleFunc("/adduser/", userHandler.Add)
http.HandleFunc("/getinfo/", userHandler.GetInfo)
http.ListenAndServe(":8080", nil)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question