Skip to content

Commit

Permalink
Merge pull request #19 from oleg-balunenko/envvarconfig
Browse files Browse the repository at this point in the history
Env var config
  • Loading branch information
obalunenko authored Apr 30, 2020
2 parents 6247d86 + f9e911a commit c0a7627
Show file tree
Hide file tree
Showing 11 changed files with 39 additions and 145 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ linters-settings:
# make an issue if func has more lines of code than this setting and it has naked returns; default is 30
max-func-lines: 30
goimports:
local-prefixes: github.com/oleg-balunenko/instadiff-cli/
local-prefixes: github.com/oleg-balunenko/scrum-report/
unparam:
algo: cha
check-exported: false
Expand Down
32 changes: 0 additions & 32 deletions cmd/scrum-report/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ package main

import (
"log"
"net"

"github.com/pkg/errors"

"github.com/oleg-balunenko/scrum-report/internal/config"
"github.com/oleg-balunenko/scrum-report/internal/logger"
Expand All @@ -15,39 +12,10 @@ func main() {
printVersion()

cfg := config.Load()
if cfg.Debug {
ip, err := getIP()
if err != nil {
log.Fatalf("failed to get ip: %v", err)
}

cfg.Host = ip
}

logger.SetUp(cfg)

r := reporter.New(cfg)

log.Fatal(r.Run())
}

func getIP() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", errors.Wrap(err, "failed to get addresses")
}

var ip string

for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
break
}
}
}

return ip, nil
}
6 changes: 5 additions & 1 deletion docker-compose.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ services:
build:
context: .
dockerfile: Dockerfile

environment:
SCRUM_REPORT_PORT: "8080"
SCRUM_REPORT_LOG_LEVEL: "DEBUG"
ports:
- "8080:8080"

networks:
scrumreport_dev:
Expand Down
5 changes: 5 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ services:
networks:
- scrum_report
image: olegbalunenko/scrum-report
environment:
SCRUM_REPORT_PORT: "8080"
SCRUM_REPORT_LOG_LEVEL: "DEBUG"
ports:
- "8080:8080"

networks:
scrum_report:
Expand Down
2 changes: 2 additions & 0 deletions env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SCRUM_REPORT_PORT=8080
SCRUM_REPORT_LOG_LEVEL=INFO
30 changes: 15 additions & 15 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
package config

import (
"flag"
"os"
)

// Config stores configuration for service.
type Config struct {
LogLevel string
Port string
Host string
Debug bool
OpenBrowser bool
LogLevel string
Port string
}

// Load configuration from flags.
func Load() *Config {
func Load() Config {
var c Config

flag.StringVar(&c.Host, "host_address", "127.0.0.1", "address of host")
flag.StringVar(&c.Port, "listen_port", "8080", "listen port")
flag.StringVar(&c.LogLevel, "log_level", "INFO", "log level")
flag.BoolVar(&c.Debug, "debug", false, `Run debug mode - use real ip machine instead localhost
to possible to debug with Charles`)
flag.BoolVar(&c.OpenBrowser, "open_browser", false, "open browser after start on index page")
c.Port = getStringOrDefault("SCRUM_REPORT_PORT", "8080")
c.LogLevel = getStringOrDefault("SCRUM_REPORT_LOG_LEVEL", "INFO")

flag.Parse()
return c
}

func getStringOrDefault(key string, defVal string) string {
val, ok := os.LookupEnv(key)
if !ok || val == "" {
return defVal
}

return &c
return val
}
3 changes: 2 additions & 1 deletion internal/logger/logger.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package logger provides functionality for logger set up.
package logger

import (
Expand All @@ -9,7 +10,7 @@ import (
)

// SetUp sets up logger logs level and format.
func SetUp(config *config.Config) {
func SetUp(config config.Config) {
log.SetOutput(os.Stdout)
log.SetFormatter(new(log.TextFormatter))

Expand Down
6 changes: 3 additions & 3 deletions internal/reporter/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type report struct {

func createHandler(writer http.ResponseWriter, request *http.Request) {
if err := request.ParseForm(); err != nil {
http.Error(writer, "failed to parse form", http.StatusInternalServerError)
http.Error(writer, "failed to parse form", http.StatusBadRequest)
return
}

Expand All @@ -47,7 +47,7 @@ func createHandler(writer http.ResponseWriter, request *http.Request) {
}
}

func indexHandler(writer http.ResponseWriter, request *http.Request) {
func indexHandler(writer http.ResponseWriter, _ *http.Request) {
writer.Header().Set("Content-Type", "text/html")

if err := homePageTmpl.Execute(writer, nil); err != nil {
Expand All @@ -56,7 +56,7 @@ func indexHandler(writer http.ResponseWriter, request *http.Request) {
}

// optionsHandlerOld set up allowed verbs.
func optionsHandler(writer http.ResponseWriter, request *http.Request) {
func optionsHandler(writer http.ResponseWriter, _ *http.Request) {
writer.Header().Set("Allow", "GET,POST")
}

Expand Down
79 changes: 0 additions & 79 deletions internal/reporter/helpers.go
Original file line number Diff line number Diff line change
@@ -1,88 +1,9 @@
package reporter

import (
"net/http"
netUrl "net/url"
"os/exec"
"runtime"
"strings"
"time"

"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)

// open opens the specified URL in the default browser of the user.
func open(url string) error {
url, err := sanitizeURL(url)
if err != nil {
return errors.Wrap(err, "invalid url")
}

for {
time.Sleep(time.Second)

log.Debug("Checking if started...")

resp, err := http.Get(url) // nolint
if err != nil {
log.Warn("Failed:", err)
continue
}

if err = resp.Body.Close(); err != nil {
log.Errorf("failed to close body: %v", err)
}

if resp.StatusCode != http.StatusOK {
log.Warn("Not OK:", resp.StatusCode)
continue
}
// Reached this point: server is up and running!
break
}

log.Debug("SERVER UP AND RUNNING!")
log.Debug("Opening browser")

var (
cmd string
args []string
)

switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}

args = append(args, url)

log.Debugf("try to execute: %s %s", cmd, args)

return exec.Command(cmd, args...).Start()
}

// sanitizeURL validates url and add protocol prefix.
func sanitizeURL(url string) (string, error) {
// workaround for this issue: https://github.com/golang/go/issues/18824
if !strings.HasPrefix(url, "http://") || !strings.HasPrefix(url, "https://") {
url = "http://" + url
}

// validate url.
u, err := netUrl.Parse(url)
if err != nil {
return "", errors.Wrap(err, "failed to parse url")
}

return u.String(), nil
}

func processFormValue(data string) []string {
var res []string

Expand Down
17 changes: 4 additions & 13 deletions internal/reporter/service.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package reporter provides functionality for report generation.
package reporter

import (
Expand Down Expand Up @@ -39,12 +40,12 @@ func routes() []route {

// Service holds all data required by reporter.
type Service struct {
config *config.Config
config config.Config
handler http.Handler
}

// New creates new service from passed config.
func New(cfg *config.Config) *Service {
func New(cfg config.Config) *Service {
return &Service{
config: cfg,
handler: newRouter(),
Expand All @@ -53,19 +54,9 @@ func New(cfg *config.Config) *Service {

// Run runs reporter service.
func (s *Service) Run() error {
addr := fmt.Sprintf("%s:%s", s.config.Host, s.config.Port)
addr := fmt.Sprintf(":%s", s.config.Port)
log.Debugf("address: %s", addr)

if s.config.OpenBrowser {
go func() {
err := open(addr)
if err != nil {
// not need to return this error - just log.
log.Errorf("failed to open browser: %v", err)
}
}()
}

return http.ListenAndServe(addr, s.handler)
}

Expand Down
2 changes: 2 additions & 0 deletions web/generator.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Package web handles generated static.
// To update views - add changes to template htmls and run go generate.
package web

//go:generate go-bindata -pkg=web templates/

0 comments on commit c0a7627

Please sign in to comment.