string - 处理字符串问题

标签 string go

我在使用 Golang 中的字符串时遇到了一些问题。似乎他们没有被移交给另一个功能。

func Sendtext(ip string, port string, text string) (err int) {
targ := ip + ":" + port
raddr,e := net.ResolveTCPAddr("tcp",targ)
if e != nil {
    os.Stdout.WriteString(e.String()+"\n")
    return 1
}
conn,e := net.DialTCP("tcp",nil,raddr)
if e != nil {
    os.Stdout.WriteString(e.String()+"\n")
    return 1
}
conn.Write([]byte(text))
mess := make([]byte,1024)
conn.Read(mess)
message := string(mess)
conn.Close()
if message[0] == 'a' {
    return 0
} else {
    return 1
}
return 0
}

func main() {
os.Stdout.WriteString("Will send URL: ")
url := GetURL()
os.Stdout.WriteString(url + "\n\n")
_, port, pass, ip := browserbridge_config.ReadPropertiesFile()
os.Stdout.WriteString("sending this url to " + ip + ":" + port + "\n")
message := url + "\n" + pass + "\n"
os.Stdout.WriteString("\nsending... ")
e := Sendtext(ip, port, message)
if e != 0 {
    os.Stdout.WriteString("ERROR\n")
    os.Exit(e);
}
os.Stdout.WriteString("DONE\n")
}

和我的配置阅读器:

func ReadConfigFile(filename string) (browsercommand string, port string, pass string, ip string) {

// set defaults
browsercommand = "%u"
port = "7896"
pass = "hallo"
ip = "127.0.0.1"

// open file
file, err := os.Open(filename)
if err != nil {
    os.Stdout.WriteString("Error opening config file. proceeding with standard config...")
    return
}


// Get reader and buffer
reader := bufio.NewReader(file)

for {
    part,_,err := reader.ReadLine()
    if err != nil {
        break
    }
    buffer := bytes.NewBuffer(make([]byte,2048))
    buffer.Write(part)
    s := strings.ToLower(buffer.String())

    if strings.Contains(s,"browsercommand=") {
        browsercommand = strings.Replace(s,"browsercommand=","",1)
    } else {
        if strings.Contains(s,"port=") {
            port = strings.Replace(s,"port=","",1)
        } else {
            if strings.Contains(s,"password=") {
                pass = strings.Replace(s,"password=","",1)
            } else {
                if strings.Contains(s,"ip=") {
                    ip = strings.Replace(s,"ip=","",1)
                }
            }
        }
    }
}

return
}

这个程序的输出:

Will send URL: test.de

sending this url to 192.168.2.100:7896

sending... 
dial tcp 192.168.2.1:0: connection refused
ERROR

(192.168.2.1是网关)

我尝试在 Sendtext 的顶部使用 os.Stdout.WriteString(targ) 或 os.Stdout.WriteString(ip),但没有得到任何输出。

关于它的令人困惑的事情:昨天它工作 xD (在我将 ReadConfig 迁移到它自己的 .go 文件之前)

我希望你能帮我解决这个...

赛拉


更新:

正如PeterSO所说,问题不在于字符串的交接 我的第一个猜测,它一定是 String 到 TCPAddr 的转换,是正确的,但它似乎是字符串的问题,而不是 net 库的问题。 我刚刚添加 ip = "192.168.2.100" 港口=“7896” 在调用 Sendtext 之后,这有助于...(至少在用户需要设置自定义 ip/端口之前...)

我知道问题首先发生在我决定从 goconf (http://code.google.com/p/goconf/) 切换到我自己的时候。这就是为什么我认为问题出在 ReadProperties() 函数中。

我还意识到 strconv.Atoi(port) 返回 0(解析“7896”:无效参数) 当我使用已实现(不可更改)配置的服务器和客户端,然后让客户端从配置文件中读取密码时,密码比较失败。当我也在代码中设置密码时(不读取文件),它起作用了。

我真的不知道现在该怎么办...有什么想法吗?

最佳答案

Go字节包:func NewBuffer(buf []byte) *Buffer

NewBuffer creates and initializes a new Buffer using buf as its initial contents. It is intended to prepare a Buffer to read existing data. It can also be used to size the internal buffer for writing. To do that, buf should have the desired capacity but a length of zero.

In most cases, new(Buffer) (or just declaring a Buffer variable) is preferable to NewBuffer. In particular, passing a non-empty buf to NewBuffer and then writing to the Buffer will overwrite buf, not append to it.

在您的 ReadConfigFile 函数中,您编写:

buffer := bytes.NewBuffer(make([]byte,2048))
buffer.Write(part)

make([]byte,2048) 函数调用为 buffer 创建一个长度和容量为 2048 字节的初始 slice 。 buffer.Write(part) 函数调用通过覆盖 buffer 写入 part。至少,您应该编写 make([]byte,0,2048) 来初始为 buffer slice 提供零长度和 2048 字节的容量。

您的 ReadConfigFile 函数还有其他缺陷。例如,key=value 格式非常严格,只能识别硬编码到函数中的键,如果没有给出配置文件,它不会返回默认值,配置文件不会关闭等。这是一个基本实现配置文件阅读器。

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

type Config map[string]string

func ReadConfig(filename string) (Config, os.Error) {
    config := Config{
        "browsercommand": "%u",
        "port":           "7896",
        "password":       "hallo",
        "ip":             "127.0.0.1",
    }
    if len(filename) == 0 {
        return config, nil
    }
    file, err := os.Open(filename)
    if err != nil {
        return nil, err
    }
    defer file.Close()
    rdr := bufio.NewReader(file)
    for {
        line, err := rdr.ReadString('\n')
        if eq := strings.Index(line, "="); eq >= 0 {
            if key := strings.TrimSpace(line[:eq]); len(key) > 0 {
                value := ""
                if len(line) > eq {
                    value = strings.TrimSpace(line[eq+1:])
                }
                config[key] = value
            }
        }
        if err == os.EOF {
            break
        }
        if err != nil {
            return nil, err
        }
    }
    return config, nil
}

func main() {
    config, err := ReadConfig(`netconfig.txt`)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("config:", config)
    ip := config["ip"]
    pass := config["password"]
    port := config["port"]
    fmt.Println("values:", ip, port, pass)
}

输入:

[a section]
key=value
; a comment
port = 80
  password  =  hello  
 ip= 217.110.104.156
# another comment
 url =test.de
file =

输出:

config: map[browsercommand:%u key:value port:80 ip:217.110.104.156 url:test.de
file: password:hello]
values: 217.110.104.156 80 hello

关于string - 处理字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7249576/

相关文章:

go - go语言有没有开源的词法分析器(解析器)?

java - 当我按 # 拆分字符串的 ArrayList 时,最后一个字段不正确

python - 从字符串中过滤字符

php - 从 HTTP_REFERER 中提取方案和主机

c++ - 将 C++ 字符串转换为 int

ios - 忽略以小写字母开头的 swift 字母

go - 将映射序列化到 gob 后 DeepEqual 不正确

Golang将nil作为可选参数传递给函数?

go - 无法在 Fedora 31 中安装 gopls

go - 在 golang 中使用 os/exec 在特定目录中执行命令