Skip to content

Instantly share code, notes, and snippets.

@rodrigosavian
Last active March 9, 2016 02:52
Show Gist options
  • Select an option

  • Save rodrigosavian/5820970d58b4e817e755 to your computer and use it in GitHub Desktop.

Select an option

Save rodrigosavian/5820970d58b4e817e755 to your computer and use it in GitHub Desktop.
Custom JSON serializer
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
type Customer struct {
Id int64 `json:"id"`
Name string `json:"name"`
LastSeen time.Time `json:"last_seen"`
FirstSequence string
}
func (c *Customer) getUUID() string {
return "2SB2-3920-3320-SS2908"
}
func (c *Customer) firstSequence(uuid string) string {
return strings.Split(uuid, "-")[0]
}
func (c *Customer) JSONMarshal() ([]byte, error) {
type Alias Customer
return json.Marshal(&struct {
LastSeen int64 `json:"last_seen"`
UUID string `json:"uuid"`
*Alias
}{
LastSeen: c.LastSeen.Unix(),
UUID: c.getUUID(),
Alias: (*Alias)(c),
})
}
func (c *Customer) JSONUnmarshal(data []byte) error {
type Alias Customer
aux := &struct {
LastSeen int64 `json:"last_seen"`
UUID string `json:"uuid"`
*Alias
}{
Alias: (*Alias)(c),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
c.LastSeen = time.Unix(aux.LastSeen, 0)
c.FirstSequence = c.firstSequence(aux.UUID)
return nil
}
func customer(w http.ResponseWriter, r *http.Request) {
c := Customer{2, "Natália", time.Now(), ""}
data, _ := c.JSONMarshal()
cc := Customer{}
cc.JSONUnmarshal(data)
fmt.Println(cc.FirstSequence)
w.Write(data)
}
func main() {
// customer := Customer{1, "Rodrigo", time.Now()}
// _ = json.NewEncoder(os.Stdout).Encode(customer)
// customer.JSONMarshal()
http.HandleFunc("/", customer)
http.ListenAndServe(":8000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment