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

标签 go couchbase gocb

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

Couchbase: Query Language Tutorial

Couchbase: Querying with N1QL

关于go - 奇怪的行为 GoLang 将字符串存储到变量中的长度限制为 64 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42255334/

相关文章:

python - 将 netCDF 数据存储到 couchbase 中

java - UnfinishedStubbingException 模拟

go - 如何解决golang中 "missing Location in call to Date"的错误

go - 如何计算 golang 中移动窗口的最后 60 秒?

java - 如何在 couchbase 的全文搜索索引中对 desc/asc 进行排序

go - 如何使用 golang SDK 检查 couchbase 文档是否存在,而不检索完整内容?

go - Couchbase gocb 批量操作提供部分为空的结果

json - Go:如何将响应体变成请求体?

c++ - FlatBuffers 的多语言集成问题

go - 区分子文档操作错误和特定路径上丢失的数据