参数的多格式支持

10 阅读1分钟

参数的多格式支持

http://127.0.0.1:8080/user/login?Mobile=13000000000&Captcha=1234
http://127.0.0.1:8080/user/login?Mobile={"Value":"13000000000"}&Captcha={"Value":"1234"}

书接上文,有没有一种方式可以同时支持上面两种方式的参数格式呢?

解决方式:自定义json解析

type Mobile struct {
    Value string `binding:"number,mobile"`
}

func (o *Mobile) UnmarshalJSON(data []byte) error {
    if data[0] != '{' {
        o.Value = gjson.ParseBytes(data).String()
        return nil
    }
    
    result := gjson.GetBytes(data, "Value")
    if result.Exists() {
        o.Value = result.String()
    }
    return nil
}

我们自定义了UnmarshalJSON函数,通过判断第一个字节是否是{来判断参数格式是json对象还是普通参数,然后赋值Value字段。

注意,json规范中,1234数字型是合法的json字符串,tom不是合法的json字符串,"tom"才是合法的json字符串。

http://127.0.0.1:8080/users?Nickname=tom
解析报错:invalid character 'o' in literal true (expecting 'r')

http://127.0.0.1:8080/users?Nickname="tom"
解析成功

这无形中又给接口对接增加了不便捷,解决方式也很简单,我们摒弃HTTP GET方式,通过POST提交json的方式规避了字符串不合法的问题。

curl --header 'Content-Type: application/json' --data '{"Mobile": "13000000000","Captcha": "1234"}' http://localhost:8080/user/login

下文中会统一这种方式。

源码链接