Golang Small Program Test (iii)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

1. Golang's Log module

Golang Log module can easily create its own logging, including log file path, log format, etc. can be defined by themselves. First look at a program:

Package Mainimport ("FMT" "Log" "OS") Func main () {logfile, err: = OS. OpenFile ("D:\\test.log", OS. O_rdwr|os. O_create, 0) if err! = Nil {fmt. Printf ("%s\r\n", err. Error ()) OS. Exit ( -1)}defer logfile. Close () Logger: = log. New (logfile, "\ r \ n", log.) Ldate|log. Ltime|log. Llongfile) Logger. Println ("Hello") logger. Println ("Oh ...") logger. Fatal ("Test") logger. Fatal ("Test2")}

First create a log file, and then use log. New () Creates a logger object and defines the format for the contents of the log file, as defined in new ():

Func New (out IO. Writer, prefix string, flag int) *logger
Ldate, ltime, etc. are defined as constants:
Const (    //Bits or ' Ed together to control what ' s printed. There is no control over the    //order they appear (the order listed here) or the format they present (as    //DESCRI Bed in the comments).  A Colon appears after these items:    //2009/01/23 01:23:23.123123/a/b/c/d.go:23:message    Ldate         = 1 << io Ta     //The DATE:2009/01/23    ltime                         //The time:01:23:23    lmicroseconds                 //microsecond Resolution: 01:23:23.123123.  assumes ltime.    Llongfile                     //full file name and line number:/a/b/c/d.go:23    lshortfile                    //Final file name element and line Number:d.go:23. Overrides Llongfile    lstdflags     = Ldate | Ltime//Initial values for the standard logger)

Log records are written to the log file by functions such as print (), Println (), and Printf (). The Fatal () function is then called to record the last log and exit (Fatal () contains the call OS. Exit (1)).

Logger gives the conclusion: A Logger can be used simultaneously from multiple goroutines; it guarantees-serialize access to the W Riter. This means that it is thread-safe.

2. Golang's Archive/zip module

This module is relatively simple, directly with a program description:

Package Mainimport ("FMT" "OS" "Log" "Archive/zip" "IO") const (LogFilePath = "D:\\zip.log") func main () {logfile,err: = os. OpenFile (Logfilepath,os. O_create|os. o_rdwr,0); if Err!=nil {fmt. Println (Err. Error ()); return;} Defer logfile. Close (); Logger: = log. New (logfile, "\ r \ n", log.) Ldate|log. Ltime|log. Llongfile); if Logger==nil {fmt. Println ("Logger init error");} R,err: = Zip. Openreader ("d:\\ new text document. zip"); if Err!=nil {logger. Fatal (err);} Defer R.close (); for _,f: = Range R.file {fmt. Println ("FileName:", F.name); Rc,err: = F.open (); if Err!=nil {logger. Fatal (err);} _,err = io. Copyn (OS. STDOUT,RC,68); Print the file contents if Err!=nil {if Err!=io. EOF {logger. Fatal (err);}}}

3. Panic and recover

The first article has been introduced, here is another example:

After the package Mainimport "FMT" Func Main () {T ()        //recover is executed, the FMT continues to execute. Println ("after recover.")} Func T () {defer func () {fmt. Println ("Defer func is run")                //recover can only execute in the defer () function r: = Recover () if r! = Nil {fmt. Println ("Recover:", R)}} () Fmt. The text in the Println ("body")        //panic is passed to the Recoverpanic ("Panic is run") fmt. Println ("Body 2")}

4. Golang's base64 plus decryption

Package Mainimport ("Encoding/base64" "FMT") const (base64table = " 123qrstuabcdvwxyzhijklawdcabdstefguvwxyzghijklmnopqr234560178912 ") var coder = base64. Newencoding (base64table) func base64encode (src []byte) []byte {return []byte] (coder. Encodetostring (SRC))}func base64decode (src []byte) ([]byte, error) {return coder. Decodestring (String (SRC))}func main () {//Encodehello: = "Hello World" debyte: = Base64Encode ([]byte (Hello))// Decodeenbyte, err: = Base64decode (debyte) if err! = Nil {fmt. Println (Err. Error ())}if Hello! = string (enbyte) {fmt. Println ("Hello is isn't equal to Enbyte")}fmt. Println (String (enbyte))}

5. Golang Time Package

Package Mainimport ("FMT" "Time") Func main () {//timestamp t: = times. Now (). Unix () fmt. PRINTLN (t)//timestamp to the specific display of the conversion FMT. Println (time. Unix (t, 0). String ())//timestamp with nanosecond t = time. Now (). Unixnano () fmt. Println (t) fmt. Println ("------------------")//Basic formatted time represents FMT. Println (time. Now (). String ()) fmt. Println (time. Now (). Format ("2006year 01month 02day")}
The output today is the day of the week:
Package main import ("FMT" "Time") Func main () {//timestamp t: = times. Now () Fmt. Println (T.weekday (). String ())}

6. Examples of Golang reflections

Package Mainimport ("FMT" "reflect") type mystruct struct {name String}func (this *mystruct) GetName () string {return THIS.N Ame}func Main () {FMT. Println ("--------------") var a mystructb: = new (MyStruct) fmt. Println (reflect. ValueOf (a)) fmt. Println (reflect. ValueOf (b)) fmt. Println ("--------------") A.name = "abc" b.name = "Def" val: = Reflect. ValueOf (a). Fieldbyname ("name") fmt. Println (val)//val2: = reflect. ValueOf (b). Fieldbyname ("name")//panic:reflect:call of reflect. Value.fieldbyname on PTR value//b is a pointer, valueof of the pointer returns the type of the pointer, it is not field, so you cannot use Fieldbynamefmt.println ("--------- -----") fmt. Println (reflect. ValueOf (a). Fieldbyname ("name"). Canset ()) fmt. Println (reflect. ValueOf (& (A.name)). Elem (). Canset ()) fmt. Println ("--------------") var c string = "xyz" P: = reflect. ValueOf (&c) fmt. Println (P.canset ())        //falsefmt. Println (P.elem (). Canset ())//truep. Elem (). SetString ("NewName") fmt. Println (c)}

Execution Result:

--------------<main. MyStruct Value><*main. MyStruct value>--------------ABC--------------falsetrue--------------falsetruenewname

The valueof () of A and B return a different value, because B is created with new () and is a pointer.

when the previous canset is a pointer (p) It is not addressable, but when it is p. Elem () (actually *p), it can be addressed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.