首页 > 文章列表 > 检查Golang Web 应用程序的输入是否有效的 utf-8 编码安全措施

检查Golang Web 应用程序的输入是否有效的 utf-8 编码安全措施

266 2024-02-21
问题内容

根据几个最佳实践文档,最好检查输入数据是否为 ​​utf-8。

在我的项目中,我使用 gin 并使用 go-playground/validator 进行验证。有一个“ascii”验证器,但没有“utf-8”验证器。

我找到了 https://pkg.go.dev/unicode/utf8#validstring,我想知道用它来检查输入是否有任何帮助,或者是否给出了,因为 go 本身在内部使用 unicode?

这是一个例子:

package main

import (
    "net/http"

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

type User struct {
    Name string `json:"name" binding:"required,alphanum"`
}

func main() {
    r := gin.Default()
    r.POST("/user", createUserHandler)
    r.Run()
}

func createUserHandler(c *gin.Context) {
    var newUser User
    err := c.ShouldBindJSON(&newUser)

    if err != nil {
        c.AbortWithError(http.StatusBadRequest, err)
        return
    }

    c.Status(http.StatusCreated)
}

调用c.shouldbindjson后是否确保newuser中的名称是utf-8编码的?使用utf8.validstring检查name有什么好处吗?


正确答案


Gin 使用标准 encoding/json 包来解组 JSON 文档。 该包的文档说明

解组带引号的字符串时,无效的 UTF-8 或无效的 UTF-16 代理项对不会被视为错误。相反,它们被 Unicode 替换字符 U+FFFD 替换。

确保解码后的字符串值是有效的 UTF-8。使用 utf8.ValidString 检查字符串值没有任何优势。

根据应用程序要求,您可能需要检查并处理 Unicode 替换字符“�”。旁白:正如本答案中的 � 所示,SO 像处理任何其他字符一样处理 Unicode 替换字符。

Go 本身在内部使用 Unicode?

某些语言功能使用 UTF-8 编码(字符串范围、[]rune 和字符串之间的转换),但这些功能不限制字符串中可以存储的字节。字符串可以包含任何字节序列,包括无效的 UTF-8。