4 changed files with 46 additions and 26 deletions
@ -0,0 +1,3 @@ |
|||
DBPath: main.db |
|||
ListenAddr: :8080 |
|||
ShortedIDLength: 4 |
|||
@ -1,49 +1,63 @@ |
|||
package main |
|||
|
|||
import ( |
|||
"io/ioutil" |
|||
"log" |
|||
"os" |
|||
"os/signal" |
|||
"strconv" |
|||
"path/filepath" |
|||
|
|||
"github.com/maxibanki/golang-url-shortener/handlers" |
|||
"github.com/maxibanki/golang-url-shortener/store" |
|||
"github.com/pkg/errors" |
|||
yaml "gopkg.in/yaml.v2" |
|||
) |
|||
|
|||
func main() { |
|||
dbPath := "main.db" |
|||
listenAddr := ":8080" |
|||
idLength := 4 |
|||
if os.Getenv("SHORTENER_DB_PATH") != "" { |
|||
dbPath = os.Getenv("SHORTENER_DB_PATH") |
|||
} |
|||
if os.Getenv("SHORTENER_LISTEN_ADDR") != "" { |
|||
listenAddr = os.Getenv("SHORTENER_LISTEN_ADDR") |
|||
} |
|||
if os.Getenv("SHORTENER_ID_LENGTH") != "" { |
|||
var err error |
|||
idLength, err = strconv.Atoi(os.Getenv("SHORTENER_ID_LENGTH")) |
|||
stop := make(chan os.Signal, 1) |
|||
signal.Notify(stop, os.Interrupt) |
|||
close, err := initShortener() |
|||
if err != nil { |
|||
log.Fatalf("could not parse shortener ID length: %v", err) |
|||
log.Fatalf("could not init shortener: %v", err) |
|||
} |
|||
<-stop |
|||
log.Println("Shutting down...") |
|||
close() |
|||
} |
|||
|
|||
func initShortener() (func(), error) { |
|||
var config struct { |
|||
DBPath string `yaml:"DBPath"` |
|||
ListenAddr string `yaml:"ListenAddr"` |
|||
ShortedIDLength int `yaml:"ShortedIDLength"` |
|||
} |
|||
stop := make(chan os.Signal, 1) |
|||
signal.Notify(stop, os.Interrupt) |
|||
store, err := store.New(dbPath, idLength) |
|||
ex, err := os.Executable() |
|||
if err != nil { |
|||
log.Fatalf("could not create store: %v", err) |
|||
return nil, errors.Wrap(err, "could not get executable path") |
|||
} |
|||
handler := handlers.New(listenAddr, *store) |
|||
file, err := ioutil.ReadFile(filepath.Join(filepath.Dir(ex), "config.yml")) |
|||
if err != nil { |
|||
return nil, errors.Wrap(err, "could not read configuration file: %v") |
|||
} |
|||
err = yaml.Unmarshal(file, &config) |
|||
if err != nil { |
|||
return nil, errors.Wrap(err, "could not unmarshal yaml file") |
|||
} |
|||
store, err := store.New(config.DBPath, config.ShortedIDLength) |
|||
if err != nil { |
|||
return nil, errors.Wrap(err, "could not create store") |
|||
} |
|||
handler := handlers.New(config.ListenAddr, *store) |
|||
go func() { |
|||
err := handler.Listen() |
|||
if err != nil { |
|||
log.Fatalf("could not listen to http handlers: %v", err) |
|||
} |
|||
}() |
|||
<-stop |
|||
log.Println("Shutting down...") |
|||
return func() { |
|||
err = handler.CloseStore() |
|||
if err != nil { |
|||
log.Printf("failed to stop the handlers: %v", err) |
|||
} |
|||
}, nil |
|||
} |
|||
|
|||
Loading…
Reference in new issue