mimir

package module
v1.5.7 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2020 License: MIT Imports: 41 Imported by: 1

README

Mimir

Description

Mimir is an Package Library tools that helps your application at scale. With Mimir, you can:

  • Breaker
  • Logging
  • Sql Pagination
  • AWS lambda handler for http go standard

Installation

go get -u github.com/suryakencana007/mimir

Usage

  • Use a Breaker
package main
import (
    "net/http"
    "github.com/hashicorp/go-cleanhttp"
    "github.com/suryakencana007/mimir/breaker"
    "github.com/suryakencana007/mimir/log"
)

func main() {
    endpoint := `www.google.com`
    cb := breaker.NewBreaker(
        "",
        100,
        10,
    )
    var res *http.Response
    err := cb.Execute(func() (err error) {
        client := cleanhttp.DefaultClient()
        req, _ := http.NewRequest(http.MethodGet,
            endpoint, nil)
        res, err = client.Do(req)
        return err
    })
    if err != nil {
        log.Error("Error",
            log.Field("error", err.Error()),
        )
        panic(err)
    }
}
  • Use a Log
package main
import (
    "github.com/suryakencana007/mimir/log"
)

func main(){
    log.ZapInit()
    
    log.Error("Error",
        log.Field("error", "error for log"),
    )
    log.Debug("Debug",
        log.Field("debug", "debug for log"),
        log.Field("message", "message debug for log"),
    )
    log.Info("Info",
        log.Field("info", "info for log"),
        log.Field("message", "message info for log"),
    )
    log.Warn("Warn",
        log.Field("warning", "warning for log"),
        log.Field("message", "message warning for log"),
    )
}

  • Use sql Pagination
package main

import (
    "net/http"
    "github.com/suryakencana007/mimir/sql"
)

func main() {
    handler := func() http.HandlerFunc { 
        return func(w http.ResponseWriter, r *http.Request) {
            pagination := &sql.Pagination{
                Params: r.URL.Query(),
            }
            orders := service.All(pagination)
            body := response.NewResponse()
            body.SetData(orders)
            body.Pagination = &response.Pagination{
                Page:  pagination.Page,
                Size:  pagination.Limit,
                Total: pagination.Total,
            }
            response.WriteJSON(w, r, body)
        }
    }
    http.ListenAndServe(":8080", handler())
}
  • AWS lambda http handler
package main

import (
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/suryakencana007/mimir/request"
)

func main() {
    handler := func() http.HandlerFunc { 
        return func(w http.ResponseWriter, r *http.Request) {
            pagination := &sql.Pagination{
                Params: r.URL.Query(),
            }
            orders := service.All(pagination)
            body := response.NewResponse()
            body.SetData(orders)
            body.Pagination = &response.Pagination{
                Page:  pagination.Page,
                Size:  pagination.Limit,
                Total: pagination.Total,
            }
            response.WriteJSON(w, r, body)
        }
    }
    lambda.Start(
        request.HandleEvent(
            handler(),
        ),
    )
}
Importing the package

This package can be used by adding the following import statement to your .go files.

    import "github.com/suryakencana007/mimir"

FAQ

Please do! We are looking for any kind of contribution to improve and add more library function helper Mimir core funtionality and documentation. When in doubt, make a PR!

License

Copyright 2019, Nanang Suryadi (https://nulis.dev)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Documentation

Index

Constants

View Source
const (
	RecommendedRoundsSHA1   = 131000
	RecommendedRoundsSHA256 = 29000
	RecommendedRoundsSHA512 = 25000
)
View Source
const (
	// 2xx
	StatusSuccess  = http.StatusOK
	StatusCreated  = http.StatusCreated
	StatusAccepted = http.StatusAccepted
	// 3xx
	StatusPermanentRedirect = http.StatusPermanentRedirect
	// 4xx
	StatusBadRequest            = http.StatusBadRequest
	StatusUnauthorized          = http.StatusUnauthorized
	StatusPaymentRequired       = http.StatusPaymentRequired
	StatusForbidden             = http.StatusForbidden
	StatusMethodNotAllowed      = http.StatusMethodNotAllowed
	StatusNotAcceptable         = http.StatusNotAcceptable
	StatusInvalidAuthentication = http.StatusProxyAuthRequired
	StatusRequestTimeout        = http.StatusRequestTimeout
	StatusUnsupportedMediaType  = http.StatusUnsupportedMediaType
	StatusUnProcess             = http.StatusUnprocessableEntity
	//5xx
	StatusInternalError           = http.StatusInternalServerError
	StatusBadGatewayError         = http.StatusBadGateway
	StatusServiceUnavailableError = http.StatusServiceUnavailable
	StatusGatewayTimeoutError     = http.StatusGatewayTimeout
)

Variables

View Source
var (
	NotPointer = errors.New("must pass a pointer, not a value")
	NilPointer = errors.New("nil pointer passed")
)
View Source
var (
	CtxResponse = ctxKeyResponse{Name: "context Respond"}
	CtxVersion  = ctxKeyVersion{Name: "context version"}
)
View Source
var (
	RenderContext = ctxRender{Name: "context render"}
)

Functions

func Application

func Application(interrupt InterruptChannel, app ApplicationFunc) (func(), error)

func Base64Decode

func Base64Decode(src string) (dst []byte, err error)

Base64Encode decodes using a Standard of base64. return string base64 encode

func Base64Encode

func Base64Encode(src []byte) (dst string)

Base64Encode encodes using a Standard of base64. return string base64 encode

func CloneStruct

func CloneStruct(src, dest interface{}) error

func Config

func Config(opts ConfigOpts, configFunc ConfigFunc) error

func DateRangeValidation

func DateRangeValidation(fl validator.FieldLevel) bool

func DateValidation

func DateValidation(fl validator.FieldLevel) bool

func DatetimeValidation

func DatetimeValidation(fl validator.FieldLevel) bool

func Debug

func Debug(msg string, fields ...interface{})

func Debugf

func Debugf(msg string, args ...interface{})

func DefaultClient

func DefaultClient(duration int) *http.Client

func DefaultPooledTransport

func DefaultPooledTransport(duration int) *http.Transport

func DefaultTransport

func DefaultTransport(duration int) *http.Transport

func Error

func Error(msg string)

func Errorf

func Errorf(msg string, args ...interface{})

func Fatal

func Fatal(msg string, fields ...interface{})

func Field

func Field(key string, value interface{}) interface{}

func GRPCkommen

func GRPCkommen() string

func GenerateChar

func GenerateChar(length int) string

GenerateVoucher Generate Voucher using Alphanumeric except O & 0 return as String

func HashPassword

func HashPassword(password, salt string) string

func Info

func Info(msg string, fields ...interface{})

func Infof

func Infof(msg string, args ...interface{})

func Instance

func Instance() *zapLog

func Logger

func Logger() func(next http.Handler) http.Handler

func NewZap

func NewZap(c Core) *zapLog

New creates new instance of zapLog

func NewZapProductionEncoderConfig

func NewZapProductionEncoderConfig() zapcore.EncoderConfig

func Panic

func Panic(msg string, fields ...interface{})

func ParseDate

func ParseDate(dtStr string) time.Time

func ParseDatetime

func ParseDatetime(dtStr string) time.Time

func ParseTagPayment

func ParseTagPayment(fl validator.FieldLevel) bool

func PassLibBase64Decode

func PassLibBase64Decode(src string) (dst []byte, err error)

PassLibBase64Decode decodes using a variant of base64, like Passlib. Check https://pythonhosted.org/passlib/lib/passlib.utils.html#passlib.utils.ab64_decode

func PassLibBase64Encode

func PassLibBase64Encode(src []byte) (dst string)

PassLibBase64Encode encodes using a variant of base64, like Passlib. Check https://pythonhosted.org/passlib/lib/passlib.utils.html#passlib.utils.ab64_encode

func Recovery

func Recovery() func(next http.Handler) http.Handler

func Redirect

func Redirect(w http.ResponseWriter, r *http.Request, url string)

func RenderReader

func RenderReader(r *http.Request) interface{}

func RenderWriter

func RenderWriter(r *http.Request, value interface{})

func SemanticVersion

func SemanticVersion(r *http.Request, label string, version string)

func Status

func Status(w http.ResponseWriter, r *http.Request, status int, v *Respond) *responseWriter

func StatusCode

func StatusCode(code int) string

func StatusText

func StatusText(code int) string

func ToCamel

func ToCamel(s string) string

ToCamel converts a string to CamelCase

func Tracer

func Tracer(service, version string, logger Logging) (opentracing.Tracer, func(), error)

func TracerServer

func TracerServer(tracer opentracing.Tracer, operationName string) func(next http.Handler) http.Handler

func TracerSpanCallback

func TracerSpanCallback(ctx context.Context, operation string, f func(span context.Context) error) error

func ULID added in v1.5.7

func ULID() ulid.ULID

Universally Unique Lexicographically Sortable Identifier

func UUID

func UUID() string

UUID returns a newly initialized string object that implements the UUID interface.

func VerifyPassword

func VerifyPassword(hashpassword, password string) (bool, error)

func Warn

func Warn(msg string, fields ...interface{})

func Warnf

func Warnf(msg string, args ...interface{})

func Welkommen added in v1.5.7

func Welkommen() string

Types

type AppRunner

type AppRunner func(context.Context) error

type ApplicationFunc

type ApplicationFunc func(context.Context) (AppRunner, func(), error)

type CircuitBreaker

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

func NewBreaker

func NewBreaker(name string, timeout, maxConcurrent int, args ...interface{}) *CircuitBreaker

SetCommandBreaker the circuit breaker

func (*CircuitBreaker) Execute

func (cb *CircuitBreaker) Execute(fn func() error) (err error)

callBreaker command circuit breaker

type ConfigConstants

type ConfigConstants interface{}

type ConfigFunc

type ConfigFunc func(*viper.Viper) error

type ConfigOpts

type ConfigOpts struct {
	Config   ConfigConstants
	Filename string
	Paths    []string
}

type Core

type Core = zapcore.Core

func DefaultCore

func DefaultCore(out zapcore.WriteSyncer) Core

func ProductionCore

func ProductionCore() Core

type ErrorValidator

type ErrorValidator struct {
	Type    string `json:"error_type,omitempty"`
	Tag     string `json:"error_tag,omitempty"`
	Field   string `json:"error_field,omitempty"`
	Value   string `json:"error_value,omitempty"`
	Message string `json:"error_message,omitempty"`
}

func Validate

func Validate(s interface{}) (errors []ErrorValidator)

type GRPCCallback

type GRPCCallback func(*rpc.Server) error

type GRPCOpts

type GRPCOpts struct {
	Logger Logging
	Port   GRPCPort
	Opts   []rpc.ServerOption
}

type GRPCPort

type GRPCPort int

type GRPCRunFunc

type GRPCRunFunc func(context.Context, GRPCCallback) error

func RemoteCallProc

func RemoteCallProc(opts GRPCOpts) (GRPCRunFunc, func())

type Https

type Https bool

type InterruptChannel

type InterruptChannel <-chan os.Signal

func InterruptChannelFunc

func InterruptChannelFunc() InterruptChannel

type LogFactory

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

func (LogFactory) Bg

func (b LogFactory) Bg() Logging

func (LogFactory) With

func (b LogFactory) With(fields ...interface{}) LogFactory

type Logging

type Logging interface {
	With(fields ...interface{}) Logging
	Debug(msg string, fields ...interface{})
	Debugf(msg string, args ...interface{})
	Info(msg string, fields ...interface{})
	Infof(msg string, args ...interface{})
	Warn(msg string, fields ...interface{})
	Warnf(msg string, args ...interface{})
	Error(msg string)
	Errorf(msg string, args ...interface{})
	Fatal(msg string, fields ...interface{})
	Panic(msg string, fields ...interface{})
	Field(key string, value interface{}) interface{} // for type fields
}

func For

func For(ctx context.Context) Logging

func With

func With(fields ...interface{}) Logging

type MediaType

type MediaType string
const (
	ApplicationJSON MediaType = "application/json"
	FormURLEncoded  MediaType = "application/x-www-form-urlencoded"
	MultipartForm   MediaType = "multipart/form-data"
	TextPlain       MediaType = "text/plain"
)

type Meta

type Meta struct {
	Code    string `json:"code,omitempty"`
	Type    string `json:"error_type,omitempty"`
	Message string `json:"error_message,omitempty"`
}

type Pagination

type Pagination struct {
	Page  int `json:"page"`
	Size  int `json:"size"`
	Total int `json:"total"`
}

type Respond added in v1.5.7

type Respond struct {
	Version    interface{} `json:"version,omitempty"`
	Meta       interface{} `json:"meta,omitempty"`
	Data       interface{} `json:"data,omitempty"`
	Pagination interface{} `json:"pagination,omitempty"`
}

func Response

func Response(r *http.Request) *Respond

func (*Respond) APIStatusAccepted added in v1.5.7

func (r *Respond) APIStatusAccepted(w http.ResponseWriter, req *http.Request) *responseWriter

APIStatusAccepted

func (*Respond) APIStatusBadGatewayError added in v1.5.7

func (r *Respond) APIStatusBadGatewayError(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusBadGatewayError

func (*Respond) APIStatusBadRequest added in v1.5.7

func (r *Respond) APIStatusBadRequest(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusBadRequest

func (*Respond) APIStatusCreated added in v1.5.7

func (r *Respond) APIStatusCreated(w http.ResponseWriter, req *http.Request) *responseWriter

APIStatusCreated

func (*Respond) APIStatusForbidden added in v1.5.7

func (r *Respond) APIStatusForbidden(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusForbidden

func (*Respond) APIStatusGatewayTimeoutError added in v1.5.7

func (r *Respond) APIStatusGatewayTimeoutError(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusGatewayTimeoutError

func (*Respond) APIStatusInternalError added in v1.5.7

func (r *Respond) APIStatusInternalError(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusInternalError

func (*Respond) APIStatusInvalidAuthentication added in v1.5.7

func (r *Respond) APIStatusInvalidAuthentication(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusInvalidAuthentication

func (*Respond) APIStatusMethodNotAllowed added in v1.5.7

func (r *Respond) APIStatusMethodNotAllowed(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusMethodNotAllowed

func (*Respond) APIStatusNotAcceptable added in v1.5.7

func (r *Respond) APIStatusNotAcceptable(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusNotAcceptable

func (*Respond) APIStatusPaymentRequired added in v1.5.7

func (r *Respond) APIStatusPaymentRequired(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusPaymentRequired

func (*Respond) APIStatusPermanentRedirect added in v1.5.7

func (r *Respond) APIStatusPermanentRedirect(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusPermanentRedirect

func (*Respond) APIStatusRequestTimeout added in v1.5.7

func (r *Respond) APIStatusRequestTimeout(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusRequestTimeout

func (*Respond) APIStatusServiceUnavailableError added in v1.5.7

func (r *Respond) APIStatusServiceUnavailableError(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusServiceUnavailableError

func (*Respond) APIStatusSuccess added in v1.5.7

func (r *Respond) APIStatusSuccess(w http.ResponseWriter, req *http.Request) *responseWriter

APIStatusSuccess for standard request api status success

func (*Respond) APIStatusUnProcess added in v1.5.7

func (r *Respond) APIStatusUnProcess(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusUnProcess

func (*Respond) APIStatusUnauthorized added in v1.5.7

func (r *Respond) APIStatusUnauthorized(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusUnauthorized

func (*Respond) APIStatusUnsupportedMediaType added in v1.5.7

func (r *Respond) APIStatusUnsupportedMediaType(w http.ResponseWriter, req *http.Request, err error) *responseWriter

APIStatusUnsupportedMediaType

func (*Respond) Body added in v1.5.7

func (r *Respond) Body(body interface{})

func (*Respond) Errors added in v1.5.7

func (r *Respond) Errors(err ...Meta) *Respond

func (*Respond) Page added in v1.5.7

func (r *Respond) Page(p Pagination)

func (*Respond) Success added in v1.5.7

func (r *Respond) Success(code int) *Respond

type ServeOpts

type ServeOpts struct {
	Logger   Logging
	Port     WebPort
	Router   ruuto.Router
	TimeOut  WebTimeOut
	TLS      Https
	CertFile string
	KeyFile  string
}

type ServerRunFunc

type ServerRunFunc func(context.Context) error

func ListenAndServe

func ListenAndServe(opts ServeOpts) (ServerRunFunc, func(context.Context))

type Version

type Version struct {
	Label  string `json:"label,omitempty"`
	Number string `json:"number,omitempty"`
}

type WebPort

type WebPort int

type WebTimeOut

type WebTimeOut int

type ZapField

type ZapField = zapcore.Field

Jump to

Keyboard shortcuts

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