duandaijian1583 2018-03-17 12:25
浏览 84
已采纳

如何在Go中管理文件内的状态?

Hard to admit it but I struggle to manage state in my cli go app. What I basically want is to manage a list of objects with their properties in a file on disk. I want to be able to add objects with their properties, update objects and/or their properties and remove them if needed.

I thought it would be easy to just have a yml or json file and edit it with some kind of library but it seems harder than it should for a go beginner like me.

An example would be the following json structure.

{
  "servers":
    [
      { "hostname": "gandalf", "ip": "192.168.1.10", "color": "red" },
      { "hostname": "bilbo", "ip": "192.168.1.11", "color": "blue" },
      { "hostname": "frodo", "ip": "192.168.1.12", "color": "yellow" }
    ]
}

Now I want to be able to add, remove and edit servers. It doesn't have to be json, yaml is fine as well.

Do you girls and guys have any suggestions (libs and an example) on how to do it? I already tried Viper but adding new objects or even editing the existing ones seems to be impossible.

  • 写回答

1条回答 默认 最新

  • douqiangchuai7674 2018-03-17 12:34
    关注

    For settings that need to be human readable and will primarily be edited by a human a yaml or json file seems fine.

    If the state is both written and read by the program itself and a full fledged database seems overkill then I would use a file based database. Probably a simple key/value store like boltdb or sqlite if the data needs more structure.

    I personally use boltdb in such a case, because it is very lightweight, superfast and I like its simplicity.

    -- edit --

    With json as a file structure the problem is that you need to write and read the entire file every single time. A edit would be a read of the entire file, unmarshalling the json, changing something in the unmarshalled object, marshalling it back to json and writing the entire file again.

    Thats why I would only use this for settings that the program reads once on startup and that's it.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c