import"time"; funcmain(){ var n=time.Now(); fmt.Print(n); return; };
Month/Weekday
1 2 3 4 5 6 7 8 9 10
var date=time.Date(2007,time.June,14,0,0,0,0,time.Local); var weekday=date.Weekday(); var wdStr string; switch weekday{ case time.Sunday: wdStr="星期天"; //... default: //... };
var str string="春江水暖鸭先知"; for i,x:=range str{ fmt.Printf("%2d-->%c\n",i,x); };
var m=map[rune]string{'a':"at",'b':"bee",'c':'cut'} for key,value:=range m{ fmt.Printf("[%c]:%s\n",key,value); };
var ch=make(chanint); gofunc(){ deferclose(ch); ch<-1; ch<-2; ch<-3; ch<-4; ch<-5; ch<-6; }(); for v:=range ch{ fmt.Printf("%d\n",v); };
continue/break
略。
goto
略。
加密解密
Base64
字符串形式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package main; import( "fmt"; "encoding/base64" ); funcmain(){ var testData="This is my DATA!!!"; var encodeStr=base64.StdEncoding.EncodeToString([]byte(testData)); fmt.Printf("%s\n",encodeStr); var decodeData,err=base64.StdEncoding.DecodeString(encodeStr); if(err!=nil){ fmt.Println("Eroor!\n",err); return; }; fmt.Printf("%s\n",string(decodeData)); return; };
换表:
1 2 3 4 5 6 7 8
var encodeStr="...";//表 必须64字节 不能出现\n \r custEncoding:=base64.NewEncoding(encodeStr); testData:="...";//要被加密的信息 var ecStr=custEncoding.EncodeToString([]byte(testData)); fmt.Printf("%s\n",ecStr);
var decodeData,_=custEncoding.DecodeString(ecStr); fmt.Printf("%s\n",decodeData);
字节形式:
1 2 3 4 5 6 7 8 9 10
var data=[]byte("..."); n:=base64.StdEncoding.EncodedLen(len(data));//编码后字节数 encodeData:=make([]byte,n); base64.StdEncoding.Encode(encodeData,data); fmt.Printf("%#x\n",encodeData);
file,err:=os.Create("encode.bin"); if err!=nil{ fmt.Println(err); return; }; var b64Writer=base64.NewEncoder(base64.StdEncoding,file); b64Writer.Write([]byte("...")); b64Writer.Write([]byte("...")); b64Writer.Write([]byte("...")); //... b64Writer.Close(); file.Close();
file,err=os.Open("encode.bin"); if err!=nil{ fmt.Println(err); return; }; var decoder=base64.NewDecoder(base64.StdEncoding.file); io.Copy(os.Stdout,decoder); file.Close();
import"cyrpto/hamc"; var Key[]byte=make([]byte,64); funcinit(){ rand.Seed(time.Now().Unix()); rand.Read(Key);//随机密钥 }; funcComputeHMAC(msg string)[]byte{ var buf=[]byte(msg); mHmac:=hmac.New(sha256.New,Key); mHmac.Write(buf); return mHmac.Sum(nil); }; var msg01 string; fmt.Scanln(&msg01); var hash01=ComputeHMAC(msg01); var msg02 string; fmt.Scanln(&msg02); var hash02=ComputeHMAC(msg02); res:=hmac.Equal(hash01,hash02); if(res){ //两条消息一致 }else{ //不一致 };
RSA
PKCS#1 v1.5标准:
1 2 3 4 5 6
import"crypto/rsa"; var prvKey,_=rsa.GenerateKey(rand.Reader,512); var pubKey=&prvkey.PublicKey; var msg="...";\ var cipherText,_=rsa.EncryptPKCS1v15(rand.Reader,pubkey,[]byte(msg)); var decText,_=rsa.DecryptPKCS1v15(rand.Reader,prvKey,cipherText);
OAEP标准:
1 2 3 4 5 6
import"crypto/rsa"; var prvKey,_=rsa.GenerateKey(rand.Reader,1024); var pubKey=&prvKey.PublicKey; var msg="..."; var cipherText,_=rsa.EncryptOAEP(sha256.New(),rand.Reader,pubKey,[]byte(msg),nil); var decText,_=rsa.DecryptOAEP(sha256.New(),rand.Reader,prvKey,cipherText,nil);
import"crypto/x509"; var prvkey,_=rsa.GenerateKey(rand.Reader,512); var pubkey=&prvkey.PublicKey; keydata:=x509.MarshalPKCS1PrivateKey(prvkey); ioutil.WriteFile("myPrvkey",keydata,0600);//写入文件 var testmsg="测试消息"; var cipherdata,_=rsa.EncryptPKCS1v15(rand.Reader,pubkey,[]byte(testmsg)); indata,err:=ioutil.ReadFile("myPrvkey"); if(err!=nil){ fmt.Println(err); return; }; loadKey,err:=x509.ParsePKCS1PrivateKey(indata); if(err!=nil){ fmt.Println(err); return; }; decrdata,err:=rsa.DecryptPKCS1v15(rand.Reader,loadKey,cipherdata); if(err!=nil){ fmt.Println(err); return; }; fmt.Printf("%s\n",decrdata);
PEM编码
编码与解码:
1 2 3 4 5 6 7
var content="..."; var block pem.Block; block.Type="DEMO"; block.Bytes=[]byte(content); var encodeData=pem.EncodeToMemory(&block); var decblock,_=pem.Decode(encodeData); fmt.Printf("%s\n%s\n",decblock.Type,decblock.Bytes);//消息类型、消息正文
解码后保留数据:
1 2 3 4 5 6 7
var pemData=` -----BEGIN MY NAME------ 546L5aSn5bGx -----END MY NAME------ Hello, Jim` var msgblock,other=pem.Decode([]byte(pemData)); fmt.Printf("%s\n%s\n%s\n",msgblock.Type,msgblock.Bytes,other);
消息头:
1 2 3 4 5 6 7 8 9 10 11 12
var msg="..."; var headers=map[string]string{ "ver":"1.0", "sender":"Jack", "copyto":"Tom", }; block:=pem.Block{ Type:"EMSG", Bytes:[]byte(msg), Headers:headers, }; pem.Encode(os.Stdout,&block);
接口与结构体
结构体
1 2 3 4 5 6 7 8 9 10 11 12 13 14
type person struct{ name string;//首字母为小写的只能在当前包中访问 age uint8; weight,height float32; gender uint8; }; var g=person{ name:"...", //... }; var pc *person=&person{ "...", //... };
结构体方法:在结构体外部定义
1 2 3 4 5 6 7
type test struct{ //... }; func(o test)doSomething()string{ test.data=1; return"dosomething"; };
type base struct{ code uint; line uint64; label string; }; type dev struct{ base; size float32; publisher string; }; var x dev //一种正确的写法 x.base.code=1001; x.base.line=1; x.base.label="F7"; //另一种正确的写法 x.code=1001; x.line=1; x.label="F7"; var y=dev{ base:base{1002,1,"D6"},//或:base{1002,1,"D6"}, size:0.12, publisher:"Dick" };
类型断言
1 2 3 4 5 6 7
var x interface{}=float64(0.00123); y,ok:=x.(float64); if(ok){ fmt.Printf("%T\n",y);//float64 }else{ //断言失败 };
数组与切片
数组
1 2 3 4 5
var f=[5]uint32{18};//第一个值18,后面的默认0 s:=[3]interface{}{"abc",887,'H'}; r:=[...]int32{800,500,1600,2400,900,700};//自动计算长度为6 n:=len(r); var b=[5][4][3]int32;
切片
1 2
s:=x[2:4];//[2,4) s3:=a[:];//全部
追加
1 2
var sf=[]float32{0.001,0.0007}; sf=append(sf,0.0008,0.1205);//添加2个元素
映射与链表
映射的初始化
1 2 3 4 5 6 7 8 9 10
//只有以下方法初始化才能继续添加元素 //法一 var m1=make(map[uint16]string); //法二 var m2=map[rune]float64{}; //法三 var m3=map[string]uint64{ "item1":8150, //... };
映射的枚举
1 2 3 4 5 6 7
myMap:=map[string]int{ "task-01":1000, //... }; for key,val:=range myMap{ fmt.Printf("%s\n%d\n",key,val); };
映射的存在性检验
1 2 3 4 5 6 7 8
var m=map[string]int{}; xv:=m["c3"];//该值如果不存在,返回默认值0 xv,ok:=m["c3"]; if ok{ //存在 }else{ //不存在 };
var strs=[]string{"xxx","xxx",...}; var out=strings.Join(strs,"#");//用#将strs连接起来
Replace
1 2
var a="xxx"; var b=strings.Replace(a,"a","b",2);//将字符串a中字符a替换为b,最多替换2次,0次可省略表示不限次数
Split
1 2 3 4
var res=strings.Split(s,"#");//以#为分隔符切分字符串s,数组保存到res var res=strings.SplitN(s,"#",2);//同上,只切分为2份 var res=strings.SplitAfter(s,"#");//在#后分割(保留分隔符) var res=strings.SplitAfterN(s,"#",2);//同上,只切分为2份
var str2=strings.TrimPrefix(str,"ftp://");//去除前缀 var str2=strings.TrimSuffix(str,".xct");//去除后缀 var str2=strings.TrimSpace(str);//去除首尾空格 var str2=strings.Trim(s,"abcd");//当字符串s首尾出现abcd之一任意则删除,直到首尾字符都不为abcd任一字符 var str2=strings.TrimLeft(s,"abcd");//同上,只首 var str2=strings.TrimRight(s,"abcd");//同上,只尾
var( num1="123456789"; num2="123456789"; ); var bigInt1=new(bit.Int); var bigInt2=new(bit.Int); bigInt1.SetString(num1,10); bigInt2.SetString(num2,10); var res1=new(big.Int); res1.Add(bigInt1,bigint2); var res2=new(bit.Int); res2.Sub(bigInt1,bigInt2); fmt.Printf("%d,%d\n",res1,res2);
阶乘
1 2
var c=new(big.Int); c.MulRange(1,30);//阶乘,求积范围为[1,30]
大浮点数
1 2 3 4 5 6 7 8 9 10 11
var strfloat="0.41646416489403"; var bigFloat=new(big.Float); bigFloat.SetPrec(50);//精度 bigFloat.SetString(strfloat); fmt.Printf("%.50f\n",bigFloat); bigRes=new(big.Float); bigRes.SetPrec(100); bigRes.Add(bigFa,bigFb); bigRes.Sub(bigFa,bigFb); bigRes.Mul(bigFa,bigFb); bigRes.Quo(bigFa,bigFb);
import"sort" var intNums=[]int{780,-5,20}; sort.Ints(intNums);//都是默认从小到大 fmt.Printf("%v\n",intNums); var floatNums=[]float64{0.01472,-2.881652,4.13}; sort.Float64s(floatNums); var strList=[]string{"zero","bus","six"}; sort.Strings(strList);
实现递减/自定义排序
1 2 3 4 5 6
var nums=[]int{17,81,3}; var decreaseFun=func(i,j int)bool{ return !(nums[i]<nums[j]); }; sort.Slice(nums,decreaseFun); fmt.Printf("%v\n",nums);