Skip to content

Instantly share code, notes, and snippets.

@ejholmes
Last active August 29, 2015 14:04
Show Gist options
  • Save ejholmes/f419c53aa6b671b8d123 to your computer and use it in GitHub Desktop.
Save ejholmes/f419c53aa6b671b8d123 to your computer and use it in GitHub Desktop.
API Resource
package main
import (
"encoding/json"
"os"
"time"
)
// Timestamp wraps time.Time and implements the json.Marshaller interface
// for presenting a timestamp in ISO8601 format.
type Timestamp struct {
time.Time
}
// MarshalJSON implements the json.Marshaller interface.
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.ISO8601() + `"`), nil
}
// ISO8601 returns an ISO8601 (RFC3339) formatted string in UTC.
func (t Timestamp) ISO8601() string {
return t.UTC().Format(time.RFC3339)
}
// Resource as an interface that provides a means of transforming a domain
// model into an API resource suitable for encoding.
type Resource interface {
Present() interface{}
}
// jobs is our domain model, probably in a separate package.
type job struct {
ID int
CreatedAt time.Time
}
// JobResource is an implementation of the Resource interface.
type JobResource struct {
*job
}
// Present implements the Resource interface.
func (r *JobResource) Present() interface{} {
return struct {
ID int `json:"id"`
CreatedAt Timestamp `json:"created_at"`
}{
ID: r.job.ID,
CreatedAt: Timestamp{Time: r.job.CreatedAt},
}
}
func main() {
j := &job{ID: 1, CreatedAt: time.Now()}
r := &JobResource{j}
json.NewEncoder(os.Stdout).Encode(r.Present())
// {"id":1,"created_at":"2014-07-17T15:08:16Z"}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment