Skip to content

Commit

Permalink
Add Register function to register new service to config.json
Browse files Browse the repository at this point in the history
  • Loading branch information
babarot committed Apr 19, 2018
1 parent eb377ae commit d4d79d8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
32 changes: 32 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
Expand All @@ -21,6 +23,8 @@ const (

type Config struct {
Services []Service `json:"services"`

path string
}

type Service struct {
Expand Down Expand Up @@ -57,6 +61,7 @@ func configDir() (string, error) {
}

func (cfg *Config) LoadFile(file string) error {
cfg.path = file
_, err := os.Stat(file)
if err == nil {
raw, _ := ioutil.ReadFile(file)
Expand Down Expand Up @@ -157,3 +162,30 @@ func (cfg *Config) Edit() error {
cmd.Stdin = os.Stdin
return cmd.Run()
}

func (cfg *Config) Registered(url string) bool {
u1, _ := neturl.Parse(url)
for _, service := range cfg.Services {
u2, _ := neturl.Parse(service.URL)
if u1.Host == u2.Host {
return true
}
}
return false
}

func (cfg *Config) Register(s Service) error {
cfg.Services = append(cfg.Services, s)
b, err := json.Marshal(cfg)
if err != nil {
return err
}
var out bytes.Buffer
if err := json.Indent(&out, b, "", " "); err != nil {
return err
}
file, _ := os.OpenFile(cfg.path, os.O_WRONLY, 0644)
w := bufio.NewWriter(file)
w.Write(out.Bytes())
return w.Flush()
}
7 changes: 7 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,13 @@ func (c CLI) run() int {
)
args = append(args, url)

if !c.cfg.Registered(url) {
c.cfg.Register(Service{
URL: url,
Env: env,
})
}

s := newShell(env.Binary, args)
return c.exit(s.run())
}
Expand Down

0 comments on commit d4d79d8

Please sign in to comment.