我有一段代码
main函数中,变量module是string类型的,值是命令行-m参数的值(这里比如输入的是"H1")
我想把这个string类型的module变量,传给getpocinfo函数,(获取最下面H1结构体的内容)
但是getpocinfo函数接受的是Poc类型,我要如何将用户命令行中输入的值转为Poc类型?
- - -
其实就是:
命令行 -m H1
然后我要得到 var H1 = Poc{...}的内容
谢谢大家
+ 完整代码
```golang
package main
import (
"fmt"
)
type Poc struct {
method string
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(){
//这里接收用户命令行中的-m参数
var module string
flag.StringVar(&module,"m","H1","module: all")
flag.Parse()
//把用户命令行中的-m的值传给getpocinfo函数
//但是getpocinfo函数接收的是Poc类型
a,b,c,d := getpocinfo(module)
fmt.Println(a+ ":" + b +":" +c+":"+d)
}
func getpocinfo(id Poc)(method string , path string , header string , body string){
method = id.method
path = id.path
header = id.headers.UserAgent
body = id.body
return method,path,header,body
}
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"}}
````
再次感谢,望知道的人解答一下
<a href="/user/jan-bar" title="@jan-bar">@jan-bar</a>
您好,谢谢您的解答,我先看看
再次感谢
#2
更多评论
【[我的博客](https://www.janbar.top/index.php/2019/11/07/99.html)】
我感觉你需要这个
```go
package main
import (
"encoding/json"
"flag"
"fmt"
"strings"
)
func main() {
var m MyType
flag.Var(&m, "m", "MyType")
var s1 SliceString
flag.Var(&s1, "s1", "s1 use [,]")
s2 := SliceString{Sep: "|"}
flag.Var(&s2, "s2", "s2 use [|]")
flag.Parse()
fmt.Printf("%#v\n", m.Get())
fmt.Printf("%#v\n", s1.Get())
fmt.Printf("%#v\n", s2.Get())
}
type MyType struct {
S string
A string `json:"a"`
B int `json:"b"`
C bool `json:"c"`
}
func (s *MyType) Get() MyType {
return *s
}
func (s *MyType) Set(set string) error {
s.S = set
return json.Unmarshal([]byte(s.S), s)
}
func (s *MyType) String() string {
return s.S
}
type SliceString struct {
S, Sep string
}
func (s *SliceString) Get() []string {
sep := ","
if s.Sep != "" {
sep = s.Sep
}
return strings.Split(s.S, sep)
}
func (s *SliceString) Set(set string) error {
s.S = set
return nil
}
func (s *SliceString) String() string {
return s.S
}
```
当执行:.app -m "{"A":"abc","B":123,"C":true}" -s1 "abc,123,def" -s2 "xyz|wer|cvb"
下面是运行结果:
main.MyType{A:"abc", B:123, C:true}
[]string{"abc", "123", "def"}
[]string{"xyz", "wer", "cvb"}
#1