Null friendly types

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

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
Similar Resources

lsp is like ls command but more human-friendly

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,

Dec 12, 2022

Tile is a 2D grid engine, built with data and cache friendly ways, includes pathfinding and observers.

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

Dec 26, 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

Dec 25, 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

Dec 30, 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

Dec 21, 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

Jan 2, 2023

[Crawler/Scraper for Golang]🕷A lightweight distributed friendly Golang crawler framework.一个轻量的分布式友好的 Golang 爬虫框架。

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

Oct 29, 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

Jan 4, 2023

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

Dec 24, 2022

A beginner friendly introduction to prometheus 🔥

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

Dec 29, 2022

A Friendly SSH Jumper Bastion Fortress Server

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

Jan 2, 2023

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

Jan 6, 2023

Command line tool for improving typing skills (programmers friendly)

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 5, 2023

vgrep - a user-friendly pager for grep

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

Jan 3, 2023

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

Dec 16, 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.

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

Jan 5, 2023

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

Jan 2, 2023

KintoHub is an open source build and deployment platform designed with a developer-friendly interface for Kubernetes.

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

Jun 7, 2022
Comments
  • 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?

  • 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?

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

Sep 26, 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

Feb 12, 2022
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

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.
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

Dec 6, 2022
null

chrome-webrtc-packet-log-parser Project status At this point the project is primerly intended to be used by checking it out and modifying main.go, how

Dec 19, 2022
null

Cleaning Code in Go Introduction So, this article is a little different from my others. Instead of focusing on a specific product, or solving a spefic

Sep 4, 2022
Grpc-gateway-map-null - gRPC Gateway test using nullable values in map

Demonstrate gRPC gateway behavior with nullable values in maps Using grpc-gatewa

Jan 6, 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

Nov 9, 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.

Oct 7, 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

Nov 9, 2022