Description

Incorrect response print containing an []uint8 values.

How to reproduce

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    g := gin.Default()
    g.GET("/test", test)
    g.Run(":9000")
}

func test(c *gin.Context) {
    resp := []uint8{1, 2}

    c.JSON(200, gin.H{
        "response": resp,
    })
}

Expectations

$ curl -XGET http://localhost:9000/test
{"response":[1, 2]}

Actual result

$ curl -XGET http://localhost:9000/test
{"response":"AQI="}

Environment

  • go version: 1.19.1 linux/amd64
  • gin version (or commit ref): 1.8.2
  • operating system: Ubuntu 20.10 (5.8.0-59-generic)

Comment From: rnotorni

I think this is a specification of the json package. Probably base64encoded.

uint8 should be Marshaler to avoid this.

Below is an example.

package main

import (
    "github.com/gin-gonic/gin"
    "fmt"
)

func main() {
    g := gin.Default()
    g.GET("/test", test)
    g.Run(":9000")
}

func test(c *gin.Context) {
    resp := uint8Slice{1, 2}

    c.JSON(200, gin.H{
        "response": resp,
    })
}

type uint8Slice []uint8

func (u uint8Slice) MarshalJSON() ([]byte, error){
    ret := make([]byte, 0, u.buffer())
    ret = append(ret, '[')
    for i, t := range u {
        if i != 0 {
            ret = append(ret, ',')
        }
        ret = append(ret, fmt.Sprintf("%v", t)...)
    }
    ret = append(ret, ']')
    return ret, nil
}

func (u uint8Slice) buffer() int {
    // '[' + ']' + (len(u) - 1) * ',' + len(u) * 255(max)
    return 2 + len(u) - 1 + len(u) * 3
}