add file (json+toml)

This commit is contained in:
Martin Geno 2017-10-25 18:58:54 +02:00
parent 0d64ba751e
commit 80290a8a17
No known key found for this signature in database
GPG Key ID: F0D39A37E925E941
4 changed files with 75 additions and 51 deletions

60
file/main.go Normal file
View File

@ -0,0 +1,60 @@
package file
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/BurntSushi/toml"
)
// ReadConfigFile reads a config model from path of a yml file
func ReadTOML(path string, data interface{}) error {
file, err := ioutil.ReadFile(path)
if err != nil {
return err
}
err = toml.Unmarshal(file, data)
if err != nil {
return err
}
return nil
}
// ReadJSON reads a config model from path of a yml file
func ReadJSON(path string, data interface{}) error {
file, err := os.Open(path)
if err != nil {
return err
}
err = json.NewDecoder(file).Decode(data)
if err != nil {
return err
}
return nil
}
// SaveJSON to path
func SaveJSON(outputFile string, data interface{}) error {
tmpFile := outputFile + ".tmp"
f, err := os.OpenFile(tmpFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
err = json.NewEncoder(f).Encode(data)
if err != nil {
return err
}
f.Close()
if err := os.Rename(tmpFile, outputFile); err != nil {
return err
}
return nil
}

15
file/worker.go Normal file
View File

@ -0,0 +1,15 @@
package file
import (
"time"
"github.com/genofire/golang-lib/worker"
)
func NewSaveJSONWorker(repeat time.Duration, path string, data interface{}) *worker.Worker {
saveWorker := worker.NewWorker(repeat, func() {
SaveJSON(path, data)
})
go saveWorker.Start()
return saveWorker
}

View File

@ -1,29 +0,0 @@
// Package that provides the functionality to start und initialize the logger
package log
import (
"log"
"net/http"
logger "github.com/Sirupsen/logrus"
httpLib "github.com/genofire/golang-lib/http"
)
// Current logger with it's configuration
var Log *logger.Logger
// Function to initiate a new logger
func init() {
Log = logger.New()
// Enable fallback, if core logger
log.SetOutput(Log.Writer())
}
// Function to add the information of a http request to the log
func HTTP(r *http.Request) *logger.Entry {
return Log.WithFields(logger.Fields{
"remote": httpLib.GetRemoteIP(r),
"method": r.Method,
"url": r.URL.RequestURI(),
})
}

View File

@ -1,22 +0,0 @@
// Package that provides the functionality to start und initialize the logger
package log
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
// Function to test the logging
func TestLog(t *testing.T) {
assertion := assert.New(t)
req, _ := http.NewRequest("GET", "https://google.com/lola/duda?q=wasd", nil)
log := HTTP(req)
_, ok := log.Data["remote"]
assertion.NotNil(ok, "remote address not set in logger")
assertion.Equal("GET", log.Data["method"], "method not set in logger")
assertion.Equal("/lola/duda?q=wasd", log.Data["url"], "path not set in logger")
}