Last active
January 25, 2021 07:39
-
-
Save adityarama1210/dbf1ee0b5055d80bc0193a9a8ac43025 to your computer and use it in GitHub Desktop.
Example of save queries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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