1. 程式人生 > >記錄一個go實現 etcd存取的小demo以便使用

記錄一個go實現 etcd存取的小demo以便使用

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)


var (
client  = &http.Client{}
baseurl = "http://"
)


//url --etcd Url
func read(key string) {
url := baseurl + key
request, erro := http.NewRequest("GET", url, nil)
if erro != nil {
log.Print(erro)
}
//發起請求
response, err := client.Do(request)
if err != nil {
log.Print(err)
}
if response.StatusCode != 200 {
log.Print("讀取資料失敗")
}
//從響應bidy讀取資料
object, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Print(err)
}
fmt.Println(string(object))


}


func set(key, value string) {
url := baseurl + key
request, err := http.NewRequest("PUT", url, strings.NewReader("value="+url.QueryEscape(value)))
if err != nil {
log.Print(err)
}
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
reponse, err := client.Do(request)
if err != nil {
log.Print(err)
}
if reponse.StatusCode != 200 {
log.Print("存入資料失敗")
}
object, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Print(err)
}
fmt.Println(string(object))
}