Null friendly types

Overview

go-nulltype

Build Status codecov

Nullable types friendly to json.Encoder, json.Decoder, database/sql, fmt.Stringer, text/template, html/template, some of ORMs.

Supported types:

  • NullBool
  • NullString
  • NullFloat64
  • NullInt64
  • NullTime

Usage

import "github.com/mattn/go-nulltype"

type User struct {
	Name	nulltype.NullString `json:"name"`
}

friendly to Stringer

var user User
fmt.Println(user.Name.Valid()) // false
fmt.Println(user.Name) // ""

user.Name.Set("Bob")
fmt.Println(user.Name.Valid()) // true
fmt.Println(user.Name) // "Bob"

fmt.Println(user.Name.StringValue() == "Bob") // true

user.Name.Reset()
fmt.Println(user.Name.Valid()) // false
fmt.Println(user.Name) // ""

friendly to json.MarshalJSON

var user User
fmt.Println(user.Name.Valid()) // false
json.NewEncoder(os.Stdout).Encode(user) // {"name": null}

user.Name.Set("Bob")
fmt.Println(user.Name.Valid()) // true
json.NewEncoder(os.Stdout).Encode(user) // {"name": "Bob"}

friendly to json.UnmarshalJSON

var user User
s := `{"name": "Bob"}`
json.NewDecoder(strings.NewReader(s)).Decode(&user)
fmt.Println(user.Name.Valid()) // true
fmt.Println(user.Name) // "Bob"

s = `{"name": null}`
json.NewDecoder(strings.NewReader(s)).Decode(&user)
fmt.Println(user.Name.Valid()) // false
fmt.Println(user.Name) // ""

friendly to database/sql

var user User
db.QueryRow(`SELECT name FROM users`).Scan(&user.Name)
fmt.Println(user.Name.Valid()) // true or false
fmt.Println(user.Name) // "Bob" or ""
db.Exec(`INSERT INTO users(name) VALUES($1)`, user.Name)

friendly to ORM

Struct tag with gorp.

type Post struct {
	Id      int64 `db:"post_id"`
	Created int64
	Title   string              `db:",size:50"`
	Body    nulltype.NullString `db:"body,size:1024"`
}
p := Post{
	Created: time.Now().UnixNano(),
	Title:   title,
	Body:    nulltype.NullStringOf(body),
}
err = dbmap.Insert(&p)

Installation

go get github.com/mattn/go-nulltype

License

MIT

Author

Yasuhiro Matsumoto

Issues
  • Make Valid method with value receiver for all value types to have Valid() interface

    Make Valid method with value receiver for all value types to have Valid() interface

    Every example in your repository contains value struct attributes, like

    type User struct {
    	Name	nulltype.NullString `json:"name"`
    }
    

    and together with ozzo validation library and go1.18 generics feature, required validation can be expressed as

    type Validatable interface {
    	Valid() bool
    }
    
    func validateNullable[V Validatable](value interface{}) error {
    	var v, ok = value.(V)
    	if !ok || !v.Valid() {
    		return errors.New("can not be null")
    	}
    	return nil
    }
    
    validation.Field(&strct.Field, validation.By(validateNullable[nulltype.NullBool])),
    

    but for some reason every null type has a pointer receiver in Valid method and it breaks type cast. Other way is to introduce reflect inside validateNullable, but I can not see a reason for Valid method to be pointer receiver, maybe you can explain it otherwise?

    opened by alexeysofin 4
  • Does not support YAML parser?

    Does not support YAML parser?

    I am using the github.com/go-yaml/yaml package to parse the YAML file, but go-nulltype does not seem to support this package, how can I solve this problem?

    opened by dxvgef 2
Owner
mattn
Long-time Golang user&contributor, Google Dev Expert for Go, and author of many Go tools, Vim plugin author. Windows hacker C#/Java/C/C++
mattn
Plugs module to see different types of plug types needed in different countries, and a comparison tool between two countries plug socket types.

plugs Importing the module: go get github.com/matthewboyd/plugs "github.com/matthewboyd/plugs" How to use the module: There are two functions wi

Matthew Boyd 2 Dec 28, 2021
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.

Errors Errors package is a drop-in replacement of the built-in Go errors package with no external dependencies. It lets you create errors of 11 differ

Kamaleshwar 42 May 18, 2022
Null Types, Safe primitive type conversion and fetching value from complex structures.

Typ Typ is a library providing a powerful interface to impressive user experience with conversion and fetching data from built-in types in Golang Feat

Gurukami 32 Aug 5, 2022
Some Golang types based on builtin. Implements interfaces Value / Scan and MarshalJSON / UnmarshalJSON for simple working with database NULL-values and Base64 encoding / decoding.

gotypes Some simple types based on builtin Golang types that implement interfaces for working with DB (Scan / Value) and JSON (Marshal / Unmarshal). N

null 0 Feb 12, 2022
Library providing opanapi3 and Go types for store/validation and transfer of ISO-4217, ISO-3166, and other types.

go-types This library has been created with the purpose to facilitate the store, validation, and transfer of Go ISO-3166/ISO-4217/timezones/emails/URL

Mikalai Konan 13 Jul 18, 2022
Go linter that checks types that are json encoded - reports unsupported types and unnecessary error checks

Checks types passed to the json encoding functions. Reports unsupported types and reports occations, where the check for the returned error can be omited.

Lucas Bremgartner 26 Jun 17, 2022
Optional is a library that provides option types for Go types.

Option Optional is a library that provides option types for Go types. Installation Golang version 1.18 + required go get -u github.com/eatmoreapple/op

聂青 5 May 15, 2022
lsp is like ls command but more human-friendly

lsp: list files in a mildly human-frendlier manner lsp lists files, like ls command, but it does not attempt to meet that archaic POSIX specification,

Dmitry Borzov 509 Jul 10, 2022
Tile is a 2D grid engine, built with data and cache friendly ways, includes pathfinding and observers.

Tile: Data-Oriented 2D Grid Engine This repository contains a 2D tile map engine which is built with data and cache friendly ways. My main goal here i

Roman Atachiants 62 Aug 7, 2022
Go Humans! (formatters for units to human friendly sizes)

Humane Units Just a few functions for helping humanize times and sizes. go get it as github.com/dustin/go-humanize, import it as "github.com/dustin/go

Dustin Sallings 3.3k Aug 15, 2022
Super short, fully unique, non-sequential and URL friendly Ids

Generator of unique non-sequential short Ids The package shortidenables the generation of short, fully unique, non-sequential and by default URL frien

teris.io 782 Aug 5, 2022
A test-friendly replacement for golang's time package

timex timex is a test-friendly replacement for the time package. Usage Just replace your time.Now() by a timex.Now() call, etc. Mocking Use timex.Over

Cabify 63 May 3, 2022
Go Humans! (formatters for units to human friendly sizes)

Humane Units Just a few functions for helping humanize times and sizes. go get it as github.com/dustin/go-humanize, import it as "github.com/dustin/go

Dustin Sallings 3.3k Aug 15, 2022
[Crawler/Scraper for Golang]🕷A lightweight distributed friendly Golang crawler framework.一个轻量的分布式友好的 Golang 爬虫框架。

Goribot 一个分布式友好的轻量的 Golang 爬虫框架。 完整文档 | Document !! Warning !! Goribot 已经被迁移到 Gospider|github.com/zhshch2002/gospider。修复了一些调度问题并分离了网络请求部分到另一个仓库。此仓库会继续

null 208 Jul 4, 2022
URL-friendly slugify with multiple languages support.

slug Package slug generate slug from unicode string, URL-friendly slugify with multiple languages support. Documentation online Example package main

GoSimple 845 Aug 11, 2022
A user-friendly CMS written in Go (golang)

Fragmenta CMS Fragmenta CMS is a user-friendly Content Management System built with Go. For more information and a demo of the CMS in action, see the

Fragmenta 589 Aug 6, 2022
A beginner friendly introduction to prometheus 🔥

Prometheus-Basics A beginner friendly introduction to prometheus. Table of Contents What is prometheus ? What are metrics and why is it important ? Ba

S Santhosh Nagaraj 1.6k Aug 2, 2022
A Friendly SSH Jumper Bastion Fortress Server

Felix 中文 Thanks to 360 Total Security and 360-web-platform For Whom BackEnd Engineer Golang SQL RESTful APIs engineer DevOps Engineer People Heavily e

mojocn 711 Aug 8, 2022
A user friendly RabbitMQ library written in Golang.

TurboCookedRabbit A user friendly RabbitMQ library written in Golang to help use streadway/amqp. Based on my work found at CookedRabbit. Work Recently

Tristan (HouseCat) Hyams 102 Jul 18, 2022
Command line tool for improving typing skills (programmers friendly)

Command line tool for improving typing speed and accuracy. The main goal is to help programmers practise programming languages. Demo Installation Pyth

Jan 355 Aug 9, 2022
vgrep - a user-friendly pager for grep

vgrep is a pager for grep, git-grep, ripgrep and similar grep implementations, and allows for opening the indexed file locations in a user-specified e

Valentin Rothberg 582 Aug 8, 2022
User-friendly Go library for building Grafana dashboards

Grabana Grabana provides a developer-friendly way of creating Grafana dashboards. Whether you prefer writing code or YAML, if you are looking for a wa

Kévin Gomez 456 Aug 10, 2022
tbls is a CI-Friendly tool for document a database, written in Go.

tbls is a CI-Friendly tool for document a database, written in Go. Key features of tbls are: Document a database automatically in GFM format. Output d

Ken’ichiro Oyama 1.5k Aug 7, 2022
Plik is a scalable & friendly temporary file upload system ( wetransfer like ) in golang.

Want to chat with us ? Telegram channel : https://t.me/plik_root_gg Plik Plik is a scalable & friendly temporary file upload system ( wetransfer like

root.gg 1k Aug 10, 2022
KintoHub is an open source build and deployment platform designed with a developer-friendly interface for Kubernetes.

What is Kintohub? KintoHub is an open source build and deployment platform designed with a developer-friendly interface for Kubernetes. Build your cod

KintoHub 30 Jun 7, 2022
Package mafsa implements Minimal Acyclic Finite State Automata in Go, essentially a high-speed, memory-efficient, Unicode-friendly set of strings.

MA-FSA for Go Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA) with Minimal Perfect Hashing (MPH). Basically, it's a set of str

SmartyStreets (Archives) 291 Jul 2, 2022
Testcontainers is a Golang library that providing a friendly API to run Docker container. It is designed to create runtime environment to use during your automatic tests.

When I was working on a Zipkin PR I discovered a nice Java library called Testcontainers. It provides an easy and clean API over the go docker sdk to

null 1.5k Aug 8, 2022
A lightweight Vault client module written in Go, with no dependencies, that is intuitive and user-friendly

libvault A lightweight Hashicorp Vault client written in Go, with no dependencies. It aims to provide an intuitive, simple API that is easy to use. Ju

null 75 Jun 22, 2022