David K. Bainbridge | 8bc905c | 2016-05-31 14:07:10 -0700 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "github.com/gorilla/mux" |
| 6 | "github.com/kelseyhightower/envconfig" |
| 7 | "log" |
| 8 | "net/http" |
| 9 | ) |
| 10 | |
| 11 | type Config struct { |
David K. Bainbridge | 252cc2c | 2016-06-02 22:28:59 -0700 | [diff] [blame] | 12 | Port int `default:"4242"` |
| 13 | Listen string `default:"0.0.0.0"` |
| 14 | Network string `default:"10.0.0.0/24"` |
| 15 | Skip int `default:"1"` |
David K. Bainbridge | 8bc905c | 2016-05-31 14:07:10 -0700 | [diff] [blame] | 16 | } |
| 17 | |
| 18 | type Context struct { |
| 19 | storage Storage |
| 20 | } |
| 21 | |
| 22 | func main() { |
| 23 | context := &Context{} |
| 24 | |
| 25 | config := Config{} |
| 26 | err := envconfig.Process("ALLOCATE", &config) |
| 27 | if err != nil { |
| 28 | log.Fatalf("[error] Unable to parse configuration options : %s", err) |
| 29 | } |
| 30 | |
| 31 | log.Printf(`Configuration: |
| 32 | Listen: %s |
| 33 | Port: %d |
David K. Bainbridge | 252cc2c | 2016-06-02 22:28:59 -0700 | [diff] [blame] | 34 | Network: %s |
| 35 | SKip: %d`, config.Listen, config.Port, config.Network, config.Skip) |
David K. Bainbridge | 8bc905c | 2016-05-31 14:07:10 -0700 | [diff] [blame] | 36 | |
| 37 | context.storage = &MemoryStorage{} |
David K. Bainbridge | 252cc2c | 2016-06-02 22:28:59 -0700 | [diff] [blame] | 38 | context.storage.Init(config.Network, config.Skip) |
David K. Bainbridge | 8bc905c | 2016-05-31 14:07:10 -0700 | [diff] [blame] | 39 | |
| 40 | router := mux.NewRouter() |
| 41 | router.HandleFunc("/allocations/{mac}", context.ReleaseAllocationHandler).Methods("DELETE") |
| 42 | router.HandleFunc("/allocations/{mac}", context.AllocationHandler).Methods("GET") |
| 43 | router.HandleFunc("/allocations/", context.ListAllocationsHandler).Methods("GET") |
| 44 | router.HandleFunc("/addresses/{ip}", context.FreeAddressHandler).Methods("DELETE") |
| 45 | http.Handle("/", router) |
| 46 | |
| 47 | http.ListenAndServe(fmt.Sprintf("%s:%d", config.Listen, config.Port), nil) |
| 48 | } |