项目作者: smgladkovskiy

项目描述 :
Golang structs - nullables and with support of custom format
高级语言: Go
项目地址: git://github.com/smgladkovskiy/structs.git
创建时间: 2018-10-27T20:22:15Z
项目社区:https://github.com/smgladkovskiy/structs

开源协议:GNU General Public License v3.0

下载


Deprecated

This repo was deprecated. I was young, inexperienced, and I was thinking about the wrong thing. I’m sorry. :)

structs

Various helpful golang structs package

Zeroable types

Default value is zero value.

  • date
  • time

Nullable types

Default value is null value.

  • string
  • bool
  • int64
  • float64
  • time
  • date

Usage

Get package via go get github.com/smgladkovskiy/structs or via dep ensure add github.com/smgladkovskiy/structs
if you use dep.

Import package in your go file:

  1. package main
  2. import (
  3. "github.com/smgladkovskiy/structs" // if need to set date or time format
  4. "github.com/smgladkovskiy/structs/null" // if nullables are used
  5. "github.com/smgladkovskiy/structs/zero" // if zeroables are used
  6. )

Use in code:

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/smgladkovskiy/structs" // if need to set date or time format
  6. "github.com/smgladkovskiy/structs/null" // if nullables are used
  7. "github.com/smgladkovskiy/structs/zero" // if zeroables are used
  8. )
  9. func main() {
  10. structs.TimeFormat = func() string {
  11. return time.RFC1123
  12. }
  13. customTime, _ := null.NewTime(time.Now())
  14. if !customTime.Valid {
  15. fmt.Println("time is null")
  16. return
  17. }
  18. fmt.Printf("custom time is %s", customTime.Time)
  19. }

Helper functions and variables

zero.NewXXX(v interface{}) *zero.XXX

Initiates new zero value of XXX type, using Scan method with passed value.

null.NewXXX(v interface{}) *null.XXX

Initiates new nullable value of XXX type, using Scan method with passed value.

null.NewXXXf(format string, a …interface{}) *null.XXX

Initiates new null.String type value for passed format string and format variables. Available for strings.

TimeFormat

There is an opportunity for zero.Time and null.Time types to set time format witch will be used with (Un)MarshallJSON methods.

To override default package format for time (time.RFC3339), there must be an stucts.TimeFormat function
overriding in your app at the configuration or init level:

  1. package main
  2. import (
  3. "time"
  4. "github.com/smgladkovskiy/structs"
  5. )
  6. func main() {
  7. structs.TimeFormat = func() string {
  8. return time.RFC1123
  9. }
  10. }

DateFormat

For zero.Date and null.Date types there is the same thing with format for (Un)MarshallJSON.

Default package date format (YYYY-MM-DD) must be overridden with stucts.DateFormat function:

  1. package main
  2. import (
  3. "github.com/smgladkovskiy/structs"
  4. )
  5. func init() {
  6. structs.DateFormat = func() string {
  7. return "02.01.2006"
  8. }
  9. }