Home > Net >  How to fill a Struct type map from Mysql
How to fill a Struct type map from Mysql

Time:11-04

Im new in Golang. This is the structure that I want to load and the problem is that there is the map [string] ChannelST which I don't know how to fill from Mysql

type StreamST struct {
    Name     string
    Channels map[string]ChannelST
}

type ChannelST struct {
    Name             string
    URL              string
    OnDemand         bool
    Debug            bool
    Status           int
    runLock          bool
    codecs           []av.CodecData
    sdp              []byte
    signals          chan int
    hlsSegmentBuffer map[int]SegmentOld
    hlsSegmentNumber int
    clients          map[string]ClientST
    ack              time.Time

CodePudding user response:

The exact answer depends a lot on your database schema. I will attempt to give a generic answer. You could go 2 ways(as far as I know):

  1. Use a library which does a lot of you in this regard like sqlx or gorm. These libraries will look at the exported fields in your struct and tags to automatically fill them.
  2. Use the standard sql library and do everything yourself. In this case you will need to use the Rows.Scan function to fill structs yourself.

In any case, your StreamST struct contains a map, which is a collection, so I assume you are joining two tables. In GORM you can specify relations and the library will take this into account. Though I am not sure if this only works for slices or maps as well, since GORM doesn't know which field of struct to use as index for the map.

When using the standard library, the rows returned are exactly the same as the result from the SQL query, so fields of your left table will be repeated and thus you need to write your own logic to turn this list of fields into the proper structure.

Lastly, you have a number of custom types like av.CodecData. If these correspond to single fields but in a custom format, you can implement custom encoding/decoding by letting these structs implement sql.Scanner and driver.Valuer interfaces.

  • Related