utils

package module
v0.0.0-...-df044ae Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2020 License: BSD-2-Clause Imports: 27 Imported by: 41

Documentation

Overview

Used for print everything as json.Marshal Created by simplejia 9/2016

Index

Examples

Constants

View Source
const (
	// KeyBody request body内容会存在此key对应params参数里
	KeyBody = "_body_"
	// KeyHeader 公共头内容会存在此key对应params参数里
	KeyHeader = "_header_"
	// KeyResp resp body内容会存在此key对应params参数里
	KeyResp = "_resp_"
	// KeyTrace trace内容会存在此key对应params参数里
	KeyTrace = "_trace_"
	// KeyTimeout timeout flag会存在此key对应params参数里
	KeyTimeout = "_timeout_"
	// KeyTimeoutMutex timeout mutex会存在此key对应params参数里
	KeyTimeoutMutex = "_timeout_mutex_"
	// KeyTimeoutDone timeout done chan会存在此key对应params参数里
	KeyTimeoutDone = "_timeout_done_"
	// KeyTimeoutOccur timeout occur flag会存在此key对应params参数里
	KeyTimeoutOccur = "_timeout_occur_"
	// KeyCtxDone request context done value会存在此key对应params参数里
	KeyCtxDone = "_ctx_done_"
)
View Source
const (
	// PROD 正式环境
	PROD = "prod"
	// DEV 开发环境,一般用于本机测试
	DEV = "dev"
	// TEST 测试环境
	TEST = "test"
	// PRE 预发布环境
	PRE = "pre"
)

Variables

View Source
var (
	AsyncTaskChan = make(chan struct{}, 0)
)
View Source
var CodeMap = map[Code]string{
	CodeSrv:  "服务错误",
	CodePara: "参数错误",
}

CodeMap 定义返回码对应的描述

View Source
var GRACEFUL_ENV = "GRACEFUL=true"
View Source
var LocalIp = func() string {
	ifaces, err := net.Interfaces()
	if err != nil {
		log.Println("utils.LocalIp error:", err)
		return ""
	}
	for _, iface := range ifaces {
		if iface.Flags&net.FlagUp == 0 {
			continue
		}
		if iface.Flags&net.FlagLoopback != 0 {
			continue
		}
		addrs, err := iface.Addrs()
		if err != nil {
			log.Println("utils.LocalIp error:", err)
			return ""
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			if ip == nil || ip.IsLoopback() {
				continue
			}
			ip = ip.To4()
			if ip == nil {
				continue
			}
			if IsInnerIp(ip.String()) {
				return ip.String()
			}
		}
	}
	log.Println("utils.LocalIp failed!")
	return ""
}()

Functions

func AsyncTaskEnter

func AsyncTaskEnter()

func AsyncTaskExit

func AsyncTaskExit()

func AsyncTaskShutdown

func AsyncTaskShutdown(timeout time.Duration)

func Get

func Get(gpp *GPP) (body []byte, err error)

func GroupByNum

func GroupByNum(p interface{}, n int) (r interface{})

func GroupByPer

func GroupByPer(p interface{}, n int) (r interface{})

func Hash33

func Hash33(src string) int

func Iprint

func Iprint(a ...interface{}) string

func IprintD

func IprintD(a ...interface{})
Example
package main

import "time"

type P struct {
	I int
}

type C struct {
	P
	J string
	T time.Time
	M map[int]*P
}

func main() {
	var v interface{}
	IprintD(v)
	v = 1
	IprintD(v)
	v = "str"
	IprintD(v)
	v = &P{I: 1}
	IprintD(v)
	v = &C{P: P{I: 1}, J: "a", M: map[int]*P{1: &P{I: 2}}}
	IprintD(v)
	v = map[string]int{"a": 1}
	IprintD(v)
	v = map[int]int{1: 2}
	IprintD(v)
	v = map[interface{}]int{1: 2}
	IprintD(v)
	i := 1
	v = map[*int]int{&i: 2}
	IprintD(v)
	v = map[int]*C{1: &C{P: P{I: 1}, J: "a", M: map[int]*P{1: &P{I: 2}}}}
	IprintD(v)

}
Output:

null
1
"str"
{
  "I": 1
}
{
  "J": "a",
  "M": {
    "1": {
      "I": 2
    }
  },
  "P": {
    "I": 1
  },
  "T": "0001-01-01T00:00:00Z"
}
{
  "a": 1
}
{
  "1": 2
}
{
  "1": 2
}
{
  "1": 2
}
{
  "1": {
    "J": "a",
    "M": {
      "1": {
        "I": 2
      }
    },
    "P": {
      "I": 1
    },
    "T": "0001-01-01T00:00:00Z"
  }
}

func IsInnerIp

func IsInnerIp(src_ip string) bool

func ListenAndServe

func ListenAndServe(addr string, handler http.Handler) error

func ListenAndServeWithTimeout

func ListenAndServeWithTimeout(addr string, handler http.Handler, shutdownTime, startTime, timeout time.Duration) error

func NameWrap

func NameWrap(name string) (addr string, err error)

func Post

func Post(gpp *GPP) (body []byte, err error)

func PostForm

func PostForm(gpp *GPP) (body []byte, err error)

func RegisterIndex

func RegisterIndex(index Index)

func RemoveAnnotation

func RemoveAnnotation(src []byte) []byte

func RlimitNofile

func RlimitNofile() string

func Slice2Interface

func Slice2Interface(slice interface{}) (ret []interface{})

func TestPost

func TestPost(h http.HandlerFunc, params interface{}) (body []byte, err error)

func TraceMe

func TraceMe(trace *Trace, name string, a ...interface{}) func()

func Updates

func Updates(d interface{}, t UpdateType, props map[string]interface{})

Types

type Base

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

func (*Base) GetParam

func (base *Base) GetParam(key string) (value interface{}, ok bool)

func (*Base) ReadBody

func (base *Base) ReadBody(r *http.Request) (body []byte)

func (*Base) Reply

func (base *Base) Reply(w http.ResponseWriter, data interface{})

func (*Base) ReplyFail

func (base *Base) ReplyFail(w http.ResponseWriter, code Code)

func (*Base) ReplyFailWithMsg

func (base *Base) ReplyFailWithMsg(w http.ResponseWriter, code Code, msg string)

func (*Base) ReplyFailWithResult

func (base *Base) ReplyFailWithResult(w http.ResponseWriter, result *Resp)

func (*Base) ReplyOk

func (base *Base) ReplyOk(w http.ResponseWriter, data interface{})

func (*Base) ReplyRaw

func (base *Base) ReplyRaw(w http.ResponseWriter, data []byte)

func (*Base) SetParam

func (base *Base) SetParam(key string, value interface{})

type Code

type Code int

Code 用于定义返回码

const (
	CodeOk   Code = 1
	CodeSrv  Code = 2 // 服务错误
	CodePara Code = 3 // 参数错误
)

type CtxDoneType

type CtxDoneType string
const (
	CtxDone CtxDoneType = "done"
)

type GPP

type GPP struct {
	Uri            string
	Timeout        time.Duration
	ConnectTimeout time.Duration
	Proxy          string
	Headers        map[string]string
	HttpHeader     http.Header
	HttpHeaderRet  *http.Header
	StatusCodeRet  *int
	Params         interface{}
	Reader         io.Reader
	// contains filtered or unexported fields
}

type IBase

type IBase interface {
	SetParam(string, interface{})
	GetParam(string) (interface{}, bool)
	ReadBody(*http.Request) []byte
	ReplyRaw(http.ResponseWriter, []byte)
	Reply(http.ResponseWriter, interface{})
	ReplyOk(http.ResponseWriter, interface{})
	ReplyFail(http.ResponseWriter, Code)
	ReplyFailWithMsg(http.ResponseWriter, Code, string)
	ReplyFailWithResult(http.ResponseWriter, *Resp)
}

IBase 所有Controller必须实现此接口

type Index

type Index interface {
	UpdateIndex(d interface{}, t UpdateType, props map[string]interface{})
}

type Resp

type Resp struct {
	Ret  Code        `json:"ret"`
	Msg  string      `json:"msg,omitempty"`
	Data interface{} `json:"data,omitempty"`
}

Resp 用于定义返回数据格式(json)

type Server

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

func NewServer

func NewServer(addr string, handler http.Handler, shutdownTime, startTime, timeout time.Duration) *Server

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() (err error)

type Trace

type Trace struct {
	ID      string       `json:"id,omitempty"`
	Mid     int64        `json:"mid,omitempty"`
	SrvSrc  string       `json:"srv_src,omitempty"`
	SrvDst  string       `json:"srv_dst,omitempty"`
	NameSrc string       `json:"name_src,omitempty"`
	NameDst string       `json:"name_dst,omitempty"`
	Procs   []*TraceProc `json:"procs,omitempty"`
	Mu      sync.Mutex   `json:"-"`
}

Trace 用于定义trace信息

func GetTrace

func GetTrace(b IBase) *Trace

func (*Trace) Decode

func (trace *Trace) Decode(s string)

func (*Trace) Encode

func (trace *Trace) Encode() string

func (*Trace) String

func (trace *Trace) String() string

type TraceProc

type TraceProc struct {
	Name string        `json:"name,omitempty"`
	Dur  string        `json:"dur,omitempty"` // time.Duration stringer
	Args []interface{} `json:"args,omitempty"`
}

type UpdateType

type UpdateType int

UpdateType 表示类型

const (
	// ADD 代表insert和upsert
	ADD UpdateType = iota
	// DELETE 代表delete
	DELETE
	// UPDATE 代表update
	UPDATE
	// GET 代表get
	GET
)

Jump to

Keyboard shortcuts

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