beaver

package module
v0.0.0-...-8cfe228 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 27, 2018 License: BSD-3-Clause Imports: 8 Imported by: 3

README

beaver build status GoDoc

A set of functions which may be useful when dealing with JSON or logger.
For more information please visit Godoc.

Install

go get github.com/Hunsin/beaver

JSON

Example of reading/writing JSON file and GET/POST JSON from http services.

package main

import (
  "net/http"
  bv "github.com/Hunsin/beaver"
)

type example struct {
  Hello string `json:"hello"`
  Year  int    `json:"year"`
  IP    string `json:"ip"`
}

func main() {
  e := example{
    Hello: "Hello World!",
    Year:  2017,
  }

  // writing JSON file; ignore error
  bv.JSON(&e).WriteFile("example.json")

  // reading JSON file; ignore error
  out := example{}
  js  := bv.JSON(&out)
  js.Open("example.json")

  // now you have the values
  println(out.Hello) // Hello World!
  println(out.Year)  // 2017

  // serving JSON data; ignore error
  http.HandleFunc("/path", func(w http.ResponseWriter, r *http.Request) {
    js.Serve(w, http.StatusOK)
  })

  // get values from other service; ignore error
  // http header is nil in this case
  js.Get("http://ip.jsontest.com", nil)
  println(js.IP)

  // send data to another service
  // the second parameter is your custom http.Header
  err := js.Post("https://url.of.service", nil)
  if err != nil {
    println(err.Error)
  }
}

Logger

Logger wraps log.Logger with additional option to set log levels. Let's see the example:

package main

import (
  "log"
  "os"
  bv "github.com/Hunsin/beaver"
)

func main() {
  f, _ := os.Create("file_name.log")
  defer f.Close()

  // setting the output destination
  bv.LogOutput(f)

  // you can decide what level of logs should write, by default all
  // there are five levels available: Fatal, Error, Warn, Info & Debug
  bv.LogLevel(bv.Lerror | bv.Linfo)

  bv.Info("Hello World!") // 2018/02/06 00:31:28 INFO : Hello World!
  
  // you can define your log tag style
  t := bv.LTag{"| Fatal | ", "| Error | ", "| Warn | ", "| Info | ", "| Debug | "}

  // you can chain functions in configuration
  l := bv.NewLogger().Output(f).Tags(t).Flags(log.Lshortfile)
  l.Error("Hello again!!") // main.go:27: | Error | Hello again!!
}

Documentation

Index

Constants

View Source
const (
	Lfatal = 1 << iota
	Lerror
	Lwarn
	Linfo
	Ldebug

	Lall = Lfatal | Lerror | Lwarn | Linfo | Ldebug
)

The levels define whether a Logger should generate logs in different level

Variables

View Source
var (

	// DefaultLogTag is a LTag with default strings
	DefaultLogTag = LTag{"FATAL:", "ERROR:", "WARN :", "INFO :", "DEBUG:"}

	// BracketLogTag is a LTag with "[...]" style
	BracketLogTag = LTag{"[FATAL]", "[ERROR]", "[WARN ]", "[INFO ]", "[DEBUG]"}
)

Functions

func Debug

func Debug(v ...interface{})

Debug calls default Logger.Debug

func Download

func Download(h http.Header, url, path string) (int64, error)

Download gets the file from a HTTP server with given url and HTTP header, saving it in given path. The file will be truncated if it already exists. A non-2xx status code from server will cause an error and the file won't be created. If h is nil, a default http.Header is applied.

func Error

func Error(v ...interface{})

Error calls default Logger.Error

func Fatal

func Fatal(v ...interface{})

Fatal calls default Logger.Fatal

func Info

func Info(v ...interface{})

Info calls default Logger.Info

func Warn

func Warn(v ...interface{})

Warn calls default Logger.Warn

func WriteFile

func WriteFile(path string, src io.Reader) (int64, error)

WriteFile copies src to the file in given pathname. It overwrites the file if it already exists.

Types

type JSONPod

type JSONPod struct {
	// contains filtered or unexported fields
}

A JSONPod is embedded with a pointer to interface. It is used to deal with JSON-encoding data.

func JSON

func JSON(v interface{}) *JSONPod

JSON returns a pointer to JSONPod which embeded with v. If v is nil or not a pointer, an error may returned when calling methods of JSONPod.

func (*JSONPod) Get

func (j *JSONPod) Get(url string, h http.Header) error

Get parses the JSON-encoded data from specified URL with given header and stores it in j. If the h is nil, a default http.Header is applied. "application/json" is appended to Accept header automatically.

func (*JSONPod) Open

func (j *JSONPod) Open(path string) error

Open parses JSON file from given path and stores the result in j.

func (*JSONPod) Parse

func (j *JSONPod) Parse(b []byte) error

Parse takes []byte b and decode to j.v

func (*JSONPod) Post

func (j *JSONPod) Post(url string, h http.Header) (*http.Response, error)

Post is a shorthand for *JSONPod.Send("POST", url, h)

func (*JSONPod) Put

func (j *JSONPod) Put(url string, h http.Header) (*http.Response, error)

Put is a shorthand for *JSONPod.Send("PUT", url, h)

func (*JSONPod) Send

func (j *JSONPod) Send(method, url string, h http.Header) (*http.Response, error)

Send issues a HTTP request to specified url with given method and header. The request's body is JSON-encoded data of j.v. A http.Response is returned. It is the caller's responsibility to close the response's Body.

func (*JSONPod) Serve

func (j *JSONPod) Serve(w http.ResponseWriter, code int) error

Serve responses with JSON-encoded data of j.v to client by given status code. The Content-Type header is set to "application/json; charset=utf-8". Additional response headers must be set before calling Serve.

func (*JSONPod) ServeGzip

func (j *JSONPod) ServeGzip(w http.ResponseWriter, code int) error

ServeGzip is equivalent to j.Serve() which response body is compressed in gzip format.

func (*JSONPod) Write

func (j *JSONPod) Write(w io.Writer) error

Write marshals j.v and writes the result to w.

func (*JSONPod) WriteFile

func (j *JSONPod) WriteFile(path string) error

WriteFile writes JSON-encoded data of j.v to a file by given path. It appends ".json" to the path if it doesn't end with the string.

type LTag

type LTag struct {
	Fatal, Error, Warn, Info, Debug string
}

A LTag is a set of strings which identify the severity level of each log

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

A Logger wraps a pointer to log.Logger and additional fields. It prints level tag and the log if severity level meets its configuration.

func LogFlags

func LogFlags(f int) *Logger

LogFlags sets the flags of default Logger

func LogLevel

func LogLevel(lv int) *Logger

LogLevel sets the level of default Logger

func LogOutput

func LogOutput(out io.Writer) *Logger

LogOutput sets the output destination of default Logger

func LogPrefix

func LogPrefix(p string) *Logger

LogPrefix sets prefix of default Logger

func LogTags

func LogTags(t LTag) *Logger

LogTags sets the tags of default Logger

func NewLogger

func NewLogger() *Logger

NewLogger returns a new Logger. By default, it logs at all level and the output destination is standard output

func (*Logger) Debug

func (l *Logger) Debug(v ...interface{})

Debug writes debug tag and v to output

func (*Logger) Error

func (l *Logger) Error(v ...interface{})

Error writes error tag and v to output

func (*Logger) Fatal

func (l *Logger) Fatal(v ...interface{})

Fatal calls os.Exit(1) after writes fatal tag and v to output

func (*Logger) Flags

func (l *Logger) Flags(f int) *Logger

Flags sets the flags of the Logger. The flag follows the standard package "log"

func (*Logger) Info

func (l *Logger) Info(v ...interface{})

Info writes info tag and v to output

func (*Logger) Level

func (l *Logger) Level(lv int) *Logger

Level sets the level of the Logger

func (*Logger) Output

func (l *Logger) Output(out io.Writer) *Logger

Output sets the output destination of the Logger. The out must not be nil

func (*Logger) Prefix

func (l *Logger) Prefix(p string) *Logger

Prefix sets the prefix of of the Logger

func (*Logger) Tags

func (l *Logger) Tags(t LTag) *Logger

Tags sets the tags of the Logger. To omit the tag of logs, simply use l.Tags(LTag{})

func (*Logger) Warn

func (l *Logger) Warn(v ...interface{})

Warn writes warn tag and v to output

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL