doumi0737 2015-08-03 15:22
浏览 22
已采纳

带有标签的Go结构字段的转换

I am really stuck here with a seemingly trivial problem in Go: I have a Golang microservice, which outputs data in json format. Let's say I have a simple struct with json tags for this result:

type Result struct {
    Name string `json:"name"`
    Age int `json:"age"`
}

In the code part where the data is actually pulled out of the database, I have a quite similar struct, like this:

type ResultBackend struct {
    Name string `bson:"fullName"`
    Age int `bson:"age"`
}

The struct fields are similar, except the different tags. I would like to keep things simple, and return just one struct from the backend service (ResultBackend), which can then be send as a JSON response, like this:

func process() Result {
    var result ResultBackend
    ... do a MongoDB query here and store results in result variable ...
    return result
}

This certainly would not work, because we have two different structs here. Of course one solution would be to embed both tags in one struct like so:

type Result struct {
    Name string `json:"name" bson:"fullName"`
    Age int `json:"age bson:"age"`
}

and then use this struct in the main code and the "process" function. This works, but this seems like "poisoning" the Result struct of the main code with the bson tags. What, for instance, if the backend result is a XML file? I'd have to add xml tags to the struct as well. Or maybe someday tags some very obsure database adapter. This doesn't seem to be the cleanest approach in my eyes. I'd rather have a clean Result struct in the main code, and simply to a conversion from one struct to another.

Is there any easy way doing that, or do I really have to copy all the fields of a ResultBackend struct to a new Result struct and return that? Or I am trying to over-simplify my code here? :)

Cheers!

  • 写回答

1条回答 默认 最新

  • duangou1868 2015-08-03 15:41
    关注

    What I'd do is create a separate type for every "serialisation format" if you will. This approach has several advantages:

    • Your concerns are separated.

    • JSON un/marshalling doesn't interfere with BSON/XML, so you can add any kind of additional struct fields (like xml.Name for example).

    • You can actually create several such types for different APIs that need different parameters.

    The only disadvantage I see is that it's more code and even more code to move data between those. Ultimately it's up to you and your application design. If you're sure that your JSON/BSON will stay the same, you can use one type. Otherwise, I'd recommend specialisation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!