Skip to content

Instantly share code, notes, and snippets.

@neomatrixcode
Created February 10, 2021 18:23
Show Gist options
  • Save neomatrixcode/d3c595a61846df3deb434ceb3c1a649a to your computer and use it in GitHub Desktop.
Save neomatrixcode/d3c595a61846df3deb434ceb3c1a649a to your computer and use it in GitHub Desktop.
using Merly
using JSON
function tojson(data::String)
return JSON.parse(data)
end
formats["application/json"] = tojson
mutable struct Animal
type::String
name::String
end
ANIMALS = Dict{Int, Animal}()
const NEXT_ID = Ref(0)
function getNextId()
id = NEXT_ID[]
NEXT_ID[] += 1
return id
end
@route POST "/createAnimal" (;JSON=JSON,ANIMALS=ANIMALS,getNextId=getNextId,Animal=Animal) begin
id = getNextId()
ANIMALS[id] = Animal(request.body["type"],request.body["name"])
info=Dict()
info["id"]=id
info["type"]= request.body["type"]
info["name"]= request.body["name"]
body = JSON.json(info)
HTTP.Response(201
, HTTP.mkheaders(["Content-Type" => "application/json"])
,body= body)
end
@route GET "/getAnimals" (;JSON=JSON,ANIMALS=ANIMALS) begin
HTTP.Response(200
,HTTP.mkheaders(["Content-Type" => "application/json"])
,body=JSON.json(ANIMALS))
end
@route GET "/getAnimal/:id" (;JSON=JSON,ANIMALS=ANIMALS) begin
id = parse(Int,request.params["id"])
HTTP.Response(200
,HTTP.mkheaders(["Content-Type" => "application/json"])
,body=JSON.json( ANIMALS[id])
)
end
@route PUT "/updateAnimal/:id" (;JSON=JSON,ANIMALS=ANIMALS,Animal=Animal) begin
id = parse(Int,request.params["id"])
ANIMALS[id] = Animal(request.body["type"],request.body["name"])
HTTP.Response(200)
end
@route DELETE "/deleteAnimal/:id" (;ANIMALS=ANIMALS) begin
id = parse(Int,request.params["id"])
delete!(ANIMALS, id)
HTTP.Response(200)
end
start(host = "127.0.0.1", port = 8086, verbose = true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment