short

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2020 License: Apache-2.0 Imports: 21 Imported by: 0

README

short

一个简单的go web框架,基于go原始库的http包,可实现中间件的添加。

提供的中间件有:

  • Method 判断请求方法
  • NoCache 设置无缓存
  • BasicAuth 验证BasicAuth
  • CORS 设置可跨域

提供了解析JSON请求和返回JSON响应的函数。

案例可参考:ShortDemo/server

提供了http客户端函数,可快速构建http请求代码。

案例可参考:ShortDemo/client

辅助功能

简单封装sqlx库的Statment和同步锁。案例可参考:ShortDemo/stmt

使用chan实现多协程的队列处理。案例可参考:ShortDemo/queue

使用chan实现线程安全的序列生成器。案例可参考:ShortDemo/serial

基于int64自定义类型TStamp实现json序列化时字符串转换。案例可参考:ShortDemo/servertstamp接口

Documentation

Index

Constants

View Source
const (
	CodeOK = iota
	CodeErr
)

Resp Code option values

View Source
const (
	// TimeLayout1 2006-01-02 15:04:05
	TimeLayout1 = "2006-01-02 15:04:05"
	// TimeLayout2 2006-01-02
	TimeLayout2 = "2006-01-02"
	// TimeLayout3 15:04:05
	TimeLayout3 = "15:04:05"
	// TimeLayout4 20060102150405
	TimeLayout4 = "20060102150405"
	// TimeLayout5 20060102
	TimeLayout5 = "20060102"
	// TimeLayout6 150405
	TimeLayout6 = "150405"
	// TimeLayout7 2006.01.02
	TimeLayout7 = "2006.01.02"
	// TimeLayout8 2006/01/02
	TimeLayout8 = "2006/01/02"
)

timestamp format layout

Variables

View Source
var DefaultConfig = &Config{
	Name: "config.short.json",
	Server: &ServerConfig{
		Addr:         ":8080",
		ReadTimeout:  5,
		WriteTimeout: 30,
		IdleTimeout:  3,
	},
	Client: &ClientConfig{
		Timeout:               15,
		KeepAlive:             30,
		ResponseHeaderTimeout: 30,
		ExpectContinueTimeout: 3,
		MaxIdleConns:          50,
		IdleConnTimeout:       60,
	},
}

DefaultConfig default configuration

Functions

func BindJSON

func BindJSON(r *http.Request, data interface{}) error

BindJSON bind json request

func CheckPath

func CheckPath(path string) string

CheckPath check path, make sure to has '/'

func CheckPattern

func CheckPattern(pattern string) string

CheckPattern check pattern, make sure to start with '/'

func CreateConfigFile

func CreateConfigFile(path string, c *Config)

CreateConfigFile create config file

func CreateFolder

func CreateFolder(path string) error

CreateFolder create folders according to path

func GetRealIP

func GetRealIP(req *http.Request) string

GetRealIP get real IP

func GzipJSON

func GzipJSON(w http.ResponseWriter, data interface{})

GzipJSON write json data with gzip

func JSON

func JSON(w http.ResponseWriter, data interface{})

JSON write json data

func JsonErr

func JsonErr(w http.ResponseWriter, err error)

JsonErr write resp err json

func JsonOK

func JsonOK(w http.ResponseWriter, data interface{})

JsonOK write resp ok json

func JsonResp

func JsonResp(w http.ResponseWriter, code int, res string)

JsonResp write resp json

func JsonWrong

func JsonWrong(w http.ResponseWriter, res string)

JsonWrong write resp wrong json

func LoadJSON

func LoadJSON(name string, data interface{}) error

LoadJSON load json to file

func LoadOrCreateJSON

func LoadOrCreateJSON(name string, data interface{}) error

LoadOrCreateJSON load json file, if not, create json file

func LogErr

func LogErr(err error, msg string)

LogErr print error in specific way

func MD5

func MD5(src string) []byte

MD5 get a string md5

func RandomString

func RandomString(n int) string

RandomString generate random string by length

func SaveJSON

func SaveJSON(name string, data interface{}) error

SaveJSON save json to file

func StrTime

func StrTime(timestamp int64, timeLayout string) string

StrTime convert timestamp to time string

func ToJsonStr

func ToJsonStr(data interface{}) string

ToJsonStr convert struct to json string

func Trace

func Trace(msg string) func()

Trace trace func execute time

func UUID

func UUID() string

UUID get uuid without '-'

func UnixTime

func UnixTime(timeStr, layout string) int64

UnixTime convert time string to timestamp

Types

type Client

type Client struct {
	*http.Client
}

Client contain http.Client, add some methods

func NewClient

func NewClient() *Client

NewClient new client with default config

func NewConfigClient

func NewConfigClient(c *ClientConfig) *Client

NewClient new client with custom config

func (*Client) GetJSON

func (c *Client) GetJSON(url string, data interface{}) (err error)

GetJSON get request, json response parse to struct

func (*Client) GetJSONAuth

func (c *Client) GetJSONAuth(url, un, pa string, data interface{}) (err error)

GetJSONAuth get request with basic auth, json response parse to struct

func (*Client) PostFormJSON

func (c *Client) PostFormJSON(url string, vals url.Values, data interface{}) (err error)

PostFormJSON json post form request, json response parse to struct

func (*Client) PostFormJSONAuth

func (c *Client) PostFormJSONAuth(url, un, pa string, vals url.Values, data interface{}) (err error)

PostFormJSONAuth json post form request with basic auth, json response parse to struct

func (*Client) PostJSON

func (c *Client) PostJSON(url string, src, data interface{}) (err error)

PostJSON json post request, json response parse to struct

func (*Client) PostJSONAuth

func (c *Client) PostJSONAuth(url, un, pa string, src, data interface{}) (err error)

PostJSONAuth json post request with basic auth, json response parse to struct

type ClientConfig

type ClientConfig struct {
	Timeout               time.Duration `json:"timeout"`
	KeepAlive             time.Duration `json:"keepAlive"`
	ResponseHeaderTimeout time.Duration `json:"responseHeaderTimeout"`
	ExpectContinueTimeout time.Duration `json:"expectContinueTimeout"`
	MaxIdleConns          int           `json:"maxIdleConns"`
	IdleConnTimeout       time.Duration `json:"idleConnTimeout"`
}

ClientConfig client configuration

type Config

type Config struct {
	Name   string        `json:"name"`
	Server *ServerConfig `json:"server"`
	Client *ClientConfig `json:"client"`
}

Config - configuration

type Dealer

type Dealer func(http.ResponseWriter, *http.Request, Dealers, int)

Dealer middleware function

func BasicAuth

func BasicAuth(username, password string) Dealer

BasicAuth middleware confirm basic authorization

func CORS

func CORS(acceptedOrigin, AcceptedMethods, AcceptedHeaders, MaxAge string) Dealer

CORS returns a Middlewarte that handle CORS

func Method

func Method(m string) Dealer

Method middleware the request method is equal to parameter m

func NoCache

func NoCache() Dealer

NoCache middleware set header cache control no cache

func TraceH

func TraceH() Dealer

TraceH trace handler execute time

type Dealers

type Dealers []Dealer

Dealers middleware function list, bool return if continue

func (Dealers) ServeHTTP

func (ds Dealers) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implement http.Handler interface and reverse to execute function

type HttpHandler

type HttpHandler struct {
	Pattern    string
	Handler    func(w http.ResponseWriter, r *http.Request)
	Middleware Dealers
}

HttpHandler http handler

func GETHandler

func GETHandler(p string, h func(w http.ResponseWriter, r *http.Request), m ...Dealer) *HttpHandler

GETHandler new a http method GET HttpHandler

func NewHandler

func NewHandler(p string, h func(w http.ResponseWriter, r *http.Request), m ...Dealer) *HttpHandler

NewHandler new a HttpHandler

func POSTHandler

func POSTHandler(p string, h func(w http.ResponseWriter, r *http.Request), m ...Dealer) *HttpHandler

POSTHandler new a http method POST HttpHandler

type Queue

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

Queue 队列

func NewQueue

func NewQueue(size int) *Queue

NewQueue 新建队列

func (*Queue) Start

func (q *Queue) Start(num int, deal func(interface{}))

Start 启动队列

func (*Queue) Stop

func (q *Queue) Stop()

Stop 停止队列

func (*Queue) Submit

func (q *Queue) Submit(item interface{})

Submit 非阻塞提交队列

func (*Queue) Submit2

func (q *Queue) Submit2(item interface{})

Submit2 阻塞提交队列

type Resp

type Resp struct {
	Code   int         `json:"code"`
	Result string      `json:"result"`
	Data   interface{} `json:"data,omitempty"`
}

Resp http request response

func NewResp

func NewResp(code int, result string, data interface{}) *Resp

NewResp new response

func RespErr

func RespErr(err error) *Resp

RespErr create error response

func RespMsg

func RespMsg(code int, result string) *Resp

RespMsg create msg response

func RespOK

func RespOK(data interface{}) *Resp

RespOK create ok response

type Serial

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

Serial 序列生成器

func NewSerial

func NewSerial(reset int) *Serial

NewSerial 创建Serial

func (*Serial) Get

func (s *Serial) Get() int

Get 获取序列值

func (*Serial) Reset

func (s *Serial) Reset(c int)

Reset 重置计数

func (*Serial) Start

func (s *Serial) Start()

Start 开始序列生成器

type Server

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

Server short server

func NewConfigServer

func NewConfigServer(c *ServerConfig) *Server

NewConfigServer new http server with custom config

func NewServer

func NewServer() *Server

NewServer new http server with default config

func (*Server) Addr

func (s *Server) Addr(addr string) *Server

Addr set sever addr

func (*Server) Exit

func (s *Server) Exit()

Exit server exit

func (*Server) FileServer

func (s *Server) FileServer(pattern, dir string) *Server

FileServer handle file server

func (*Server) Handlers

func (s *Server) Handlers(list []*HttpHandler) *Server

Handlers set http handlers

func (*Server) OnInit

func (s *Server) OnInit(init func()) *Server

OnInit on init server

func (*Server) OnStop

func (s *Server) OnStop(stop func()) *Server

OnStop on stop server

func (*Server) Run

func (s *Server) Run()

Run run server

type ServerConfig

type ServerConfig struct {
	Addr         string        `bson:"addr"`
	ReadTimeout  time.Duration `bson:"readTimeout"`
	WriteTimeout time.Duration `bson:"writeTimeout"`
	IdleTimeout  time.Duration `bson:"idleTimeout"`
}

ServerConfig server configuration

type StmtDB

type StmtDB struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

StmtDB package sqlx.DB with sqlx.Stmt, sqlx.NamedStmt map, and a sync.Mutex

func NewStmtDB

func NewStmtDB(db *sqlx.DB) *StmtDB

NewStmtDB new StmtDB

func (*StmtDB) CloseDB

func (s *StmtDB) CloseDB()

CloseDB close StmtDB

func (*StmtDB) DeferLock

func (s *StmtDB) DeferLock() func()

DeferLock execute mutex Lock() and return mutex.Unlock for defer example: defer s.DeferLock()()

func (*StmtDB) Lock

func (s *StmtDB) Lock()

Lock use mutex Lock()

func (*StmtDB) NStmt

func (s *StmtDB) NStmt(sqlStr string) (stmt *sqlx.NamedStmt, err error)

NStmt get a sqlx.NamedStmt with lazy PrepareNamed

func (*StmtDB) Stmt

func (s *StmtDB) Stmt(sqlStr string) (stmt *sqlx.Stmt, err error)

Stmt get a sqlx.Stmt with lazy Preparex

func (*StmtDB) Unlock

func (s *StmtDB) Unlock()

Unlock use mutex Unlock()

type TStamp

type TStamp int64

TStamp custom type for int64

func NewStampTime

func NewStampTime(te time.Time) TStamp

NewStampTime new TStamp by time.Time

func NewStrStamp

func NewStrStamp(ts string) TStamp

NewStrStamp new TStamp by time string

func NewTimeStamp

func NewTimeStamp(ts int64) TStamp

NewTimeStamp new TStamp

func (TStamp) Format

func (t TStamp) Format(layout string) string

Format get format time

func (TStamp) GoString

func (t TStamp) GoString() string

GoString implement GoStringer

func (TStamp) Int64

func (t TStamp) Int64() int64

Int64 get int64 value

func (TStamp) MarshalJSON

func (t TStamp) MarshalJSON() (buf []byte, err error)

MarshalJSON implement Marshaler

func (TStamp) String

func (t TStamp) String() string

String implement Stringer

func (TStamp) Time

func (t TStamp) Time() time.Time

Time get time.Time

func (*TStamp) UnmarshalJSON

func (t *TStamp) UnmarshalJSON(b []byte) error

UnmarshalJSON implement Unmarshaler

type XmlMap

type XmlMap map[string]string

XmlMap xml转换map

func (XmlMap) MarshalXML

func (m XmlMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals the map to XML

func (*XmlMap) UnmarshalXML

func (m *XmlMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals the XML into a map of string to strings

Jump to

Keyboard shortcuts

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