go语言 最近遇到的问题总结

本文总结了使用`github.com/dlintw/goconf`和`github.com/larspensjo/config`库在Go语言中读取配置文件的方法,包括单独读取二级标题配置和兼容一级标题配置的技巧。还探讨了利用os包进行文件操作,特别是写文件,以及strconv进行类型强转,如int32与string的互转。此外,讨论了interface{}的使用和如何获取机器物理参数,以及如何在Go中执行shell命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用”github.com/dlintw/goconf” 与”github.com/larspensjo/config”读配置文件

首先应该下载包

go get "github.com/dlintw/goconf" --读取二级标题数据
go get "github.com/larspensjo/config" --读取一级标题数据,可兼容上个包

包会下载到 **$GOPATH/src** 路径下,否则默认下载到 **$GOROOT/src**下

导入包

    import (
        ""github.com/dlintw/goconf""
        "其他包"
        )

单独读取二级标题配置文件:

//此函数默认将配置文件当做字符串读取,类型转换需要在函数外部自己实现
func read_conf_log_file(name string, name1 string) (interface{}, error){
    c, err := goconf.ReadConfigFile("monitor.conf")
    checkErr(err)

    return c.GetString(name, name1)
}
    //调用函数 传入参数应为配置文件的一级标题和二级标题名
    log_size_warn, err := read_conf_log_file("log_file_size_warn", "size")

配置文件如下:

[mem]
mem_warn=10

[cpu]
cpu_warn=30

[disk]
disk_warn=10

[speed]
speed_warn=10
net_card=eth0

[log_file_size_warn]
size=10

[log]
log_path=/path/to/gotest/src/test_main/iwatch/1.conf
log_path2=/path/to/gotest/src/test_main/iwatch/2.conf
log_path3=/path/to/gotest/src/test_main/iwatch/3.conf
...

读取一级标题配置文件 (兼容上个包) –可用于同时读取多个未知的二级标题数据

/*
    该函数可一次直接读取一级标题下的二级标题
    再通过range方法迭代获得二级标题对应的每一个数据
    最后将以map[key1,:value1, key2:value2...]类型返回给外部
    key:二级标题 value:二级标题对应的数据
*/
func read_conf_log_file_map() (map[string]string, error){
    cfg, err := config.ReadDefault("/path/to/gotest/src/test_main/iwatch/monitor.conf")
    if err != nil {
        //log.Fatalf("Fail to find", *configFile, err)
        fmt.Println("Fail to find")
    }
    //set config file std End
    var log_file_map = make(map[string]string)
    //Initialized topic from the configuration
    if cfg.HasSection("log") {
        //section 为二级标题字符串数组
        section, err := cfg.SectionOptions("log")
        if err == nil {
            for _, v := range section {
                options, err := cfg.String("log", v)
                if err == nil {
                    log_file_map[v] = options
                }
            }
        }
    }
//返回的map为map[string]string类型的
    return log_file_map, err
}

//调用函数
log_file_map, err := read_conf_log_file_map()
for k, log_path := range log_file_map{
    ...
    //k,log_path 即为对应的二级标题及其数据
    //如:log_path  /path/to/gotest/src/test_main/iwatch/1.conf
    //   log_path2  /path/to/gotest/src/test_main/iwatch/2.conf
    //   log_path3  /path/to/gotest/src/test_main/iwatch/3.conf
    }

利用os包写文件

//主要给文件尾部追加数据
func write_conf() {
    file, err := os.OpenFile("monite_writer.conf", os.O_WRONLY, 0644)
    if err != nil {
        file, err = os.Create("monite_writer.conf")
    }
    checkErr(err)
    defer file.Close()
    //n, _ := file.Seek(0, os.SEEK_SET)
    //fi, _ := file.Stat()  //  获取文件信息
    //fi.Size

    n, _ := file.Seek(0, os.SEEK_END)
    //0:代表偏移量,负数代表向前偏移
    //SEEK_SET,SEEK_CUR和SEEK_END值 依次 为 0, 1和 2
    //代表文件头,当前位置,文件尾部
    file.WriteAt([]byte("hello golang test\n"), n)
    //指定偏移量来写文件,这里为文件尾部
}

os还有对流的操作,如writer和reader。需要看一看

使用strconv进行类型的强转

int32与string互转

var ai int32 = strconv.Atoi("123")   --string类型转int32
var astr string = strconv.Itoa(123)  --int32类型转string

更多用法见下:
##浮点数与字符串互转
##将“带引号的字符串” s 转换为常规的字符串(不带引号和转义字符)

strconv包 用法

空interface(即interface{})与强转换

强类型转换:一定要用括号扩住需转换的数据
var a int = 10
var b int64 = int64(a)

    //利用interface{}j接收各种不同类型数据
    //返回不同类型的数据
        func test(data interface{})  interface{}{
            switch data.(type)
                case int:...
                case string:...
                case float:...

            return data
        }
    //调用函数
    //string
    var data1 interface{} = test("123")
    var data_str string = data1.(string)

    //int32
    var data2 interface{} = test(123)
    var data_int int = data2.(int)

    //float32
    var data3 interface{} = test(1.0)
    var data_float = data3.(float)

获取机器物理参数

下载包

go get "github.com/shirou/gopsutil"

导入包

import (
        "github.com/shirou/gopsutil/cpu"
        "github.com/shirou/gopsutil/disk"
        _"github.com/shirou/gopsutil/host"
        "github.com/shirou/gopsutil/mem"
        "github.com/shirou/gopsutil/net"
)
获取依赖包: golang.org/x (谷歌被墙,go get 无法直接下载)
git clone https://github.com/golang/net.git $GOPATH/src/github.com/golang/net
git clone https://github.com/golang/sys.git $GOPATH/src/github.com/golang/sys
git clone https://github.com/golang/tools.git $GOPATH/src/github.com/golang/tools
ln -s $GOPATH/src/github.com/golang $GOPATH/src/golang.org/x


func mem_usage() {
    v, _ := mem.VirtualMemory()
    percent.mem_percent = v.UsedPercent

    //mem_percent = (float64)((v.Used)/(v.Total))
}

func cpu_usage() {
    cc, _ := cpu.Percent(time.Second, false)
    percent.cpu_percent = cc[0]
}

func disk_usage() {
    d, _ := disk.Usage("/")
    percent.disk_percent = d.UsedPercent
}

func find_net_card(nv []net.IOCountersStat) (int, error){
    //net_card := "eth0" 
    for k, v := range nv{
        //eth0 由配置文件读取
        if v.Name == config_warn.net_card {
            //ki, err :=strconv.Atoi(k)
            //checkErr(err)
            return k, nil
        }

    }
    return -1, errors.New(fmt.Sprintf("could not find \"%v\"\n", config_warn.net_card))
}


func speed_usage() {
    nv_start, _ := net.IOCounters(true)

    num, err := find_net_card(nv_start)
    checkErr(err)

    start_receive_bytes := nv_start[num].BytesRecv
    start_send_bytes := nv_start[num].BytesSent

    time.Sleep(10 *time.Second)

    nv_end, _ := net.IOCounters(true)
    end_receive_bytes := nv_end[num].BytesRecv
    end_send_bytes := nv_end[num].BytesSent

    percent.speed_receive_percent = (float64)(end_receive_bytes - start_receive_bytes)/10/1024
    percent.speed_send_percent = (float64)(end_send_bytes - start_send_bytes)/10/1024

    //fmt.Println(start_receive_bytes, start_send_bytes)
    //fmt.Println(nv_start[0], nv_start[1], nv_start[2])
}

func get_time() string{
    var timestamp int64 = time.Now().Unix()
    var s string = time.Unix(timestamp, 0).Format("Mon Jan 15:04:05 2006-01-02")
    return s
}

func get_phy_info() {
    get_time()
    mem_usage()
    cpu_usage()
    disk_usage()
    speed_usage()
}

//主要获取了上下行速率,cpu使用率,内存使用率,磁盘使用率

go执行shell命令

//通过传入想执行的命令即可
//返回执行的结果
func exec_shell(s string) (string, error){
    cmd := exec.Command("/bin/bash", "-c", s)

    //将io.Writer类型转化为string类型,通过buffer将[]byte与string互转
    var out bytes.Buffer
    cmd.Stdout = &out

    err := cmd.Run()
    checkErr(err)
    fmt.Printf("%v", out.String())

    return out.String(), err
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值