Skip to content

Instantly share code, notes, and snippets.

@adityarama1210
Last active January 25, 2021 07:39
Show Gist options
  • Save adityarama1210/dbf1ee0b5055d80bc0193a9a8ac43025 to your computer and use it in GitHub Desktop.
Save adityarama1210/dbf1ee0b5055d80bc0193a9a8ac43025 to your computer and use it in GitHub Desktop.
Example of save queries
func getUser(username string) (User, error) {
var userObject User
// RISK TO SQL INJECTION EXAMPLE
// assuming username = string values from client parameter and we have userObject with user type struct
query := `SELECT * FROM users WHERE username = ` + username
err := db.QueryRow(query).Scan(&userObject)
if err != nil {
// handle error
}
// continue processing...
}
func getUserSafe(username string) (User, error) {
var userObject User
// PREVENTING THE SQL INJECTION
// Instead, use this kind of parameter (mysql)
query := `SELECT * FROM users WHERE username = ?`
// or if you are using postgre, use $1, $2, $3 for the parameter
err := db.QueryRow(query, username).Scan(&userObject)
if err != nil {
// handle error
}
// continue processing
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment