分享一个Go json 踩坑记录
下面由golang教程栏目给大家分享一个Go json 踩坑记录,希望对需要的朋友有所帮助!
JSON,一种轻量级的资料交换语言,该语言以易于让人阅读的文字为基础,用来传输由属性值或者序列性的值组成的数据对象。现已经被广泛应用,Go 当然也提供了完备的支持,通过 encoding/json
便可方便的序列化及反序列化 JSON 数据。但是也有些关键点需要额外注意下。
Go 可使用 json.Marshal()
便捷的获取 JSON 数据,查看该函数对应的 godoc 文档,里面有这么一段话:
String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using HTMLEscape, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be disabled when using an Encoder, by calling SetEscapeHTML(false).
json.Marshal()
在进行序列化时,会进行 HTMLEscape 编码,会将 “<”, “>”, “&”, U+2028, 及 U+2029 转码成 “\u003c”,”\u003e”, “\u0026”, “\u2028”, 和 “\u2029”。这在正常使用时是没有问题的,但如果在对接第三方需要对 JSON 字符串进行取摘要比对时,如果一方未进行 HTMLEscape 编码,取出的摘要便会天差地别。上述文档中也给出了解决方法,通过 SetEscapeHTML(false)
来禁用便可。方法如下:
bf := bytes.NewBuffer([]byte{})jsonEncoder := json.NewEncoder(bf)jsonEncoder.SetEscapeHTML(false)_ = jsonEncoder.Encode(body)jsonStr := bf.String()
但是这样使用仍然会有些问题,json.Encoder.Encode()
会在 JSON 字符串后接一个 换行符,该函数源码如下:
// Encode writes the JSON encoding of v to the stream, // followed by a newline character. // // See the documentation for Marshal for details about the // conversion of Go values to JSON. func (enc *Encoder) Encode(v interface{}) error { if enc.err != nil { return enc.err } e := newEncodeState() err := e.marshal(v, encOpts{escapeHTML: enc.escapeHTML}) if err != nil { return err } // Terminate each value with a newline. // This makes the output look a little nicer // when debugging, and some kind of space // is required if the encoded value was a number, // so that the reader knows there aren't more // digits coming. e.WriteByte('\n') b := e.Bytes() if enc.indentPrefix != "" || enc.indentValue != "" { if enc.indentBuf == nil { enc.indentBuf = new(bytes.Buffer) } enc.indentBuf.Reset() err = Indent(enc.indentBuf, b, enc.indentPrefix, enc.indentValue) if err != nil { return err } b = enc.indentBuf.Bytes() } if _, err = enc.w.Write(b); err != nil { enc.err = err } encodeStatePool.Put(e) return err }
可以看出,该函数在进行序列化后又写入了一个 \n
字符。如果不需要该字符,则需要额外的将其剔除:
jsonStr := string(bf.Bytes()[:bf.bf.Len()])
以上是分享一个Go json 踩坑记录的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

在Go中安全地读取和写入文件至关重要。指南包括:检查文件权限使用defer关闭文件验证文件路径使用上下文超时遵循这些准则可确保数据的安全性和应用程序的健壮性。

如何为Go数据库连接配置连接池?使用database/sql包中的DB类型创建数据库连接;设置MaxOpenConns以控制最大并发连接数;设置MaxIdleConns以设定最大空闲连接数;设置ConnMaxLifetime以控制连接的最大生命周期。

Golang和C++分别是垃圾回收和手动内存管理编程语言,语法和类型系统各异。Golang通过Goroutine实现并发编程,C++通过线程实现。Golang内存管理简单,C++性能更强。实战案例中,Golang代码更简洁,C++性能优势明显。

Go框架架构的学习曲线取决于对Go语言和后端开发的熟悉程度以及所选框架的复杂性:对Go语言的基础知识有较好的理解。具有后端开发经验会有所帮助。复杂性不同的框架导致学习曲线差异。

Go框架凭借高性能和并发性优势脱颖而出,但也存在一些缺点,如相对较新、开发者生态系统较小、缺少某些功能。此外,快速变化和学习曲线可能因框架而异。Gin框架以其高效路由、内置JSON支持和强大的错误处理而成为构建RESTfulAPI的热门选择。

最佳实践:使用明确定义的错误类型(errors包)创建自定义错误提供更多详细信息适当记录错误正确传播错误,避免隐藏或抑制根据需要包装错误以添加上下文

如何在Golang单元测试中使用Gomega进行断言在Golang单元测试中,Gomega是一个流行且功能强大的断言库,它提供了丰富的断言方法,使开发人员可以轻松验证测试结果。安装Gomegagoget-ugithub.com/onsi/gomega使用Gomega进行断言以下是使用Gomega进行断言的一些常用示例:1.相等断言import"github.com/onsi/gomega"funcTest_MyFunction(t*testing.T){

如何使用Go框架文档?确定文档类型:官网、GitHub存储库、第三方资源。了解文档结构:入门指南、深入教程、参考手册。根据需要定位信息:使用组织结构或搜索功能。理解术语和概念:仔细阅读并理解新的术语和概念。实战案例:使用Beego创建一个简单的Web服务器。其他Go框架文档:Gin、Echo、Buffalo、Fiber。
