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 { |
| 12 | Port int `default:"4242"` |
| 13 | Listen string `default:"0.0.0.0"` |
| 14 | StartAddress string `default:"10.0.0.2" envconfig:"start_address"` |
| 15 | AddressCount uint `default:"252" envconfig:"address_count"` |
| 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 |
| 34 | StartAddress: %s |
| 35 | AddressCount: %d`, config.Listen, config.Port, config.StartAddress, config.AddressCount) |
| 36 | |
| 37 | context.storage = &MemoryStorage{} |
| 38 | context.storage.Init(config.StartAddress, config.AddressCount) |
| 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 | } |