奇怪的行为 GoLang 将字符串存储到变量中的长度限制为 64 字节

Strange behaviour GoLang limits storing of string into a variable to 64 bytes length

我一直在尝试将一个大字符串存储到 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 注入。

参考文献:

The Go Programming Language Specification

Couchbase: Query Language Tutorial

Couchbase: Querying with N1QL