I have been learning golang in the last couple days, but I am so frustrated because I am trying to make a simple CRUD api and I can't create a simple user.
I am using Fiber (very similar to Express.js) with golang's sql with mysql driver.
Here is my entire handler:
func CreateUser(c *fiber.Ctx) {
type InputData struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
// input data
input := new(InputData)
c.BodyParser(input)
// connects to db
db, err := sql.Open("mysql", "root:root@tcp(localhost:8877)/sql")
if err != nil {
log.Fatal(err)
}
// the code freezes here
if err := db.Ping(); err != nil {
log.Fatal(err)
}
fmt.Println("Connected to the MySQL database! ")
// defer will close the connection when the main function has finished
defer db.Close()
// inserts the user
prep, err := db.Prepare("INSERT INTO users (username, email, password) VALUES (?,?,?)")
if err != nil {
panic(err.Error())
}
result, err := prep.Exec(input.Username, input.Email, input.Password)
if err != nil {
panic(err.Error())
}
// response
c.JSON(result)
}
Am I doing something I shouldn't be?
(btw, this is almost my entire code, I removed the "err" handling)
Have a nice day guys!