Example #1
0
func TestError(t *testing.T) {
	tt := testing2.Wrap(t)
	err := errors.Err(`Duplicate entry '14d1b6c34a001-1648e0754a001' for key 'PRIMARY'`) // for combined primary key
	tt.Eq(PRIMARY_KEY, duplicateKey(err))

	err = errors.Err("CONSTRAINT `article_vote_ibfk_1` FOREIGN KEY (`article_id`) REFERENCES `article` (`article_id`)")
	tt.Eq("article_id", foreignKey(err))
}
Example #2
0
// Init set up store and lifetime for session manager
func (sm *sessionManager) Init(store SessionStore, lifetime int64) error {
	if store == nil {
		return errors.Err("Empty session store")
	}
	if lifetime == 0 {
		return errors.Err("Session lifetime is zero 0 no session will be stored")
	}
	sm.store = store
	sm.lifetime = lifetime
	return nil
}
Example #3
0
func TestFunc(t *testing.T) {
	tt := testing2.Wrap(t)

	errReg := errors.Err("regexp not match")
	r := Regexp{
		Regexp: regexp.MustCompile("^\\d+$"),
		Err:    errReg,
	}
	tt.Nil(r.Validate("123"))
	tt.Eq(errReg, r.Validate("123dqe"))

	errLength := errors.Err("Wrong length")
	errChars := errors.Err("Wrong chars")
	length := Length{
		Min: 3, Max: 10, Err: errLength,
	}.Validate
	chars := Chars{
		Chars: "0123456789", Err: errChars,
	}.Validate

	single := Use(length, chars)
	tt.Nil(single("023456"))

	vc := UseMul(length, chars)
	tt.Eq(vc("0"), errLength)
	tt.Eq(vc("0000000000000000000000"), errLength)
	tt.Nil(vc("000"))

	tt.Eq(vc("abcde"), errChars)

	// length process first, chars process remains
	tt.Eq(vc("01", "abc"), errLength)
	tt.Eq(vc("012", "abc"), errChars)
	tt.Eq(vc("012", "a"), errChars)
	tt.Nil(vc("012", "0"))
	tt.Nil(vc("012", "0", "1111111111111111"))

	// length process first, chars process remains
	vc = UseMul(length, Use(length, chars))
	tt.Eq(vc("012", "a"), errLength)
	tt.Eq(vc("012", "0"), errLength)
	tt.Eq(vc("012", "0", "1111111111111111"), errLength)

	vc = UseStrictMul(length, chars)
	tt.Nil(vc("abcd", "1234"))

	defer tt.Recover()
	vc("012", "0", "1111111111111111")
}
Example #4
0
func (j *JSONP) Init(zerver.Env) error {
	if j.CallbackVar == "" {
		return errors.Err("callback name should not be empty")
	}
	j.log = log.Derive("Filter", "JSONP")
	return nil
}
Example #5
0
func TestValidateM(t *testing.T) {
	tt := testing2.Wrap(t)

	err := errors.Err("incorrect length")
	v := ValidLength(3, 10, err).ValidateM
	tt.Eq(err, v("a23", "a"))
	tt.Nil(v("a23", "1234"))
}
Example #6
0
func main() {
	args := flag.Args()

	path := "."
	if len(args) != 0 {
		path = args[0]
	}
	ext = "." + ext

	wg := sync.WaitGroup{}
	errors.Fatal(
		filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}

			if !info.IsDir() && filepath.Ext(info.Name()) == ext {
				wg.Add(1)
				go process(path, &wg)
			}

			return nil
		}),
	)

	wg.Wait()

	errors.CondDo(len(as.categories) == 0,
		errors.Err("No files contains api in this dir or file"),
		errors.FatalAnyln)
	errors.CondDo(outputType != "md",
		errors.Err("Sorry, currently only support markdown format"),
		errors.FatalAnyln)

	orders := slices.Strings(strings2.SplitAndTrim(order, orderSep)).Clear("")
	if fname != "" {
		errors.Fatalln(file.OpenOrCreate(fname, overwrite, func(fd *os.File) error {
			as.WriteMarkDown(fd, orders)

			return nil
		}))
	} else {
		as.WriteMarkDown(os.Stdout, orders)
	}
}
Example #7
0
func BenchmarkSimpleEmail(b *testing.B) {
	se := Use(
		Length{
			Min: 3,
			Max: 10,
			Err: errors.Err("aa"),
		}.Validate,
		SimpleEmail{
			Err: errors.Err("Wrong email"),
		}.Validate,
		Chars{
			Chars: "[email protected]",
			Err:   errors.Err("aa"),
		}.Validate)
	for i := 0; i < b.N; i++ {
		_ = se("[email protected]")
	}
}
Example #8
0
func (c Code) NewS(err string) Error {
	if err == "" {
		return nil
	}

	return HTTPError{
		error: errors.Err(err),
		code:  int(c),
	}
}
Example #9
0
func TestSimpleEmail(t *testing.T) {
	tt := testing2.Wrap(t)
	err := errors.Err("Wrong email")
	se := &SimpleEmail{Err: err}

	tt.Nil(se.Validate("[email protected]"))
	tt.Eq(err, se.Validate("11@1."))
	tt.Eq(err, se.Validate("@1.a"))
	tt.Eq(err, se.Validate("[email protected]"))
	tt.Eq(err, se.Validate("11@"))
}
Example #10
0
func WriteGZIP(w io.Writer, v interface{}) (err error) {
	gw := gzip.NewWriter(w)
	switch v := v.(type) {
	case string:
		_, err = gw.Write(unsafe2.Bytes(v))
	case []byte:
		_, err = gw.Write(v)
	default:
		err = errors.Err("Only support string and []byte")
	}
	gw.Close()

	return
}
Example #11
0
func (m *Queue) Init(env zerver.Env) error {
	if m.Processor == nil {
		return errors.Err("message processor shouldn't be nil")
	}
	if m.TaskBufsize == 0 {
		m.TaskBufsize = 256
	}
	if m.BytesPool == nil {
		m.BytesPool = bytes2.NewFakePool()
	}

	m.queue = make(chan zerver.Task, m.TaskBufsize)
	m.log = log.Derive("TaskHandler", "MessageQueue")
	go m.start()
	return nil
}
Example #12
0
func TestTrace(t *testing.T) {
	tt := testing2.Wrap(t)
	tt.Nil(Trace(nil))

	var e error = errors.Err("Error")

	e2 := Trace(e)
	es := "github.com/cosiner/gohper/errors/trace.TestTrace:trace_test.go:16:" + e.Error()
	tt.Eq(es, e2.Error())

	e2 = Trace(e2)
	tt.Eq(es, e2.Error())

	TraceEnabled = false
	e2 = Trace(e)
	tt.Eq(e2, e)
}
Example #13
0
func TestTrace(t *testing.T) {
	tt := testing2.Wrap(t)
	tt.Nil(Trace(nil))

	var e error = errors.Err("Error")

	e2 := Trace(e)
	es := "trace_test.go:16:" + e.Error()
	tt.Eq(es, e2.Error())

	e2 = Trace(e2)
	tt.Eq(es, e2.Error())

	TraceEnabled = false
	e2 = Trace(e)
	tt.Eq(e2, e)
}
Example #14
0
func (x *Xsrf) Init(env zerver.Env) error {
	if x.Secret == "" {
		return errors.Err("xsrf secret can't be empty")
	}

	defval.Int64(&x.Timeout, _DEF_XSRF_TIMEOUT)
	defval.Nil(&x.HashMethod, sha256.New)
	defval.String(&x.Error, "xsrf token is invalid or not found")

	if x.UsePool {
		if x.Pool == nil {
			x.Pool = bytes2.NewSyncPool(0, true)
		}
	} else {
		x.Pool = bytes2.FakePool{}
	}
	defval.Nil(&x.TokenInfo, jsonToken{})
	x.log = log.Derive("Component", "Xsrf")
	return nil
}
Example #15
0
func (m *Queue) Init(env zerver.Environment) error {
	if m.Processor == nil {
		return errors.Err("message processor shouldn't be nil")
	}
	if m.TaskBufsize == 0 {
		m.TaskBufsize = 256
	}
	if m.ErrorLogger == nil {
		m.ErrorLogger = env.Logger()
	}
	m.ErrorLogger = m.ErrorLogger.Prefix("zerver/msq")
	if m.BytesPool == nil {
		m.BytesPool = bytes2.NewFakePool()
	}

	m.queue = make(chan zerver.Task, m.TaskBufsize)

	go m.start()
	return nil
}
Example #16
0
func (m *Queue) Init(zerver.Environment) error {
	if m.Processor == nil {
		return errors.Err("message processor shouldn't be nil")
	}
	if m.Bufsize == 0 {
		m.Bufsize = 1024
	}

	m.queue = make(chan interface{}, m.Bufsize)
	m.signal = make(chan struct{})

	go func() {
		for {
			select {
			case msg := <-m.queue:
				m.Process(msg)
			case <-m.signal:
				return
			}
		}
	}()

	return nil
}
Example #17
0
package token

import (
	"bytes"
	"crypto/hmac"
	"encoding/binary"
	"hash"
	"time"

	"github.com/cosiner/gohper/encoding"
	"github.com/cosiner/gohper/errors"
	"github.com/cosiner/gohper/time2"
)

const (
	ErrBadKey           = errors.Err("bad key")
	ErrExpiredKey       = errors.Err("expired key")
	ErrInvalidSignature = errors.Err("invalid signature")
)

type Cipher struct {
	signKey []byte
	ttl     time.Duration
	hash    func() hash.Hash
	sigLen  int
	hdrLen  int
}

func NewCipher(signKey []byte, ttl time.Duration, hash func() hash.Hash, encs ...encoding.Encoding) encoding.Encoding {
	sigLen := hash().Size() / 3
	return encoding.Pipe(encs).Prepend(&Cipher{
Example #18
0
import (
	"bytes"
	"fmt"
	"html/template"
	"net/smtp"
	"strings"

	"github.com/cosiner/gohper/bytes2"
	"github.com/cosiner/gohper/errors"
	"github.com/cosiner/gohper/strings2"
	"github.com/cosiner/gohper/unsafe2"
)

const (
	ErrNoTemplate = errors.Err("no template for this type")
)

type mailTemplate struct {
	Subject string
	*template.Template
}

type Mail struct {
	From    string
	To      []string
	Subject string

	Type string
	Data interface{}
Example #19
0
		if nano%base >= base/2 {
			ms++
		}
		return strconv.Itoa(ms) + "ms"
	}

	base *= 1000
	var s = int(nano / base)
	if nano%base >= base/2 {
		s++
	}
	return strconv.Itoa(s) + "s"
}

const (
	ErrWrongHumanTimeFormat = errors.Err("wrong human time format")
)

// ParseHuman convert human time format to duration.
// support:
// 	'H': hour,
// 	'M': minute,
// 	'S': second,
// 	'm': millsecond,
// 	'u': microsecond,
// 	'n': nanosecond
func ParseHuman(timestr string) (time.Duration, error) {
	var t, counter time.Duration
	for i, l := 0, len(timestr); i < l; i++ {
		c := timestr[i]
		if c >= '0' && c <= '9' {
Example #20
0
package validate

import (
	"github.com/cosiner/gohper/errors"
)

const (
	ErrParamsCountNotMatch = errors.Err("parameters count not matched with validators")
)

type Validator func(string) error
type ValidChain []Validator

func New(validators ...Validator) ValidChain {
	return ValidChain(validators)
}

func Use(vc ...Validator) Validator {
	return New(vc...).Validate
}

func UseMul(vc ...Validator) func(...string) error {
	return New(vc...).ValidateM
}

func UseStrictMul(vc ...Validator) func(...string) error {
	return New(vc...).StrictValidateM
}

// Validate string with validators, return first error or nil
func (vc ValidChain) Validate(s string) error {
Example #21
0
// ScanURLVars scan values into variable addresses
// if address is nil, skip it
func (v *urlVarIndexer) ScanURLVar(name string, addr interface{}) error {
	if index, has := v.vars[name]; has {
		return reflect2.UnmarshalPrimitive(v.values[index], reflect.ValueOf(addr))
	}
	return errors.Err("No this variable: " + name)
}
Example #22
0
func (j JSONP) Init(zerver.Environment) error {
	if string(j) == "" {
		return errors.Err("callback name should not be empty")
	}
	return nil
}
Example #23
0
package filter

import (
	"sync"

	"github.com/cosiner/gohper/errors"
	"github.com/cosiner/gohper/utils/defval"
	"github.com/cosiner/kv"
	"github.com/cosiner/ygo/log"
	"github.com/cosiner/zerver"
	"github.com/cosiner/zerver/component"
)

const (
	ErrRequestIDExist = errors.Err("Request id already exist")
)

type (
	// RequestId is a simple filter prevent application/user from overlap request
	// the request id is generated by client itself or other server components.
	RequestId struct {
		Store         IDStore
		HeaderName    string
		PassingOnNoId bool
		Error         string
		ErrorOverlap  string
		logger        log.Logger
	}

	IDStore interface {
		zerver.Component
Example #24
0
		chars    []byte    // all possible first characters of next route node
		childs   []*router // child routers
		noFilter bool
		routeProcessor
	}

	existError struct {
		pos     string
		typ     string
		pattern string
	}
)

const (
	ErrConflictPathVar = errors.Err("There is a similar route pattern which use same wildcard" +
		" or catchall at the same position, " +
		"this means one of them will nerver be matched, " +
		"please check your routes")
)

func (e existError) Error() string {
	return fmt.Sprintf("%s: %s for this route: %s already exist", e.pos, e.typ, e.pattern)
}

// NewRouter create a new Router
func NewRouter() Router {
	rt := new(router)
	rt.noFilter = true

	return rt
}
Example #25
0
func TestSimpleEmail(t *testing.T) {
	tt := testing2.Wrap(t)
	se := &SimpleEmail{Err: errors.Err("Wrong email")}
	tt.Log(se.Validate("[email protected]"))
}
Example #26
0
package zerver

import (
	"encoding/base64"
	"io"
	"net/http"
	"net/url"
	"strings"

	"github.com/cosiner/gohper/errors"
	"github.com/cosiner/gohper/utils/attrs"
)

const (
	ErrNoResourceType = errors.Err("there is no this resource type on server")
)

type (
	// RequestWrapper wrap a request, then return another one and a flag specified
	// whether should close request.Body on request destroy, it should close
	// original request.Body if need
	RequestWrapper func(*http.Request, bool) (*http.Request, bool)

	Request interface {
		Wrap(RequestWrapper)

		ReqMethod() string
		URL() *url.URL
		GetHeader(name string) string
		RemoteAddr() string
		Authorization() (string, bool)
Example #27
0
package file

import (
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/cosiner/gohper/errors"
	"github.com/cosiner/gohper/io2"
)

const ErrDestIsFile = errors.Err("destination is a file")

// FileOpFunc accept a file descriptor, return an error or nil
type FileOpFunc func(*os.File) error

// Open file use given flag
func Open(fname string, flags int, fn FileOpFunc) error {
	fd, err := os.OpenFile(fname, flags, FilePerm)
	if err != nil {
		return err
	}

	if fn != nil {
		err = fn(fd)
	}
	if e := fd.Close(); e != nil && err == nil {
		err = e
	}
Example #28
0
package rand

import (
	"crypto/rand"
	"math/big"

	"github.com/cosiner/gohper/errors"
)

// Charset of characters to use for generating random strings
const (
	ALPHABET     = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	NUMERALS     = "0123456789"
	ALPHANUMERIC = NUMERALS + ALPHABET

	ErrNegativeNum  = errors.Err("Number cannot be negative")
	ErrEmptyCharset = errors.Err("Charset cannot be empty")
)

type (
	BytesFunc  func(n int, charset string) ([]byte, error)
	StringFunc func(n int, charset string) (string, error)
)

// B generate a random bytes in gived charset
var B BytesFunc = func(n int, charset string) ([]byte, error) {
	if n <= 0 || len(charset) == 0 {
		panic("negative number or empty charset")
	}

	result := make([]byte, n)
Example #29
0
package ast

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"reflect"

	"github.com/cosiner/gohper/errors"
	"github.com/cosiner/gohper/strings2"
)

const (
	// END cause whole parsing end
	END = errors.Err("parsing end")

	// TYPE_END cause single type's parsing end
	TYPE_END = errors.Err("type parsing end")
)

type Attrs struct {
	// Package name
	Package string

	// helpful for access single type, if don't know, don't use it
	Accessed bool

	// Common
	TypeName string
Example #30
0
import (
	"bufio"

	"net"

	"fmt"
	"github.com/clrpc/clrpc-go/errors"
	"github.com/clrpc/clrpc-go/protocol"
	"github.com/cosiner/gohper/encoding"
	errors2 "github.com/cosiner/gohper/errors"
	"github.com/cosiner/gohper/time2"
)

const (
	ErrServiceExists  = errors2.Err("service already registered")
	ErrInvalidService = errors2.Err("invalid service function")
	ErrHasNoParam     = errors2.Err("has no param")
)

type Params func(params ...interface{}) error
type Replies func(replies ...interface{}) error

type request struct {
	*Server
	r         *bufio.Reader
	nextParam bool
}

func (r *request) Params(params ...interface{}) error {
	var err error