Golang で CouchDB のデータを削除する方法です。
次のプログラムで作成したデータを削除します。
Golang で CouchDB を使う (Create)
couch_delete.go
// ----------------------------------------------------------------
//
// couch_delete.go
//
// May/20/2018
//
// ----------------------------------------------------------------
package main
import (
"fmt"
"encoding/json"
"os"
"strings"
"net/http"
"log"
"io"
"io/ioutil"
)
// ----------------------------------------------------------------
func main () {
fmt.Printf ("*** 開始 ***\n")
key_in := os.Args[1]
fmt.Printf ("key_in = %d\n" , key_in)
url := "http://localhost:5984/nagano/" + key_in
json_str := url_get_proc (url)
fmt.Printf (json_str + "\n")
var unit_aa map[string]interface{}
if err := json.Unmarshal([]byte(json_str), &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_in,name,population,date_mod)
url_target := url + "?rev=" + unit_aa["_rev"].(string)
deleteRequest(url_target,strings.NewReader(""))
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)
}
// ----------------------------------------------------------------
func deleteRequest(url string, data io.Reader) {
client := &http.Client{}
req, err := http.NewRequest(http.MethodDelete, url, data)
if err != nil {
// handle error
log.Fatal(err)
}
_, err = client.Do(req)
if err != nil {
// handle error
log.Fatal(err)
}
}
// ----------------------------------------------------------------
// ----------------------------------------------------------------
Makefile
couch_delete: couch_delete.go
go build couch_delete.go
clean:
rm -f couch_delete
実行コマンドの例
./couch_delete t2030
次のバージョンで確認しました。
$ go version
go version go1.13.8 linux/amd64