forked from robmerrell/hipsterdb
/
main.go
86 lines (70 loc) · 1.96 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"flag"
"fmt"
"github.com/hoisie/web"
"github.com/robmerrell/hipsterdb/datastore"
"os"
)
// the datastore that we interface with
var ds *datastore.Datastore
// command line flags
var flagOutOfStyleSeconds, flagMainstreamThreshold uint
var flagPort string
// command line usage
func usage() {
fmt.Fprintf(os.Stderr, "usage: hipsterdb [options]\n")
flag.PrintDefaults()
os.Exit(2)
}
func init() {
// setup the command line processing
flag.UintVar(&flagOutOfStyleSeconds, "o", 100, "seconds it takes for mainstream data to go out of style")
flag.UintVar(&flagMainstreamThreshold, "m", 20, "how many times data can be accessed before it is mainstream")
flag.StringVar(&flagPort, "p", ":9999", "port number to run the DB interface on")
flag.Usage = usage
flag.Parse()
// setup our datastore
ds = &datastore.Datastore{OutOfStyleSeconds: flagOutOfStyleSeconds, MainstreamThreshold: flagMainstreamThreshold}
datastore.ProcessOutOfStyle()
}
// Returns a key or abort with an error if it doesn't exist or the item
// has gone mainstream.
func getItem(ctx *web.Context, key string) string {
item, err := ds.GetItem(key)
if err != nil {
var errorStatus int
if err.Error() == datastore.ACCESS_MISSING {
errorStatus = 404
} else {
errorStatus = 403
}
ctx.Abort(errorStatus, err.Error())
return ""
}
return item.Value
}
// Upsert an item in the datastore.
func upsertItem(ctx *web.Context, key string) string {
value := ctx.Params["value"]
if value == "" {
ctx.Abort(400, "Item creation is missing a value")
return ""
}
// insert the item
item := datastore.NewItem(key, value)
ds.InsertItem(item)
return "created " + key
}
// Delete an item from the datastore.
func deleteItem(ctx *web.Context, key string) string {
ds.DeleteItem(key)
datastore.RemoveFromMainstreamKeys(key)
return "deleted " + key
}
func main() {
web.Get("/(.*)", getItem)
web.Post("/(.*)", upsertItem)
web.Delete("/(.*)", deleteItem)
web.Run(flagPort)
}