【go标准库系列】go语言标准库reflect反射学习

源码

package main

import (
"flag"
"fmt"
"net/http"
"reflect"
)
type GoService struct {

}
func (G *GoService) HttpServer(port string){
http.HandleFunc("/", func(responseWriter http.ResponseWriter, request *http.Request) {
responseWriter.Write([]byte("hello word"))
})
http.ListenAndServe(":"+port,nil)
}
func main(){
cmd:=flag.String("cmd","","cmd is a string indecated what server")
arg:=flag.String("args","","p is a string ,parameter for service")
flag.Parse()
if len(*cmd)==0 {
flag.Usage()
return
}
in :=make([]reflect.Value,0)
if len(*arg)!=0 {
in=append(in,reflect.ValueOf(*arg))
}
//指定类
service:=&GoService{}
f:=reflect.ValueOf(service).MethodByName(*cmd)
if !f.IsValid() {
return
}
f.Call(in)
//u:=User{1,"golang",12}
//Info(u)
}

编译

go build -o bin/runt.exe main.go

执行

cd bin
runt.exe -cmd=HttpServer -args=8091