LoginSignup
0
0

More than 3 years have passed since last update.

Golang で CouchDB のデータを読む (Read)

Last updated at Posted at 2018-05-20

Golang で CouchDB のデータを読む方法です。
次のプログラムで作成したデータを読みます。
Golang で CouchDB を使う (Create)

couch_read.go
// ----------------------------------------------------------------
//
//  couch_read.go
//
//                  Mar/20/2018
//
// ----------------------------------------------------------------
package main

import (
    "fmt"
    "encoding/json"
    "io/ioutil"
    "log"
    "os"
    "net/http"
)

// ----------------------------------------------------------------
func main () {

    fmt.Printf ("*** 開始 ***\n")

    url := "http://localhost:5984/nagano/_all_docs"

    json_str := url_get_proc (url)

    var data map[string]interface{}
    if err := json.Unmarshal([]byte(json_str), &data); err != nil {
            panic(err)
        }

    fmt.Printf("total_rows = %f\n" , data["total_rows"])
    xx := data["rows"]
    yy := xx.([]interface{})

    for _,value := range yy {
        pp := value.(map[string]interface {})
        key := pp["id"].(string)
        url := "http://localhost:5984/nagano/" + key
        json_str_unit := url_get_proc (url)
    var unit_aa map[string]interface{}
    if err := json.Unmarshal([]byte(json_str_unit), &unit_aa); err != nil {
            panic(err)
        }

        name := unit_aa["name"].(string)
        population := unit_aa["population"].(float64)
        date_mod := unit_aa["date_mod"].(string)
        fmt.Printf ("%s\t%s\t%f\t%s\n",key,name,population,date_mod)

        }


    fmt.Printf ("*** 終了 ***\n")
}

// ----------------------------------------------------------------
func url_get_proc (url string) string {
    resp, err := http.Get (url)

    json_str := ""

    if err != nil {
        log.Fatalln(err)
        fmt.Printf("%s", err)
        os.Exit(1) 
    } else {
        defer resp.Body.Close()
         contents, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            fmt.Printf("%s", err)
            os.Exit(1)
            }
        json_str := string(contents)
//      fmt.Printf("%s\n", json_str)
    return (json_str)

        }

    return (json_str)
}

// ----------------------------------------------------------------
// ----------------------------------------------------------------
Makefile
couch_read: couch_read.go
    go build couch_read.go
clean:
    rm -f couch_read

実行コマンド

./couch_read

次のバージョンで確認しました。

$ go version
go version go1.13.8 linux/amd64
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0