How to handle sql.NullString, sql.NullInt64,


I’m stuck trying to override the default behaviour of c.JSON(…).

I have some NULL values in my records, so I defined structures like this:

type User struct {
	ID        int            `json:"ID" sql:"id"`
	Username  string         `json:"Username" sql:"username"`
	Password  string         `json:"Password" sql:"password"`
	Email     sql.NullString `json:"Email" sql:"email"`
	SocketID  sql.NullInt64  `json:"SocketID" sql:"SocketID"`
	Enabled   sql.NullInt64  `json:"Enabled" sql:"Enabled"`
	SessionID sql.NullString `json:"SessionID" sql:"SessionID"`
	Avatar    sql.NullString `json:"Avatar" sql:"Avatar"`
	State     sql.NullString `json:"State" sql:"State"`
	Hidden    sql.NullString `json:"Hidden" sql:"Hidden"`

Handling the request to GET users, I use this json response:

return c.JSON(http.StatusOK, response)

For sql.Null… values, I get:

  "Email": {
    "String": "",
    "Valid": false
  "SocketID": {
    "Int64": 0,
    "Valid": false

I’m trying to override the default Marshal using:

type NullString sql.NullString

func (x *NullString) MarshalJSON() ([]byte, error) {
if !x.Valid {
return []byte("null"), nil
return json.Marshal(x.String)

But I can’t get a json with just the value (or blank string).

How did you manage this?

Thank you. :slight_smile:

Went through similar issue.
Then, after researching a lot, found this as the best solution:

Just import this package

import (
   // Other packages
    nullable ""

And use types defined in this package

type Book struct {
	ID       int64           `json:"id" db:"id"`
	Source   nullable.String `json:"source" db:"source"`
	Type     nullable.Int    `json:"type" db:"type"`

Now binding with c.Bind(), c.JSON() etc will work seamlessly.

hmm … the site is interesting. We had a problem … There was the end of the semester, it remained to pass a couple more essays … The most difficult, unfortunately. One day we were studying at a friend’s house, which was not very convenient … We asked older students, they said that since some time they have been using one site - it became interesting to us. Well, we registered there … Helped !!! I hope it will help you too.