Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created April 24, 2018 15:40
Show Gist options
  • Save xeoncross/d9d24eb52d55f6a5184823b0ee533d72 to your computer and use it in GitHub Desktop.
Save xeoncross/d9d24eb52d55f6a5184823b0ee533d72 to your computer and use it in GitHub Desktop.
To use `sql.NullString` or `sql.NullInt64` on a Go (golang) struct you need to wrap sql.NullString inside a new type, then implement the json.Unmarshaler interface on that new type.
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"strings"
)
type NullString sql.NullString
func (s *NullString) UnmarshalJSON(data []byte) error {
s.String = strings.Trim(string(data), `"`)
s.Valid = true
return nil
}
type SendgridEvent struct {
Email string `json:"email"`
Timestamp int `json:"timestamp"`
SMTPID string `json:"smtp-id,omitempty"`
SgEventID string `json:"sg_event_id"`
SgMessageID string `json:"sg_message_id"`
Event string `json:"event"`
IP string `json:"ip,omitempty"`
URL string `json:"url,omitempty"`
Useragent NullString `json:"useragent,omitempty"`
SgUserID int `json:"sg_user_id,omitempty"`
AsmGroupID int `json:"asm_group_id,omitempty"`
}
func main() {
body := `[
{
"email":"[email protected]",
"timestamp": 1337197600,
"smtp-id":"<[email protected]>",
"sg_event_id":"sendgrid_internal_event_id",
"sg_message_id":"sendgrid_internal_message_id",
"event": "processed"
},
{
"email":"[email protected]",
"timestamp": 1337966815,
"ip":"X.XX.XXX.XX",
"sg_event_id":"sendgrid_internal_event_id",
"url":"https://sendgrid.com",
"sg_message_id":"sendgrid_internal_message_id",
"useragent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
"event":"click"
},
{
"ip": "X.XX.XXX.XX",
"sg_user_id": 123,
"sg_event_id":"sendgrid_internal_event_id",
"sg_message_id":"sendgrid_internal_message_id",
"useragent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
"event": "group_unsubscribe",
"email": "[email protected]",
"timestamp": 1337969592,
"asm_group_id": 42
}
]`
r := strings.NewReader(body) // fake request body
var records []SendgridEvent
err := json.NewDecoder(r).Decode(&records)
if err != nil {
log.Println(err)
return
}
for _, r := range records {
fmt.Printf("%+v\n", r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment