Skip to content

Instantly share code, notes, and snippets.

@rdp rdp/server.cr

forked from jgaskins/server.cr
Last active Dec 4, 2019
Embed
What would you like to do?
Serve a sample JSON payload in Crystal
require "http"
require "uuid"
require "uuid/json"
class App
include HTTP::Handler
def call(context)
Fiber.yield # Simulate getting data from the DB
response_payload.to_json context.response
end
def response_payload
products = [
{
id: rand(),
name: "The First Product",
description: "This is the first product in the collection",
price_cents: 1000_00,
},
{
id: rand(),
name: "The Second Product",
description: "This is the second product in the collection",
price_cents: 1000_00,
},
{
id: rand(),
name: "The Third Product",
description: "This is the third product in the collection",
price_cents: 1000_00,
},
]
{
customer: {
id: rand(),
name: "Jamie Gaskins",
email: "jamie@example.com",
created_at: Time.now,
updated_at: Time.now,
},
order: {
id: rand(),
product_ids: products.map{ |p| p[:id] },
},
products: products,
}
end
end
port = 9000
puts "Listening on #{port}"
HTTP::Server.new([App.new]).listen port
// Golang server for comparison to the Crystal version
package main
import (
"log"
"net/http"
"time"
"encoding/json"
"github.com/satori/go.uuid"
)
type Product struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
PriceCents int32 `json:"price_cents"`
}
type Products []Product
type Customer struct {
Id string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type Order struct {
Id string `json:"id"`
ProductIds []string `json:"product_ids"`
}
type Payload struct {
Customer Customer `json:"customer"`
Order Order `json:"order"`
Products Products `json:"products"`
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
guid, _ := uuid.NewV4()
id := guid.String()
products := Products{
Product{
Id: id,
Name: "The First Product",
Description: "This is the first product in the collection",
PriceCents: 100000,
},
Product{
Id: id,
Name: "The Second Product",
Description: "This is the second product in the collection",
PriceCents: 100000,
},
Product{
Id: id,
Name: "The Third Product",
Description: "This is the third product in the collection",
PriceCents: 100000,
},
}
product_ids := []string {
id,
id,
id,
}
payload := Payload{
Customer: Customer{
Id: id,
Name: "Jamie Gaskins",
Email: "jamie@example.com",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
},
Order: Order{
Id: id,
ProductIds: product_ids,
},
Products: products,
}
json.NewEncoder(w).Encode(payload)
})
log.Fatal(http.ListenAndServe(":54321", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.