首页 > 后端开发 > Golang > 正文

Go语言命令行参数字符串如何转换为自定义结构体?

心靈之曲
发布: 2025-03-01 13:06:11
原创
1003人浏览过

Go语言命令行参数字符串到自定义结构体的转换

本文探讨如何将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结构体。

改进后的代码:

AI-Text-Classifier
AI-Text-Classifier

OpenAI官方出品,可以区分人工智能书写的文本和人类书写的文本

AI-Text-Classifier 59
查看详情 AI-Text-Classifier

立即学习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语言命令行参数字符串如何转换为自定义结构体?

以上就是Go语言命令行参数字符串如何转换为自定义结构体?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号