我一直在尝试将一个大字符串存储到 GoLang 中的字符串变量中,但由于某些未知原因,GoLang 将字符串的长度限制为 64 字节
这个字符串连接的主要目的是在运行时根据用户输入生成 couchbase 的 N1QL 查询
userInput := []string{"apple", "boy", "cat", "dog"}
var buffer string
buffer = "SELECT * FROM DB WHERE DB.ITEM_NAME="+userInput[0]+
"OR DB.ITEM_NAME="+userInput[1]
在这种情况下,如果我在变量缓冲区上进行调试,例如,我可以看到它只包含直到“SELECT * FROM DB WHERE DB.ITEM_NAME =”+userInput[0]+OR”,具体取决于用户输入大小,它会变化并且它将字符串限制为第 64 个字符
最佳答案
行为符合预期。这种行为并不奇怪。
您的代码创建了明显错误的 Couchbase N1QL:
package main
import (
"fmt"
)
func main() {
userInput := []string{"apple", "boy", "cat", "dog"}
var buffer string
buffer = "SELECT * FROM DB WHERE DB.ITEM_NAME=" + userInput[0] +
"OR DB.ITEM_NAME=" + userInput[1]
fmt.Println(buffer)
}
输出:
SELECT * FROM DB WHERE DB.ITEM_NAME=appleOR DB.ITEM_NAME=boy
这是一个合理的解决方案:
package main
import (
"fmt"
)
func main() {
userInput := []string{"apple", "boy", "cat", "dog"}
query := fmt.Sprintf(
`SELECT * FROM DB WHERE DB.ITEM_NAME=%q OR DB.ITEM_NAME=%q;`,
userInput[0], userInput[1],
)
fmt.Println(query)
}
输出:
SELECT * FROM DB WHERE DB.ITEM_NAME="apple" OR DB.ITEM_NAME="boy";
注意:谨防 SQL 注入(inject)。
引用资料:
The Go Programming Language Specification
关于go - 奇怪的行为 GoLang 将字符串存储到变量中的长度限制为 64 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42255334/