本文探讨如何将go语言程序的命令行参数(字符串类型)转换为自定义结构体类型。 问题在于,程序需要根据用户输入的-m参数值获取对应的结构体内容。例如,用户输入-m h1,程序需将字符串"h1"转换为预定义的poc结构体h1。
已知程序定义了poc结构体和h1变量:
package main
import (
"flag"
"fmt"
)
type poc struct {
method string
headers headers
path string
body string
expression int
}
type headers struct {
useragent string
accept string
xforwardedfor string
contenttype string
referer string
acceptlanguage string
cookie string
}
var h1 = poc{
method: "get",
path: "/resin-doc/viewfile/?file=index.jsp",
body: "",
expression: 200,
headers: headers{
useragent: "mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/63.0.3239.132 safari/537.36",
accept: "",
xforwardedfor: "",
contenttype: "",
referer: "",
acceptlanguage: "",
cookie: "",
},
}getpocinfo函数接收poc类型参数,但main函数接收的module变量是字符串类型,直接传递会导致类型不匹配。
解决方法是使用map存储不同名称的poc结构体。根据用户输入的字符串(例如"h1")作为键,从map中获取对应的poc结构体。
改进后的代码:
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"flag"
"fmt"
)
// ... (Poc and headers struct definitions remain the same) ...
func main() {
var module string
flag.StringVar(&module, "m", "H1", "module: all")
flag.Parse()
pocMap := map[string]poc{
"H1": h1,
// Add other Poc structs here as needed
}
poc, ok := pocMap[module]
if !ok {
fmt.Println("Invalid module name")
return
}
method, path, header, body := getpocinfo(poc)
fmt.Printf("%s:%s:%s:%s\n", method, path, header, body)
}
func getpocinfo(id poc) (method string, path string, header string, body string) {
method = id.method
path = id.path
header = id.headers.useragent //Corrected to access useragent
body = id.body
return
}通过map[string]poc,程序可灵活处理多个poc结构体,并根据用户输入选择对应的结构体,避免了类型转换问题。 注意,代码中getpocinfo函数的header返回值已修正为正确访问useragent字段的方式。 此外,Printf用于更清晰的输出格式。

以上就是Go语言命令行参数字符串如何转换为自定义结构体?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号