当前位置:   article > 正文

go之构建简单的web服务器3.0_golang web3

golang web3

引入etcd模块,实现对etcd的增删改。目录架构如下

在这里插入图片描述

etcd.go代码

package storage

import (
	"context"
	"time"
	"fmt"
    "errors"
	clientv3 "go.etcd.io/etcd/client/v3"
)

//连接etcd
func ConnectEtcd() (*clientv3.Client,error) {
    cli, err := clientv3.New(clientv3.Config{
        Endpoints:   []string{"127.0.0.1:2379"},
        DialTimeout: 5 * time.Second,
    })
    if err != nil {
        return nil,errors.New(fmt.Sprintf("connect to etcd failed, err:%v\n", err))
    }
   
    return cli,nil
}

//通过key获取value
//控制台命令:./etcdctl --endpoints=localhost:2379 get "/app"
func GetEtcdData(key string) ([]byte,error) {
	if  key == "" {
		return nil,errors.New("key不能为空")
	}
	//连接etcd
    cli,err := ConnectEtcd();
    if err != nil {
        return nil,err
    }
    defer cli.Close()
    ctx := context.TODO()
    kv := clientv3.NewKV(cli)//用newKv的方式获取键值对
    resp, err := kv.Get(ctx, key)
    
    if err != nil {
        return nil,errors.New(fmt.Sprintf("get from etcd failed, err:%v\n", err))
    }
    // fmt.Println(resp.Kvs) //[key:"foo" create_revision:2 mod_revision:3 version:2 value:"bar" ]
    // fmt.Println(len(resp.Kvs))
    if len(resp.Kvs) == 0 {
        return nil,errors.New("key未设置value")
    }
    // data["key"] = string(resp.Kvs[0].Key)
    // data["value"] = string(resp.Kvs[0].Value)
    // common.ReturnSuccess(w,conf.SUCCESS_CODE,"获取成功",data)
    return resp.Kvs[0].Value,nil
}


//通过前缀获取相关的key
//控制台命令:
// ./etcdctl --endpoints=localhost:2379 get "/app"  --prefix
func GetEtcdDataWithPrefix(prefix string) ([]*map[string]interface{},error){

	//连接etcd
    cli,err := ConnectEtcd();
    if err != nil {
        return nil,err
    }
    defer cli.Close()
    ctx := context.TODO()
    kv := clientv3.NewKV(cli)//用newKv的方式获取键值对
    //通过前缀获取key
    resp, err := kv.Get(ctx, prefix,clientv3.WithPrefix())
    
    if err != nil {
        return nil,errors.New(fmt.Sprintf("get from etcd failed, err:%v\n", err))
    }

    data := make([]*map[string]interface{},len(resp.Kvs))
    for k,v := range resp.Kvs {
        temp := make(map[string]interface{})
        temp["key"] = string(v.Key)
        temp["value"] = string(v.Value)
        data[k] = &temp
        // data = append(data,&temp)
    }
    return data,nil
}

//设置key
//控制台命令:./etcdctl put k1 v1
func SetEtcdData(key string, value string) error {
   
    if key == "" || value == "" {
        return errors.New("缺少key或value!!!")
    }
    //连接etcd
    cli,err := ConnectEtcd();
    if err != nil {
        return err
    }
    defer cli.Close()
    // put
    ctx := context.TODO()
    _, err = cli.Put(ctx, key, value)
    if err != nil {
        return errors.New(fmt.Sprintf("put to etcd failed, err:%v\n", err))
    }
    return nil
}

//删除key 
//控制台命令:./etcdctl del k1
func DelEtcdData(key string) error {

    if key == "" {
        return errors.New("key不能为空!!!")
    }
   //连接etcd
    cli,err := ConnectEtcd();
    if err != nil {
        return err
    }
    defer cli.Close()
   
    if _, err := cli.Delete(context.Background(), key); err != nil {
        return errors.New(fmt.Sprintf("delete failed, err:%v\n", err))
    }
    return nil
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127

etcd模块下的etcd_edit.go直接调用edit.go的方法进行增删改查

package etcd

import (
	"net/http"
	"fmt"
    //内部包
	common "etcd_web/common"
	conf "etcd_web/config"
    storage "etcd_web/storage"
)


//通过key获取value
func GetEtcdData(w http.ResponseWriter, r *http.Request) {
	
	key := r.FormValue("key")
	if  key == "" {
		common.ReturnError(w,conf.FAIL_CODE,fmt.Sprintf("key不能为空"))
		return
	}
    //根据key获取value
	value,err := storage.GetEtcdData(key)
    if err != nil {
        //Error()方法返回错误类型的字符串
        common.ReturnError(w,conf.FAIL_CODE,err.Error())
        return
    }
    data := make(map[string]interface{})
    data["key"] = key
    data["value"] = string(value)
    
    common.ReturnSuccess(w,conf.SUCCESS_CODE,"获取成功",data)
}


//通过前缀获取相关的key
func GetEtcdDataWithPrefix(w http.ResponseWriter, r *http.Request) {
	prefix := r.FormValue("prefix")
	data,err := storage.GetEtcdDataWithPrefix(prefix)
    if err != nil {
        common.ReturnError(w,conf.FAIL_CODE,err.Error())
        return
    }
    common.ReturnSuccess(w,conf.SUCCESS_CODE,"获取成功",data)
}

//设置key
//控制台命令:./etcdctl put k1 v1
func SetEtcdData(w http.ResponseWriter, r *http.Request) {
    key := r.FormValue("key")
    value := r.FormValue("value")
    if key == "" || value == "" {
        common.ReturnError(w,conf.FAIL_CODE,"缺少key或value")
        return
    }

    err := storage.SetEtcdData(key,value);
    if err != nil {
        common.ReturnError(w,conf.FAIL_CODE,err.Error())
        return
    }
    common.ReturnSuccess(w,conf.SUCCESS_CODE,"设置成功",nil)
}

//删除key 
//控制台命令:./etcdctl del k1
func DelEtcdData(w http.ResponseWriter, r *http.Request) {
    key := r.FormValue("key")
    if key == "" {
        common.ReturnError(w,conf.FAIL_CODE,"key不能为空")
        return
    }

    err := storage.DelEtcdData(key)
    if err != nil {
        common.ReturnError(w,conf.FAIL_CODE,err.Error())
        return
    }
    common.ReturnSuccess(w,conf.SUCCESS_CODE,"删除成功",nil)
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/607530
推荐阅读
相关标签
  

闽ICP备14008679号