News for hackers. Stuff that matters.
Re:Go Concurrency by buro9 on Thursday March 28, 2013 @10:38AM (#5455004)
I was at the talk last night and jgrahamc said that nearly all of the code in the slide deck is what they are doing in production code, though simplified to fit on a slide essentially.

Things like the memory recycler are needed to help keep the high tide of memory usage as low as possible (prior to the garbage collector coming along and taking care of stuff).

One of the other talks covered ways in which you could deal with JSON, and it is pretty trivial. The example used in that talk was how to solve a semi-structured JSON file (where items in an array were of differing structure), but even then working with JSON remains pretty easy and the built-in marshalling can even be over-ridden if you have such a need (for example to map a complex type into a simple JSON representation).

Anyhow, your scenario... a few snippets to help you see it, if you need a working example you can run locally just ask and I'll knock one up.

This is a struct:

    type MyRecord struct {
        Id int64 `json:"id"`,
        Title string `json:"title,omitempty"`,
    }
And it might match a database table like this:

    CREATE TABLE my_records (
        record_id bigint NOT NULL,
        title character varying(150)
    )
That struct has some tags after the field declarations that describe to the JSON processor how to marshal an instance of MyRecord into some JSON.

If that table were Postgres you would probably use the driver located here: https://github.com/lib/pq

You could connect to the database and populate your record from the database thus:

    db, err := sql.Open("postgres", myConnectionString)
    // do something if err != nil
    defer db.Close()

    stmt, err := db.Prepare(`SELECT record_id, title FROM my_records LIMIT 1 OFFSET 0`)
    // do something if err != nil
    defer stmt.Close()
    
    row := stmt.QueryRow()
    
    record := new(MyRecord)
    err = row.Scan(&record.Id, &record.Title)
    // do something if err != nil
Now that your record is populated from the database, you can marshal it to JSON:

    output, err = json.Marshal(record)
    // do something if err != nil
If your row in the database looked like:

    INSERT INTO my_records (record_id, title) VALUES (1,"Hello World")
Then you JSON now in the output var looks like:

    {"id":1,"title":"Hello World"}
The example in the sibling comment shows the essence of the whole program with the email bit too, but this post shows some of the detail of actually fetching the record and marshalling it... there isn't much to it.

There are no comments on this comment yet.