This repository was archived by the owner on Jan 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathStringBreakGood.go
More file actions
66 lines (58 loc) · 1.85 KB
/
StringBreakGood.go
File metadata and controls
66 lines (58 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"bytes"
"encoding/json"
"strings"
sq "github.com/Masterminds/squirrel"
)
// Good because there is no concatenation with quotes:
func saveGood(id string, version interface{}) {
versionJSON, _ := json.Marshal(version)
sq.StatementBuilder.
Insert("resources").
Columns("resource_id", "version_md5").
Values(id, sq.Expr("md5(?)", versionJSON)).
Exec()
}
// Good because quote characters are removed before concatenation:
func saveGood2(id string, version interface{}) {
versionJSON, _ := json.Marshal(version)
escaped := strings.Replace(string(versionJSON), "\"", "", -1)
sq.StatementBuilder.
Insert("resources").
Columns("resource_id", "version_md5").
Values(id, sq.Expr("\""+escaped+"\"")).
Exec()
}
// Good because quote characters are removed before concatenation:
func saveGood3(id string, version interface{}) {
versionJSON, _ := json.Marshal(version)
escaped := strings.ReplaceAll(string(versionJSON), "'", "")
sq.StatementBuilder.
Insert("resources").
Columns("resource_id", "version_md5").
Values(id, sq.Expr("'"+escaped+"'")).
Exec()
}
var globalReplacer = strings.NewReplacer("\"", "", "'", "")
// Good because quote characters are removed before concatenation:
func saveGood4(id string, version interface{}) {
versionJSON, _ := json.Marshal(version)
escaped := globalReplacer.Replace(string(versionJSON))
sq.StatementBuilder.
Insert("resources").
Columns("resource_id", "version_md5").
Values(id, sq.Expr("'"+escaped+"'")).
Exec()
}
// Good because quote characters are removed before concatenation:
func saveGood5(id string, version interface{}) {
versionJSON, _ := json.Marshal(version)
buf := new(bytes.Buffer)
globalReplacer.WriteString(buf, string(versionJSON))
sq.StatementBuilder.
Insert("resources").
Columns("resource_id", "version_md5").
Values(id, sq.Expr("'"+buf.String()+"'")).
Exec()
}