
巧妙解决命令行字符串参数到自定义结构体的转换难题
本文提供一种基于Go语言map的高效方案,解决将命令行参数(字符串类型)转换为自定义结构体类型的问题。 假设程序接收-m参数,其值(例如“h1”)代表需要获取特定poc结构体信息,而getpocinfo函数需要poc类型参数。 直接转换字符串到结构体不可行,因此需要建立字符串标识符与poc结构体实例的映射。
我们使用map[string]Poc来存储字符串标识符和对应poc结构体实例。 以下代码演示了该方法:
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
}
func main() {
var module string
flag.StringVar(&module, "m", "H1", "module: all")
flag.Parse()
pocMap := map[string]Poc{
"H1": {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"}},
// ... 添加更多Poc结构体实例
}
poc, ok := pocMap[module]
if !ok {
fmt.Println("无效的模块名称")
return
}
method, path, header, body := getpocinfo(poc)
fmt.Println(method + ":" + path + ":" + header + ":" + body)
}
func getpocinfo(id Poc) (method, path, header, body string) {
method = id.method
path = id.path
header = id.headers.UserAgent
body = id.body
return
}此方案通过pocMap快速查找对应的poc结构体,避免了不安全的直接类型转换。 如果module值不在pocMap中,程序会输出错误信息,保证了程序的健壮性。 这种方法比直接字符串转换更可靠、更清晰。
以上就是如何高效地将命令行字符串参数转换为自定义结构体?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号