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

时间:2017-02-15 16:47:06

标签: 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个字符

1 个答案:

答案 0 :(得分:2)

行为符合预期。这种行为并不奇怪。

你的代码明显错误的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