douwang9650 2015-03-09 20:10
浏览 18
已采纳

解组XML以构造并转换为切片

I have a simple project in Golang which I use to learn this language. Main purpose of the "service" which I'm developing is to run a daemon to save URLs which are exposed as XML. This way I can "produce" my own read-later service. So far so good :). You can find the project here: https://github.com/rogierlommers/readinglist-golang

I'm using Gin-Gonic as the framework for serving html. I've already managed to read an xml file, unmarshal it but now I want to add some new data into this "thing". In other words: I think I need to convert it into a slice, but I don't know how to manage this.

F.e. the endpoint r.GET("/add/:url") should use the function util.AddRecord to insert the new url into the slice. But how?

[edit] Basically my problem can be viewed in this go playground: http://play.golang.org/p/Vx0s02E12R

  • 写回答

1条回答 默认 最新

  • douyi6960 2015-03-09 22:10
    关注

    In a comment on your question you asked:

    I first need to create a slice, right?

    The answer is yes, but you already have a slice in your ReadingListRecords struct:

    type ReadingListRecords struct {
        XMLName xml.Name `xml:"records"`
        Records []Record `xml:"record"`
    }
    

    So, you can simply call append on that slice and pass in a new record struct:

    records.Records = append(record.Records, Record{xml.Name{"", "record"}, 4, "url", "2015-03-09 00:00:00"})
    

    You could also expand the API for your ReadingListRecords structure to include a handy Append function:

    type RecordSet interface {
        Append(record Record) error
    }
    
    func (records *ReadingListRecords) Append(record Record) error {
        newRecords := append(records.Records, record)
    
        if newRecords == nil {
            return errors.New("Could not append record")
        } else {
            records.Records = newRecords
            return nil
        }
    }
    

    Adding an interface seems like a good idea since you would like to use this as a service in multiple applications.

    See my fork of your playground here.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题