Command line parameters
When writing code, running the program do some initialization operations, they often Acts parameters into the program through the command, it will use the command-line arguments
For example, specify the mode of operation and program levels:
go run HTTPServer.go --mode survival --level 1
os.Args
May be variable by Args package os Get all command line parameters , obtained is a string slice type ([] string), a first parameter is the command line execution file itself
package main import ( "fmt" "os" ) func main (){ fmt.Println(os.Args) } 运行结果: [C:\Users\chenkai\AppData\Local\Temp\___go_build_main_go__3_.exe]
flag package
Use flag packet parsing command line parameters there are two types of methods, below the record about usage
1) initialized variable assignment (recommended)
package main import ( "flag" "fmt" ) func main (){ var mode string var level int var onOff bool flag.StringVar(&mode,"mode", "survival", "game pattern") flag.IntVar(&level, "level", 1, "game level") flag.BoolVar(&onOff, "onOff", true, "game onOff") //解析命令行参数 flag.Parse() fmt.Printf("%v\t%v\t%v\t", mode, level, onOff) } 运行结果: survival 0 true
2) using the received pointer variable
package main import ( "flag" "fmt" ) func main (){ var mode *string = flag.String("mode", "survival", "game pattern") var level *int = flag.Int("level", 1, "game level") var onOff *bool = flag.Bool("onOff", true, "game onOff") //解析命令行参数 flag.Parse() fmt.Printf("%v\t%v\t%v\t\n", mode, level, onOff) fmt.Printf("%v\t%v\t%v\t", *mode, *level, *onOff) } 运行结果: 0xc00004e200 0xc0000620c0 0xc0000620c8 survival 0 true
json protocol
json data format is a cross-platform, of course, Go also supports json protocol, divided into json serialization and de-serialization
- Serialization: Go to convert the data type in the format string into json
- Deserialization: json string acting on the data type in the Go
1) the sequence of (json.Marshal)
Turn structure json:
package main import ( "encoding/json" "fmt" ) type User struct { UserName string NickName string Age int Sex string Email string } func main (){ var userA User = User{ UserName: "托尼", NickName: "tony", Age: 36, Sex: "男", Email: "[email protected]", } var jsonData []byte //func Marshal(v interface{}) ([]byte, error) jsonData, err := json.Marshal(userA) if err != nil { fmt.Printf("json marshal error[%v]", err) } fmt.Println (String (jsonData)) The result: } {"UserName":"托尼","NickName":"tony","Age":36,"Sex":"男","Email":"[email protected]"}
If you want to change the key json string, you can set up a structure json Tags:
package main import ( "encoding/json" "fmt" ) type User struct { UserName string `json:"username"` NickName string `json:"nickname"` Age int `json:"age"` Sex string `json:"sex"` Email string `json:"email"` } func main (){ var userA User = User{ UserName: "托尼", NickName: "tony", Age: 36, Sex: "男", Email: "[email protected]", } var jsonData []byte //func Marshal(v interface{}) ([]byte, error) jsonData, err := json.Marshal(userA) if err != nil { fmt.Printf("json marshal error[%v]", err) } fmt.Println(string(jsonData)) } 运行结果: {"username":"托尼","nickname":"tony","age":36,"sex":"男","email":"[email protected]"}
map turn json:
package main import ( "encoding/json" "fmt" ) func main (){ var mapA map[string]string = make(map[string]string) mapA["name"] = "johny" mapA["email"] = "[email protected]" var jsonData []byte jsonData, err := json.Marshal(mapA) if err != nil { fmt.Printf("json marshal error[%v]", err) } fmt.Println(string(jsonData)) } 运行结果: {"email":"[email protected]","name":"johny"}
2) deserialization (json.Unmarshal)
json structure back into a sequence: a first acquiring json data structure, and then assigned to another type of structure
package main import ( "encoding/json" "fmt" ) type User struct { UserName string `json:"username"` NickName string `json:"nickname"` Age int `json:"age"` Sex string `json:"sex"` Email string `json:"email"` } func marshalData() string { var userA User = User{ UserName: "托尼", NickName: "tony", Age: 36, Sex: "男", Email: "[email protected]", } var jsonData []byte //func Marshal(v interface{}) ([]byte, error) jsonData, err := json.Marshal(userA) if err != nil { fmt.Printf("json marshal error[%v]", err) } return string(jsonData) } FUNC main () { jsonData: = marshalData () var userB the User} = {the User fmt.Println (userB) // FUNC Unmarshal (Data [] byte, interface {V}) error ERR: = json.Unmarshal ([] byte (jsonData), & userB) ! IF ERR = nil { fmt.Printf ( "the unmarshal JSON error [% V]", ERR) } fmt.Println (userB) } The result: {0} // null character is a blank portion string, string type default is an empty string, int type default value is 0 {M [email protected]} Tony tony 36
Custom error
Custom error generally content with little, but also need to look at, is to achieve a Error () method, the type of error to be wrong type of interface to implement custom
Realized the error interface is the type of error, error interfaces are defined as follows:
type error interface { Error() string }
demo: When you open a file error, an error is returned to customize the content of
package main import ( "encoding/json" "fmt" "os" "time" ) type OpenError struct { path string operation string createTime time.Time message string } func (openErr *OpenError) Error() string { var jsonData []byte jsonData, err := json.Marshal(*openErr) if err != nil { fmt.Printf("json marshal error[%v]", err) } return string(jsonData) } func openFile(filepath string) error { var openErr = &OpenError{} file, err := os.Open(filepath) if err != nil { openErr.path = filepath openErr.operation ="read" openErr.createTime = time.Now() openErr.message = err.Error() return openErr } defer file.Close() return openErr } func main(){ //err := openFile("D:\\golang_workspace\\file_test\\source.txt") err := openFile("D:\\golang_workspace\\file_testsdafs") //fmt.Println(err.Error()) //fmt.Println(err) if err != nil { fmt.Println(err.Error()) } }
ending ~