一个引号引发的惨案---string转byte[]

背景

客户端通过https请求访问服务端,校验服务端body返回值必须 =="OK",满足=="OK"业务能正常运行,否则异常
server端:

b, _ := json.Marshal("OK")
c.Ctx.Output.Body(b)

client端:

respBody, _ := ioutil.ReadAll(resp.Body)
content:=string(respBody)
if content == "OK" {
    ... //success
}

调试中发现死活进不到content == "OK"的判断,将content的值print出来也为"OK",但就是进不到相等的判断分支,导致业务一直异常,摸索半天后发现是string和byte[]转换的问题,后将server端修改如下,终于运行正常

var bytesOK = []byte("OK")
c.Ctx.Output.Body(bytesOK)

结论

string和byte[] 转换,需要匹配

  • Marshal 匹配 Unmarshal
  • []byte("OK") 匹配 string(bytesOK)
  • string 转为byte[],Marshal 会比 []byte("OK") 方式前后各多一个 "(ASCII 34)

测试demo源码:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var bytesOK = []byte("OK")
    marshalBytesOK, _ := json.Marshal("OK")

    fmt.Println("bytesOK:", bytesOK)
    fmt.Println("marshalBytesOK:", marshalBytesOK)

    ok1 := string(bytesOK)
    fmt.Println("ok1:", ok1)
    fmt.Println("is ok1 == OK:", ok1 == "OK")

    ok2 := string(marshalBytesOK)
    fmt.Println("ok2:", ok2)
    fmt.Println("is ok2 == OK:", ok2 == "OK")

    var ok3 string
    json.Unmarshal(marshalBytesOK, &ok3)
    fmt.Println("ok3:", ok3)
    fmt.Println("is ok3 == OK:", ok3 == "OK")

}

输出如下:

bytesOK: [79 75]
marshalBytesOK: [34 79 75 34]
ok1: OK
is ok1 == OK: true
ok2: "OK"
is ok2 == OK: false
ok3: OK
is ok3 == OK: true

你可能感兴趣的:(一个引号引发的惨案---string转byte[])