Created
September 23, 2022 06:42
-
-
Save raismaulana/e34053802809423e33a86d61946cb942 to your computer and use it in GitHub Desktop.
safe_column_query.go
This file contains 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 query(db *sql.DB, orderBy []string) { | |
query := fmt.Sprint("select id, name, grade from students ") | |
paging := "" | |
if len(opt.OrderBy) > 0 { | |
validColumn := map[string]string{ | |
"id": "id", | |
"created_at": "created_at", | |
} | |
paging = sanitizeOrderBy(orderBy, validColumn, paging) | |
} | |
query = query + paging | |
_, err := db.Query(query) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
} | |
func sanitizeOrderBy(cols []string, valid map[string]string, defaultString string) (res string) { | |
sort := map[string]string{ | |
"asc": "asc", | |
"desc": "desc", | |
} | |
i := 0 | |
for _, col := range cols { | |
ss := strings.Split(col, " ") | |
if v, ok := valid[ss[0]]; ok { | |
if i != 0 { | |
res += ", " | |
} | |
res += prefix + v + " " | |
if len(ss) > 1 { | |
if v, ok := sort[strings.ToLower(ss[1])]; ok { | |
res += v + " " | |
} | |
} | |
i++ | |
} | |
} | |
if res != "" { | |
res = "order by " + res | |
} else { | |
res = defaultString | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment