duanchigeng4313 2017-02-15 16:47
浏览 416
已采纳

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

I have been trying to store a large string into a string variable in GoLang , but for some unknown reason GoLang is limiting the string to 64 Bytes in length

The main purpose of this string concatenation is to generate a couchbase's N1QL query at runtime based on user input

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]

In such a case if I debug on variable buffer, for example I can see it contains only until "SELECT * FROM DB WHERE DB.ITEM_NAME="+userInput[0]+OR" depending upon user input size it varies and it caps the string to 64th character

  • 写回答

1条回答 默认 最新

  • duancongduo4109 2017-02-15 20:55
    关注

    The behaviour is as expected. The behaviour is not strange.

    Your code creates obviously wrong 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)
    }
    

    Output:

    SELECT * FROM DB WHERE DB.ITEM_NAME=appleOR DB.ITEM_NAME=boy
    

    Here is a plausible solution:

    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)
    }
    

    Output:

    SELECT * FROM DB WHERE DB.ITEM_NAME="apple" OR DB.ITEM_NAME="boy";
    

    Note: Beware of SQL injection.

    References:

    The Go Programming Language Specification

    Couchbase: Query Language Tutorial

    Couchbase: Querying with N1QL

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样采集或者其它途径拿到全国最新个体工商户数据
  • ¥20 我是一名大学生,想学习java是自学还是报培训班呢
  • ¥15 pycharm该如何爬取网易云歌曲下的评论?
  • ¥15 java调用sap webservice问题
  • ¥20 如何完全复现何恺明resnet论文里的结果,有代码吗,获得论文中的结果(如下图)
  • ¥15 mysql如果表行行数小于1000条还需要分区吗
  • ¥20 有关matlab自定义特殊算符的问题
  • ¥15 第15届蓝桥杯选拔赛斗鱼养殖场
  • ¥15 在vivado的FIFO使用中,FIFO有没有提供可以输出内部存储空间状态的端口?
  • ¥15 C++ QT内存数据匹配对比指导