dth54864 2015-01-10 00:39 采纳率: 0%
浏览 200

使用Golang从PUT / PATCH忽略JSON有效负载中不需要的字段的最佳方法是什么?

I have a situation where people consuming our API will need to do a partial update in my resource. I understand that the HTTP clearly specifies that this is a PATCH operation, even though people on our side are used to send a PUT request for this and that's how the legacy code is built.

For exemplification, imagine the simple following struct:

type Person struct {
    Name string
    Age int
    Address string
}

On a POST request, I will provide a payload with all three values (Name, Age, Address) and validate them accordingly on my Golang backend. Simple.

On a PUT/PATCH request though, we know that, for instance, a name never changes. But say I would like to change the age, then I would simply send a JSON payload containing the new age:

PUT /person/1 {age:30}

Now to my real question: What is the best practice to prevent name from being used/updated intentionally or unintentionally modified in case a consumer of our API send a JSON payload containing the name field?

Example:

PUT /person/1 {name:"New Name", age:35} 

Possible solutions I thought of, but I don't actually like them, are:

  1. On my validator method, I would either forcibly remove the unwanted field name OR respond with an error message saying that name is not allowed.

  2. Create a DTO object/struct that would be pretty much an extension of my Person struct and then unmarshall my JSON payload into it, for instance

    type PersonPut struct { Age int Address string }

In my opinion this would add needless extra code and logic to abstract the problem, however I don't see any other elegant solution.

I honestly don't like those two approaches and I would like to know if you guys faced the same problem and how you solved it.

Thanks!

  • 写回答

5条回答 默认 最新

  • douba4824 2015-01-10 01:03
    关注

    I am not proficient on Golang but I believe a good strategy would be converting your name field to be a read-only field.

    For instance, in a strictly object-oriented language as Java/.NET/C++ you can just provide a Getter but not a Setter.

    Maybe there is some accessor configuration for Golang just like Ruby has....

    If it is read-only then it shouldn't bother with receiving a spare value, it should just ignore it. But again, not sure if Golang supports it.

    评论

报告相同问题?

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢