工作,学习,生活,这里将会有一些记录. 备用域名:http://meisw.wdlinux.cn 注册 | 登陆
浏览模式: 标准 | 列表分类:golang

golang time 时间的加减法

 time包中的Add和Sub的用法,Add用于计算某个时间之前和之后的时间点,Sub用于计算两个时间差

package main


import (

"fmt"

"strings"

"time"

)


func main() {

// Add 时间相加

now := time.Now()

// ParseDuration parses a duration string.

// A duration string is a possibly signed sequence of decimal numbers,

// each with optional fraction and a unit suffix,

// such as "300ms", "-1.5h" or "2h45m".

//  Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

// 10分钟前

m, _ := time.ParseDuration("-1m")

m1 := now.Add(m)

fmt.Println(m1)


// 8个小时前

h, _ := time.ParseDuration("-1h")

h1 := now.Add(8 * h)

fmt.Println(h1)


// 一天前

d, _ := time.ParseDuration("-24h")

d1 := now.Add(d)

fmt.Println(d1)


printSplit(50)


// 10分钟后

mm, _ := time.ParseDuration("1m")

mm1 := now.Add(mm)

fmt.Println(mm1)


// 8小时后

hh, _ := time.ParseDuration("1h")

hh1 := now.Add(hh)

fmt.Println(hh1)


// 一天后

dd, _ := time.ParseDuration("24h")

dd1 := now.Add(dd)

fmt.Println(dd1)


printSplit(50)


// Sub 计算两个时间差

subM := now.Sub(m1)

fmt.Println(subM.Minutes(), "分钟")


sumH := now.Sub(h1)

fmt.Println(sumH.Hours(), "小时")


sumD := now.Sub(d1)

fmt.Printf("%v 天\n", sumD.Hours()/24)


}


func printSplit(count int) {

fmt.Println(strings.Repeat("#", count))

}

golang交叉编译工具,gox使用入门

 http://studygolang.com/articles/650

Golang给目录按时间排序.正则、时间条件搜索文件

 http://blog.csdn.net/fyxichen/article/details/50991805

golang时间函数处理

golang时间处理
相关包 "time"

  • 时间戳 
    当前时间戳

    fmt.Println(time.Now().Unix()) # 1389058332

     

  • str格式化时间
    当前格式化时间

    fmt.Println(time.Now().Format("2006-01-02 15:04:05")) # 这是个奇葩,必须是这个时间点, 据说是go诞生之日, 记忆方法:6-1-2-3-4-5 # 2014-01-07 09:42:20

     

  • 时间戳转str格式化时间

    str_time := time.Unix(1389058332, 0).Format("2006-01-02 15:04:05") fmt.Println(str_time) # 2014-01-07 09:32:12
  • str格式化时间转时间戳
    这个比较麻烦

    the_time := time.Date(2014, 1, 7, 5, 50, 4, 0, time.Local) unix_time := the_time.Unix() fmt.Println(unix_time) # 389045004

    还有一种方法,使用time.Parse

    the_time, err := time.Parse("2006-01-02 15:04:05", "2014-01-08 09:04:41") if err == nil {         unix_time := the_time.Unix() 	fmt.Println(unix_time)		 } # 1389171881

 

http://studygolang.com/articles/669
--------------------

Go 如何获取三个月前的月份日期

  1. func main () {
  2. now := time.Now()
  3.  
  4. yesterday := now.AddDate( 0, -1, 0 )
  5. bef_yes := yesterday.AddDate ( 0, -1, 0 )
  6.  
  7. fmt.Printf("Today:%s\n", now.Format("200601"))
  8. fmt.Printf("Yesterday:%s\n", yesterday.Format("200601"))
  9. fmt.Printf("Yesterdat before Yesterday:%s\n",bef_yes.Format("200601"))
 http://www.golangtc.com/t/51bd288c320b5264b800001c
 
--------------
时间比较

先把当前时间格式化成相同格式的字符串,然后使用time的Before, After, Equal 方法即可.

1
2
3
4
5
6
7
8
9
time1 := "2015-03-20 08:50:29"
time2 := "2015-03-21 09:04:25"
//先把时间字符串格式化成相同的时间类型
t1, err := time.Parse("2006-01-02 15:04:05", time1)
t2, err := time.Parse("2006-01-02 15:04:05", time2)
if err == nil && t1.Before(t2) {
  //处理逻辑
  fmt.Println("true")
}
 http://www.jb51.net/article/64705.htm
--------------
golang time 时间的加减法
http://blog.csdn.net/codyguo/article/details/53009451
 

使用golang生成证书

 http://studygolang.com/articles/9959

 
http://blog.csdn.net/yevvzi/article/details/54346519

golang null值处理

NULL值处理

简单说就是设计数据库的时候不要出现null,处理起来非常费力。Null的type很有限,例如没有sql.NullUint64; null值没有默认零值。

for rows.Next() {     var s sql.NullString     err := rows.Scan(&s)     // check err     if s.Valid {        // use s.String     } else {        // NULL value     } }

 

https://segmentfault.com/a/1190000003036452
 
 
------------

而对于在Go中构建页面, text/template 中的很多功能不会自动判断Nullable类型,比如 {{if .Property}} ,如果 Property 属性是Nullable类型,且他是 NULL 即 Valid 属性为 false ,但是模板中的 if 还是会认为 true ,因为这个Nullable类型本身是一个值所以 if 会认为是 true,而Nullable类型本身到底是不是 NULL 根本没有意义,所以必须要写 {{if .Property.Valid}}。在输出上,也要写 {{.Property.String}} (不同Nullable类型值得属性会不一样,这里以 sql.NullString 演示)。

或者用实际代码演示这个问题:

package main  import (     "bytes"     "database/sql"     "fmt"     "text/template" )  type Test struct {     EmptyString    sql.NullString     NonEmptyString sql.NullString }  func main() {     test := &Test{}     test.EmptyString = sql.NullString{Valid: false}     test.NonEmptyString = sql.NullString{Valid: true, String: "Mgen"}     template := template.Must(template.New("test").Parse("{{if .EmptyString}}{{.NonEmptyString}}{{end}}"))     buffer := &bytes.Buffer{}     err := template.Execute(buffer, test)     if err != nil {         panic(err)     }     fmt.Print(buffer.String()) } 

这段代码会输出:

{Mgen true} 

验证了上面讲的两个问题:

  • 为 NULL 的Nullable类型会在模板 if 中直接理解成 true .
  • 输出问题,上面输出 {Mgen true} 实际上就是把 sql.NullString 的两个内部属性全部输出出来了。

Go中 NullString 类型定义:

type NullString struct {         String string         Valid  bool // Valid is true if String is not NULL } 

所以正确的模板应该这样写:

template := template.Must(template.New("test").Parse("{{if .EmptyString.Valid}}{{.NonEmptyString.String}}{{end}}")) 

总之一旦遇到数据库中的 NULL ,还是会稍微有些麻烦的,目前的解决方案可供选择:

  • 数据库中尽量不存 NULL 值,或者使用 ISNULL 或 COALESCE 对 NULL 值坐下处理。
  • JSON上对Nullable类型进行改造,模板定义上属性要针对Nullable类型的属性做判断。
  • 不需要Nullable, NULL 值转换成空值, 这是文章开头我说的愿望:joy:,目前不支持 。
 
 
http://www.tuicool.com/articles/QJZJjaQ

Golang1.7.3使用x509标准库创建自签名证书和签发名其他证书

主代码: package rsa  import (     "crypto/rand"     "crypto/rsa"     "crypto/x509"     "crypto/x509/pkix"     "encoding/pem"     "io/ioutil"     "math/big"     rd "math/rand"     "os"     "time" )  func init() {     rd.Seed(time.Now().UnixNano()) }  type CertInformation struct {     Country            []string     Organization       []string     OrganizationalUnit []string     EmailAddress       []string     Province           []string     Locality           []string     CommonName         string     CrtName, KeyName   string     IsCA               bool     Names              []pkix.AttributeTypeAndValue }  func CreateCRT(RootCa *x509.Certificate, RootKey *rsa.PrivateKey, info CertInformation) error {     Crt := newCertificate(info)     Key, err := rsa.GenerateKey(rand.Reader, 2048)     if err != nil {         return err     }      var buf []byte     if RootCa == nil || RootKey == nil {         //创建自签名证书         buf, err = x509.CreateCertificate(rand.Reader, Crt, Crt, &Key.PublicKey, Key)     } else {         //使用根证书签名         buf, err = x509.CreateCertificate(rand.Reader, Crt, RootCa, &Key.PublicKey, RootKey)     }     if err != nil {         return err     }      err = write(info.CrtName, "CERTIFICATE", buf)     if err != nil {         return err     }      buf = x509.MarshalPKCS1PrivateKey(Key)     return write(info.KeyName, "PRIVATE KEY", buf) } //编码写入文件 func write(filename, Type string, p []byte) error {     File, err := os.Create(filename)     defer File.Close()     if err != nil {         return err     }     var b *pem.Block = &pem.Block{Bytes: p, Type: Type}     return pem.Encode(File, b) }  func Parse(crtPath, keyPath string) (rootcertificate *x509.Certificate, rootPrivateKey *rsa.PrivateKey, err error) {     rootcertificate, err = ParseCrt(crtPath)     if err != nil {         return     }     rootPrivateKey, err = ParseKey(keyPath)     return }  func ParseCrt(path string) (*x509.Certificate, error) {     buf, err := ioutil.ReadFile(path)     if err != nil {         return nil, err     }     p := &pem.Block{}     p, buf = pem.Decode(buf)     return x509.ParseCertificate(p.Bytes) }  func ParseKey(path string) (*rsa.PrivateKey, error) {     buf, err := ioutil.ReadFile(path)     if err != nil {         return nil, err     }     p, buf := pem.Decode(buf)     return x509.ParsePKCS1PrivateKey(p.Bytes) }  func newCertificate(info CertInformation) *x509.Certificate {     return &x509.Certificate{         SerialNumber: big.NewInt(rd.Int63()),         Subject: pkix.Name{             Country:            info.Country,             Organization:       info.Organization,             OrganizationalUnit: info.OrganizationalUnit,             Province:           info.Province,             CommonName:         info.CommonName,             Locality:           info.Locality,             ExtraNames:         info.Names,         },         NotBefore:             time.Now(),//证书的开始时间         NotAfter:              time.Now().AddDate(20, 0, 0),//证书的结束时间         BasicConstraintsValid: true, //基本的有效性约束         IsCA:           info.IsCA,   //是否是根证书         ExtKeyUsage:    []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},    //证书用途         KeyUsage:       x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,         EmailAddresses: info.EmailAddress,     } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
测试代码: package rsa  import (     "crypto/x509/pkix"     "encoding/asn1"     "os"     "testing" )  func Test_crt(t *testing.T) {     baseinfo := CertInformation{Country: []string{"CN"}, Organization: []string{"WS"}, IsCA: true,         OrganizationalUnit: []string{"work-stacks"}, EmailAddress: []string{"czxichen@163.com"},         Locality: []string{"SuZhou"}, Province: []string{"JiangSu"}, CommonName: "Work-Stacks",         CrtName: "test_root.crt", KeyName: "test_root.key"}      err := CreateCRT(nil, nil, baseinfo)     if err != nil {         t.Log("Create crt error,Error info:", err)         return     }     crtinfo := baseinfo     crtinfo.IsCA = false     crtinfo.CrtName = "test_server.crt"     crtinfo.KeyName = "test_server.key"     crtinfo.Names = []pkix.AttributeTypeAndValue{{asn1.ObjectIdentifier{2, 1, 3}, "MAC_ADDR"}} //添加扩展字段用来做自定义使用      crt, pri, err := Parse(baseinfo.CrtName, baseinfo.KeyName)     if err != nil {         t.Log("Parse crt error,Error info:", err)         return     }     err = CreateCRT(crt, pri, crtinfo)     if err != nil {         t.Log("Create crt error,Error info:", err)     }     os.Remove(baseinfo.CrtName)     os.Remove(baseinfo.KeyName)     os.Remove(crtinfo.CrtName)     os.Remove(crtinfo.KeyName) }

 

http://blog.csdn.net/fyxichen/article/details/53010255

 

Go加密解密之RSA

 安全总是很重要的,各个语言对于通用的加密算法都会有实现。前段时间,用Go实现了RSA和DES的加密解密,在这分享一下。(对于RSA和DES加密算法本身,请查阅相关资料)

在PHP中,很多功能经常是一个函数解决;而Go中的却不是。本文会通过PHP加密,Go解密;Go加密,PHP解密来学习Go的RSA和DES相关的API。

该文讨论Go RSA加密解密。所有操作在linux下完成。

一、概要

这是一个非对称加密算法,一般通过公钥加密,私钥解密。

在加解密过程中,使用openssl生产密钥。执行如下操作:

1)创建私钥
openssl genrsa -out private.pem 1024 //密钥长度,1024觉得不够安全的话可以用2048,但是代价也相应增大
2)创建公钥
openssl rsa -in private.pem -pubout -out public.pem

这样便生产了密钥。

一般地,各个语言也会提供API,用于生成密钥。在Go中,可以查看encoding/pem包和crypto/x509包。具体怎么产生,可查看《GO加密解密RSA番外篇:生成RSA密钥》

加密解密这块,涉及到很多标准,个人建议需要的时候临时学习一下。

http://blog.studygolang.com/2013/01/go%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%E4%B9%8Brsa/

-------------------

http://www.golangtc.com/t/54c0c8ff421aa95374000091

Records:47123456