登录
首页 >  Golang >  Go问答

自定义 JSON 编组器支持 Base64 编码 | 在调用 routes.Temp 类型的 MarshalJSON 时发生错误:无效字符“e”

来源:stackoverflow

时间:2024-02-29 10:09:25 424浏览 收藏

一分耕耘,一分收获!既然都打开这篇《自定义 JSON 编组器支持 Base64 编码 | 在调用 routes.Temp 类型的 MarshalJSON 时发生错误:无效字符“e”》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我想编写一个自定义编组器。我已经完成了以下实现。

type temp struct {
    time time.time
}

func (t temp) marshaljson() ([]byte, error) {
    type __ temp
    var x = __(t)
    var buff bytes.buffer
    if err := json.newencoder(&buff).encode(x); err != nil {
        return nil, err
    }
    raw := buff.bytes()
    dst := make([]byte, base64.stdencoding.encodedlen(len(raw)))
    base64.stdencoding.encode(dst, raw)
    return dst, nil
}

路由器逻辑如下。

func health(c *gin.context) {
    c.json(http.statusok, gin.h{
        "token": temp{time.now()},
    })
}

运行后,我收到如下错误。

2022/08/06 00:36:53 [recovery] 2022/08/06 - 00:36:53 panic recovered:
get /health http/1.1
host: localhost:9000
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
accept-encoding: gzip, deflate, br
accept-language: en-us,en;q=0.9
cache-control: max-age=0
connection: keep-alive
sec-ch-ua: ".not/a)brand";v="99", "google chrome";v="103", "chromium";v="103"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macos"
sec-fetch-dest: document
sec-fetch-mode: navigate
sec-fetch-site: none
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: mozilla/5.0 (macintosh; intel mac os x 10_15_7) applewebkit/537.36 (khtml, like gecko) chrome/103.0.0.0 safari/537.36


json: error calling marshaljson for type routes.temp: invalid character 'e' looking for beginning of value
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/render/json.go:56 (0x19448bd)
    json.render: panic(err)
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:915 (0x194fd3c)
    (*context).render: if err := r.render(c.writer); err != nil {
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:958 (0x19502f3)
    (*context).json: c.render(code, render.json{data: obj})
/users/vajahat/work/dotpe/order/routes/routes.go:43 (0x1f61b9c)
    health: c.json(200, gin.h{
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:165 (0x194a0bc)
    (*context).next: c.handlers[c.index](c)
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/recovery.go:99 (0x195c437)
    customrecoverywithwriter.func1: c.next()
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:165 (0x194a0bc)
    (*context).next: c.handlers[c.index](c)
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/logger.go:241 (0x195ae31)
    loggerwithconfig.func1: c.next()
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:165 (0x194a0bc)
    (*context).next: c.handlers[c.index](c)
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:489 (0x1958a7b)
    (*engine).handlehttprequest: c.next()
/users/vajahat/go/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:445 (0x1958584)
    (*engine).servehttp: engine.handlehttprequest(c)
/usr/local/go/src/net/http/server.go:2947 (0x14ca5d3)
    serverhandler.servehttp: handler.servehttp(rw, req)
/usr/local/go/src/net/http/server.go:1991 (0x14c413b)
    (*conn).serve: serverhandler{c.server}.servehttp(w, w.req)
/usr/local/go/src/runtime/asm_amd64.s:1594 (0x1072640)
    goexit: byte    $0x90   // nop

[gin] 2022/08/06 - 00:36:53 | 500 |   5.20548072s |             ::1 | get      "/health"

错误json:为类型routes.temp调用marshaljson时出错:寻找值开头的无效字符'e'困扰了我很长时间。

我期待如下输出。

{
    "token":"eyJUaW1lIjoiMjAyMi0wOC0wNlQwMDo0ODoyOS4yNDEzNTUrMDU6MzAifQo="
}

在调试器中,它正在工作。 我相信问题出在渲染时间。我想将上面的内容作为输出。

非常感谢任何建议或帮助。


正确答案


您的 marshaljson() 函数必须返回有效的 json 值;但是,您的示例生成原始 base64 字符串,它不是有效的 json。

您可以通过简单地将当前返回值括在引号中以使其成为有效的 json 字符串来修复此问题!

b64len := base64.StdEncoding.EncodedLen(len(raw))
dst := make([]byte, b64len+2)
base64.StdEncoding.Encode(dst[1:], raw)
dst[0], dst[b64len+1] = '"', '"'
return dst, nil

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>