add golint check and fix all golints

This commit is contained in:
astaxie 2017-04-30 22:41:23 +08:00
parent ea3d0690cf
commit a91e2e9950
20 changed files with 271 additions and 175 deletions

View File

@ -36,6 +36,7 @@ install:
- go get -u honnef.co/go/tools/cmd/gosimple - go get -u honnef.co/go/tools/cmd/gosimple
- go get -u github.com/mdempsky/unconvert - go get -u github.com/mdempsky/unconvert
- go get -u github.com/gordonklaus/ineffassign - go get -u github.com/gordonklaus/ineffassign
- go get -u github.com/golang/lint/golint
before_script: before_script:
- psql --version - psql --version
- sh -c "if [ '$ORM_DRIVER' = 'postgres' ]; then psql -c 'create database orm_test;' -U postgres; fi" - sh -c "if [ '$ORM_DRIVER' = 'postgres' ]; then psql -c 'create database orm_test;' -U postgres; fi"
@ -54,5 +55,6 @@ script:
- unconvert $(go list ./... | grep -v /vendor/) - unconvert $(go list ./... | grep -v /vendor/)
- ineffassign . - ineffassign .
- find . ! \( -path './vendor' -prune \) -type f -name '*.go' -print0 | xargs -0 gofmt -l -s - find . ! \( -path './vendor' -prune \) -type f -name '*.go' -print0 | xargs -0 gofmt -l -s
- golint ./...
addons: addons:
postgresql: "9.4" postgresql: "9.4"

2
config/env/env.go vendored
View File

@ -12,6 +12,8 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// Package env is used to parse environment.
package env package env
import ( import (

View File

@ -39,6 +39,7 @@ var (
getMethodOnly bool getMethodOnly bool
) )
// InitGzip init the gzipcompress
func InitGzip(minLength, compressLevel int, methods []string) { func InitGzip(minLength, compressLevel int, methods []string) {
if minLength >= 0 { if minLength >= 0 {
gzipMinLength = minLength gzipMinLength = minLength

View File

@ -291,7 +291,7 @@ func (srv *Server) fork() (err error) {
// RegisterSignalHook registers a function to be run PreSignal or PostSignal for a given signal. // RegisterSignalHook registers a function to be run PreSignal or PostSignal for a given signal.
func (srv *Server) RegisterSignalHook(ppFlag int, sig os.Signal, f func()) (err error) { func (srv *Server) RegisterSignalHook(ppFlag int, sig os.Signal, f func()) (err error) {
if ppFlag != PreSignal && ppFlag != PostSignal { if ppFlag != PreSignal && ppFlag != PostSignal {
err = fmt.Errorf("Invalid ppFlag argument. Must be either grace.PreSignal or grace.PostSignal.") err = fmt.Errorf("Invalid ppFlag argument. Must be either grace.PreSignal or grace.PostSignal")
return return
} }
for _, s := range hookableSignals { for _, s := range hookableSignals {
@ -300,6 +300,6 @@ func (srv *Server) RegisterSignalHook(ppFlag int, sig os.Signal, f func()) (err
return return
} }
} }
err = fmt.Errorf("Signal '%v' is not supported.", sig) err = fmt.Errorf("Signal '%v' is not supported", sig)
return return
} }

View File

@ -55,9 +55,9 @@ func registerSession() error {
conf.ProviderConfig = filepath.ToSlash(BConfig.WebConfig.Session.SessionProviderConfig) conf.ProviderConfig = filepath.ToSlash(BConfig.WebConfig.Session.SessionProviderConfig)
conf.DisableHTTPOnly = BConfig.WebConfig.Session.SessionDisableHTTPOnly conf.DisableHTTPOnly = BConfig.WebConfig.Session.SessionDisableHTTPOnly
conf.Domain = BConfig.WebConfig.Session.SessionDomain conf.Domain = BConfig.WebConfig.Session.SessionDomain
conf.EnableSidInHttpHeader = BConfig.WebConfig.Session.SessionEnableSidInHTTPHeader conf.EnableSidInHTTPHeader = BConfig.WebConfig.Session.SessionEnableSidInHTTPHeader
conf.SessionNameInHttpHeader = BConfig.WebConfig.Session.SessionNameInHTTPHeader conf.SessionNameInHTTPHeader = BConfig.WebConfig.Session.SessionNameInHTTPHeader
conf.EnableSidInUrlQuery = BConfig.WebConfig.Session.SessionEnableSidInURLQuery conf.EnableSidInURLQuery = BConfig.WebConfig.Session.SessionEnableSidInURLQuery
} else { } else {
if err = json.Unmarshal([]byte(sessionConfig), conf); err != nil { if err = json.Unmarshal([]byte(sessionConfig), conf); err != nil {
return err return err

View File

@ -11,11 +11,14 @@ import (
) )
const ( const (
CacheSize int = 64 // CacheSize set the flush size
CacheSize int = 64
// Delimiter define the topic delimiter
Delimiter string = "##" Delimiter string = "##"
) )
type AliLSConfig struct { // Config is the Config for Ali Log
type Config struct {
Project string `json:"project"` Project string `json:"project"`
Endpoint string `json:"endpoint"` Endpoint string `json:"endpoint"`
KeyID string `json:"key_id"` KeyID string `json:"key_id"`
@ -35,18 +38,17 @@ type aliLSWriter struct {
withMap bool withMap bool
groupMap map[string]*LogGroup groupMap map[string]*LogGroup
lock *sync.Mutex lock *sync.Mutex
AliLSConfig Config
} }
// 创建提供Logger接口的日志服务 // NewAliLS create a new Logger
func NewAliLS() logs.Logger { func NewAliLS() logs.Logger {
alils := new(aliLSWriter) alils := new(aliLSWriter)
alils.Level = logs.LevelTrace alils.Level = logs.LevelTrace
return alils return alils
} }
// 读取配置 // Init parse config and init struct
// 初始化必要的数据结构
func (c *aliLSWriter) Init(jsonConfig string) (err error) { func (c *aliLSWriter) Init(jsonConfig string) (err error) {
json.Unmarshal([]byte(jsonConfig), c) json.Unmarshal([]byte(jsonConfig), c)
@ -55,28 +57,26 @@ func (c *aliLSWriter) Init(jsonConfig string) (err error) {
c.FlushWhen = CacheSize c.FlushWhen = CacheSize
} }
// 初始化Project
prj := &LogProject{ prj := &LogProject{
Name: c.Project, Name: c.Project,
Endpoint: c.Endpoint, Endpoint: c.Endpoint,
AccessKeyId: c.KeyID, AccessKeyID: c.KeyID,
AccessKeySecret: c.KeySecret, AccessKeySecret: c.KeySecret,
} }
// 获取logstore
c.store, err = prj.GetLogStore(c.LogStore) c.store, err = prj.GetLogStore(c.LogStore)
if err != nil { if err != nil {
return err return err
} }
// 创建默认Log Group // Create default Log Group
c.group = append(c.group, &LogGroup{ c.group = append(c.group, &LogGroup{
Topic: proto.String(""), Topic: proto.String(""),
Source: proto.String(c.Source), Source: proto.String(c.Source),
Logs: make([]*Log, 0, c.FlushWhen), Logs: make([]*Log, 0, c.FlushWhen),
}) })
// 创建其它Log Group // Create other Log Group
c.groupMap = make(map[string]*LogGroup) c.groupMap = make(map[string]*LogGroup)
for _, topic := range c.Topics { for _, topic := range c.Topics {
@ -114,7 +114,7 @@ func (c *aliLSWriter) WriteMsg(when time.Time, msg string, level int) (err error
var lg *LogGroup var lg *LogGroup
if c.withMap { if c.withMap {
// 解析出Topic并匹配LogGroup // TopicLogGroup
strs := strings.SplitN(msg, Delimiter, 2) strs := strings.SplitN(msg, Delimiter, 2)
if len(strs) == 2 { if len(strs) == 2 {
pos := strings.LastIndex(strs[0], " ") pos := strings.LastIndex(strs[0], " ")
@ -123,7 +123,7 @@ func (c *aliLSWriter) WriteMsg(when time.Time, msg string, level int) (err error
lg = c.groupMap[topic] lg = c.groupMap[topic]
} }
// 默认发到空Topic // send to empty Topic
if lg == nil { if lg == nil {
content = msg content = msg
lg = c.group[0] lg = c.group[0]
@ -133,15 +133,14 @@ func (c *aliLSWriter) WriteMsg(when time.Time, msg string, level int) (err error
lg = c.group[0] lg = c.group[0]
} }
// 生成日志 c1 := &LogContent{
c1 := &Log_Content{
Key: proto.String("msg"), Key: proto.String("msg"),
Value: proto.String(content), Value: proto.String(content),
} }
l := &Log{ l := &Log{
Time: proto.Uint32(uint32(when.Unix())), // 填写日志时间 Time: proto.Uint32(uint32(when.Unix())),
Contents: []*Log_Content{ Contents: []*LogContent{
c1, c1,
}, },
} }
@ -150,7 +149,6 @@ func (c *aliLSWriter) WriteMsg(when time.Time, msg string, level int) (err error
lg.Logs = append(lg.Logs, l) lg.Logs = append(lg.Logs, l)
c.lock.Unlock() c.lock.Unlock()
// 满足条件则Flush
if len(lg.Logs) >= c.FlushWhen { if len(lg.Logs) >= c.FlushWhen {
c.flush(lg) c.flush(lg)
} }
@ -161,7 +159,7 @@ func (c *aliLSWriter) WriteMsg(when time.Time, msg string, level int) (err error
// Flush implementing method. empty. // Flush implementing method. empty.
func (c *aliLSWriter) Flush() { func (c *aliLSWriter) Flush() {
// flush所有group // flush all group
for _, lg := range c.group { for _, lg := range c.group {
c.flush(lg) c.flush(lg)
} }
@ -175,9 +173,6 @@ func (c *aliLSWriter) flush(lg *LogGroup) {
c.lock.Lock() c.lock.Lock()
defer c.lock.Unlock() defer c.lock.Unlock()
// 把以上的LogGroup推送到SLS服务器
// SLS服务器会根据该logstore的shard个数自动进行负载均衡。
err := c.store.PutLogs(lg) err := c.store.PutLogs(lg)
if err != nil { if err != nil {
return return

View File

@ -1,30 +1,43 @@
package alils package alils
import "github.com/gogo/protobuf/proto" import (
import "fmt" "fmt"
import "math" "io"
"math"
// discarding unused import gogoproto "." "github.com/gogo/protobuf/proto"
github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" )
import "io"
// Reference imports to suppress errors if they are not otherwise used. // Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal var _ = proto.Marshal
var _ = fmt.Errorf var _ = fmt.Errorf
var _ = math.Inf var _ = math.Inf
var (
// ErrInvalidLengthLog invalid proto
ErrInvalidLengthLog = fmt.Errorf("proto: negative length found during unmarshaling")
// ErrIntOverflowLog overflow
ErrIntOverflowLog = fmt.Errorf("proto: integer overflow")
)
// Log define the proto Log
type Log struct { type Log struct {
Time *uint32 `protobuf:"varint,1,req,name=Time" json:"Time,omitempty"` Time *uint32 `protobuf:"varint,1,req,name=Time" json:"Time,omitempty"`
Contents []*Log_Content `protobuf:"bytes,2,rep,name=Contents" json:"Contents,omitempty"` Contents []*LogContent `protobuf:"bytes,2,rep,name=Contents" json:"Contents,omitempty"`
XXX_unrecognized []byte `json:"-"` XXXUnrecognized []byte `json:"-"`
} }
func (m *Log) Reset() { *m = Log{} } // Reset the Log
func (m *Log) String() string { return proto.CompactTextString(m) } func (m *Log) Reset() { *m = Log{} }
func (*Log) ProtoMessage() {}
// String return the Compact Log
func (m *Log) String() string { return proto.CompactTextString(m) }
// ProtoMessage not implemented
func (*Log) ProtoMessage() {}
// GetTime return the Log's Time
func (m *Log) GetTime() uint32 { func (m *Log) GetTime() uint32 {
if m != nil && m.Time != nil { if m != nil && m.Time != nil {
return *m.Time return *m.Time
@ -32,49 +45,65 @@ func (m *Log) GetTime() uint32 {
return 0 return 0
} }
func (m *Log) GetContents() []*Log_Content { // GetContents return the Log's Contents
func (m *Log) GetContents() []*LogContent {
if m != nil { if m != nil {
return m.Contents return m.Contents
} }
return nil return nil
} }
type Log_Content struct { // LogContent define the Log content struct
Key *string `protobuf:"bytes,1,req,name=Key" json:"Key,omitempty"` type LogContent struct {
Value *string `protobuf:"bytes,2,req,name=Value" json:"Value,omitempty"` Key *string `protobuf:"bytes,1,req,name=Key" json:"Key,omitempty"`
XXX_unrecognized []byte `json:"-"` Value *string `protobuf:"bytes,2,req,name=Value" json:"Value,omitempty"`
XXXUnrecognized []byte `json:"-"`
} }
func (m *Log_Content) Reset() { *m = Log_Content{} } // Reset LogContent
func (m *Log_Content) String() string { return proto.CompactTextString(m) } func (m *LogContent) Reset() { *m = LogContent{} }
func (*Log_Content) ProtoMessage() {}
func (m *Log_Content) GetKey() string { // String return the compact text
func (m *LogContent) String() string { return proto.CompactTextString(m) }
// ProtoMessage not implemented
func (*LogContent) ProtoMessage() {}
// GetKey return the Key
func (m *LogContent) GetKey() string {
if m != nil && m.Key != nil { if m != nil && m.Key != nil {
return *m.Key return *m.Key
} }
return "" return ""
} }
func (m *Log_Content) GetValue() string { // GetValue return the Value
func (m *LogContent) GetValue() string {
if m != nil && m.Value != nil { if m != nil && m.Value != nil {
return *m.Value return *m.Value
} }
return "" return ""
} }
// LogGroup define the logs struct
type LogGroup struct { type LogGroup struct {
Logs []*Log `protobuf:"bytes,1,rep,name=Logs" json:"Logs,omitempty"` Logs []*Log `protobuf:"bytes,1,rep,name=Logs" json:"Logs,omitempty"`
Reserved *string `protobuf:"bytes,2,opt,name=Reserved" json:"Reserved,omitempty"` Reserved *string `protobuf:"bytes,2,opt,name=Reserved" json:"Reserved,omitempty"`
Topic *string `protobuf:"bytes,3,opt,name=Topic" json:"Topic,omitempty"` Topic *string `protobuf:"bytes,3,opt,name=Topic" json:"Topic,omitempty"`
Source *string `protobuf:"bytes,4,opt,name=Source" json:"Source,omitempty"` Source *string `protobuf:"bytes,4,opt,name=Source" json:"Source,omitempty"`
XXX_unrecognized []byte `json:"-"` XXXUnrecognized []byte `json:"-"`
} }
func (m *LogGroup) Reset() { *m = LogGroup{} } // Reset LogGroup
func (m *LogGroup) String() string { return proto.CompactTextString(m) } func (m *LogGroup) Reset() { *m = LogGroup{} }
func (*LogGroup) ProtoMessage() {}
// String return the compact text
func (m *LogGroup) String() string { return proto.CompactTextString(m) }
// ProtoMessage not implemented
func (*LogGroup) ProtoMessage() {}
// GetLogs return the loggroup logs
func (m *LogGroup) GetLogs() []*Log { func (m *LogGroup) GetLogs() []*Log {
if m != nil { if m != nil {
return m.Logs return m.Logs
@ -82,6 +111,7 @@ func (m *LogGroup) GetLogs() []*Log {
return nil return nil
} }
// GetReserved return Reserved
func (m *LogGroup) GetReserved() string { func (m *LogGroup) GetReserved() string {
if m != nil && m.Reserved != nil { if m != nil && m.Reserved != nil {
return *m.Reserved return *m.Reserved
@ -89,6 +119,7 @@ func (m *LogGroup) GetReserved() string {
return "" return ""
} }
// GetTopic return Topic
func (m *LogGroup) GetTopic() string { func (m *LogGroup) GetTopic() string {
if m != nil && m.Topic != nil { if m != nil && m.Topic != nil {
return *m.Topic return *m.Topic
@ -96,6 +127,7 @@ func (m *LogGroup) GetTopic() string {
return "" return ""
} }
// GetSource return Source
func (m *LogGroup) GetSource() string { func (m *LogGroup) GetSource() string {
if m != nil && m.Source != nil { if m != nil && m.Source != nil {
return *m.Source return *m.Source
@ -103,15 +135,22 @@ func (m *LogGroup) GetSource() string {
return "" return ""
} }
// LogGroupList define the LogGroups
type LogGroupList struct { type LogGroupList struct {
LogGroups []*LogGroup `protobuf:"bytes,1,rep,name=logGroups" json:"logGroups,omitempty"` LogGroups []*LogGroup `protobuf:"bytes,1,rep,name=logGroups" json:"logGroups,omitempty"`
XXX_unrecognized []byte `json:"-"` XXXUnrecognized []byte `json:"-"`
} }
func (m *LogGroupList) Reset() { *m = LogGroupList{} } // Reset LogGroupList
func (m *LogGroupList) String() string { return proto.CompactTextString(m) } func (m *LogGroupList) Reset() { *m = LogGroupList{} }
func (*LogGroupList) ProtoMessage() {}
// String return compact text
func (m *LogGroupList) String() string { return proto.CompactTextString(m) }
// ProtoMessage not implemented
func (*LogGroupList) ProtoMessage() {}
// GetLogGroups return the LogGroups
func (m *LogGroupList) GetLogGroups() []*LogGroup { func (m *LogGroupList) GetLogGroups() []*LogGroup {
if m != nil { if m != nil {
return m.LogGroups return m.LogGroups
@ -119,6 +158,7 @@ func (m *LogGroupList) GetLogGroups() []*LogGroup {
return nil return nil
} }
// Marshal the logs to byte slice
func (m *Log) Marshal() (data []byte, err error) { func (m *Log) Marshal() (data []byte, err error) {
size := m.Size() size := m.Size()
data = make([]byte, size) data = make([]byte, size)
@ -129,6 +169,7 @@ func (m *Log) Marshal() (data []byte, err error) {
return data[:n], nil return data[:n], nil
} }
// MarshalTo data
func (m *Log) MarshalTo(data []byte) (int, error) { func (m *Log) MarshalTo(data []byte) (int, error) {
var i int var i int
_ = i _ = i
@ -136,11 +177,10 @@ func (m *Log) MarshalTo(data []byte) (int, error) {
_ = l _ = l
if m.Time == nil { if m.Time == nil {
return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("Time") return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("Time")
} else {
data[i] = 0x8
i++
i = encodeVarintLog(data, i, uint64(*m.Time))
} }
data[i] = 0x8
i++
i = encodeVarintLog(data, i, uint64(*m.Time))
if len(m.Contents) > 0 { if len(m.Contents) > 0 {
for _, msg := range m.Contents { for _, msg := range m.Contents {
data[i] = 0x12 data[i] = 0x12
@ -153,13 +193,14 @@ func (m *Log) MarshalTo(data []byte) (int, error) {
i += n i += n
} }
} }
if m.XXX_unrecognized != nil { if m.XXXUnrecognized != nil {
i += copy(data[i:], m.XXX_unrecognized) i += copy(data[i:], m.XXXUnrecognized)
} }
return i, nil return i, nil
} }
func (m *Log_Content) Marshal() (data []byte, err error) { // Marshal LogContent
func (m *LogContent) Marshal() (data []byte, err error) {
size := m.Size() size := m.Size()
data = make([]byte, size) data = make([]byte, size)
n, err := m.MarshalTo(data) n, err := m.MarshalTo(data)
@ -169,33 +210,34 @@ func (m *Log_Content) Marshal() (data []byte, err error) {
return data[:n], nil return data[:n], nil
} }
func (m *Log_Content) MarshalTo(data []byte) (int, error) { // MarshalTo logcontent to data
func (m *LogContent) MarshalTo(data []byte) (int, error) {
var i int var i int
_ = i _ = i
var l int var l int
_ = l _ = l
if m.Key == nil { if m.Key == nil {
return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("Key") return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("Key")
} else {
data[i] = 0xa
i++
i = encodeVarintLog(data, i, uint64(len(*m.Key)))
i += copy(data[i:], *m.Key)
} }
data[i] = 0xa
i++
i = encodeVarintLog(data, i, uint64(len(*m.Key)))
i += copy(data[i:], *m.Key)
if m.Value == nil { if m.Value == nil {
return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("Value") return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("Value")
} else {
data[i] = 0x12
i++
i = encodeVarintLog(data, i, uint64(len(*m.Value)))
i += copy(data[i:], *m.Value)
} }
if m.XXX_unrecognized != nil { data[i] = 0x12
i += copy(data[i:], m.XXX_unrecognized) i++
i = encodeVarintLog(data, i, uint64(len(*m.Value)))
i += copy(data[i:], *m.Value)
if m.XXXUnrecognized != nil {
i += copy(data[i:], m.XXXUnrecognized)
} }
return i, nil return i, nil
} }
// Marshal LogGroup
func (m *LogGroup) Marshal() (data []byte, err error) { func (m *LogGroup) Marshal() (data []byte, err error) {
size := m.Size() size := m.Size()
data = make([]byte, size) data = make([]byte, size)
@ -206,6 +248,7 @@ func (m *LogGroup) Marshal() (data []byte, err error) {
return data[:n], nil return data[:n], nil
} }
// MarshalTo LogGroup to data
func (m *LogGroup) MarshalTo(data []byte) (int, error) { func (m *LogGroup) MarshalTo(data []byte) (int, error) {
var i int var i int
_ = i _ = i
@ -241,12 +284,13 @@ func (m *LogGroup) MarshalTo(data []byte) (int, error) {
i = encodeVarintLog(data, i, uint64(len(*m.Source))) i = encodeVarintLog(data, i, uint64(len(*m.Source)))
i += copy(data[i:], *m.Source) i += copy(data[i:], *m.Source)
} }
if m.XXX_unrecognized != nil { if m.XXXUnrecognized != nil {
i += copy(data[i:], m.XXX_unrecognized) i += copy(data[i:], m.XXXUnrecognized)
} }
return i, nil return i, nil
} }
// Marshal LogGroupList
func (m *LogGroupList) Marshal() (data []byte, err error) { func (m *LogGroupList) Marshal() (data []byte, err error) {
size := m.Size() size := m.Size()
data = make([]byte, size) data = make([]byte, size)
@ -257,6 +301,7 @@ func (m *LogGroupList) Marshal() (data []byte, err error) {
return data[:n], nil return data[:n], nil
} }
// MarshalTo LogGroupList to data
func (m *LogGroupList) MarshalTo(data []byte) (int, error) { func (m *LogGroupList) MarshalTo(data []byte) (int, error) {
var i int var i int
_ = i _ = i
@ -274,8 +319,8 @@ func (m *LogGroupList) MarshalTo(data []byte) (int, error) {
i += n i += n
} }
} }
if m.XXX_unrecognized != nil { if m.XXXUnrecognized != nil {
i += copy(data[i:], m.XXX_unrecognized) i += copy(data[i:], m.XXXUnrecognized)
} }
return i, nil return i, nil
} }
@ -307,6 +352,8 @@ func encodeVarintLog(data []byte, offset int, v uint64) int {
data[offset] = uint8(v) data[offset] = uint8(v)
return offset + 1 return offset + 1
} }
// Size return the log's size
func (m *Log) Size() (n int) { func (m *Log) Size() (n int) {
var l int var l int
_ = l _ = l
@ -319,13 +366,14 @@ func (m *Log) Size() (n int) {
n += 1 + l + sovLog(uint64(l)) n += 1 + l + sovLog(uint64(l))
} }
} }
if m.XXX_unrecognized != nil { if m.XXXUnrecognized != nil {
n += len(m.XXX_unrecognized) n += len(m.XXXUnrecognized)
} }
return n return n
} }
func (m *Log_Content) Size() (n int) { // Size return LogContent size based on Key and Value
func (m *LogContent) Size() (n int) {
var l int var l int
_ = l _ = l
if m.Key != nil { if m.Key != nil {
@ -336,12 +384,13 @@ func (m *Log_Content) Size() (n int) {
l = len(*m.Value) l = len(*m.Value)
n += 1 + l + sovLog(uint64(l)) n += 1 + l + sovLog(uint64(l))
} }
if m.XXX_unrecognized != nil { if m.XXXUnrecognized != nil {
n += len(m.XXX_unrecognized) n += len(m.XXXUnrecognized)
} }
return n return n
} }
// Size return LogGroup size based on Logs
func (m *LogGroup) Size() (n int) { func (m *LogGroup) Size() (n int) {
var l int var l int
_ = l _ = l
@ -363,12 +412,13 @@ func (m *LogGroup) Size() (n int) {
l = len(*m.Source) l = len(*m.Source)
n += 1 + l + sovLog(uint64(l)) n += 1 + l + sovLog(uint64(l))
} }
if m.XXX_unrecognized != nil { if m.XXXUnrecognized != nil {
n += len(m.XXX_unrecognized) n += len(m.XXXUnrecognized)
} }
return n return n
} }
// Size return LogGroupList size
func (m *LogGroupList) Size() (n int) { func (m *LogGroupList) Size() (n int) {
var l int var l int
_ = l _ = l
@ -378,8 +428,8 @@ func (m *LogGroupList) Size() (n int) {
n += 1 + l + sovLog(uint64(l)) n += 1 + l + sovLog(uint64(l))
} }
} }
if m.XXX_unrecognized != nil { if m.XXXUnrecognized != nil {
n += len(m.XXX_unrecognized) n += len(m.XXXUnrecognized)
} }
return n return n
} }
@ -397,6 +447,8 @@ func sovLog(x uint64) (n int) {
func sozLog(x uint64) (n int) { func sozLog(x uint64) (n int) {
return sovLog((x << 1) ^ (x >> 63)) return sovLog((x << 1) ^ (x >> 63))
} }
// Unmarshal data to log
func (m *Log) Unmarshal(data []byte) error { func (m *Log) Unmarshal(data []byte) error {
var hasFields [1]uint64 var hasFields [1]uint64
l := len(data) l := len(data)
@ -474,7 +526,7 @@ func (m *Log) Unmarshal(data []byte) error {
if postIndex > l { if postIndex > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
m.Contents = append(m.Contents, &Log_Content{}) m.Contents = append(m.Contents, &LogContent{})
if err := m.Contents[len(m.Contents)-1].Unmarshal(data[iNdEx:postIndex]); err != nil { if err := m.Contents[len(m.Contents)-1].Unmarshal(data[iNdEx:postIndex]); err != nil {
return err return err
} }
@ -491,7 +543,7 @@ func (m *Log) Unmarshal(data []byte) error {
if (iNdEx + skippy) > l { if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
m.XXX_unrecognized = append(m.XXX_unrecognized, data[iNdEx:iNdEx+skippy]...) m.XXXUnrecognized = append(m.XXXUnrecognized, data[iNdEx:iNdEx+skippy]...)
iNdEx += skippy iNdEx += skippy
} }
} }
@ -504,7 +556,9 @@ func (m *Log) Unmarshal(data []byte) error {
} }
return nil return nil
} }
func (m *Log_Content) Unmarshal(data []byte) error {
// Unmarshal data to LogContent
func (m *LogContent) Unmarshal(data []byte) error {
var hasFields [1]uint64 var hasFields [1]uint64
l := len(data) l := len(data)
iNdEx := 0 iNdEx := 0
@ -608,7 +662,7 @@ func (m *Log_Content) Unmarshal(data []byte) error {
if (iNdEx + skippy) > l { if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
m.XXX_unrecognized = append(m.XXX_unrecognized, data[iNdEx:iNdEx+skippy]...) m.XXXUnrecognized = append(m.XXXUnrecognized, data[iNdEx:iNdEx+skippy]...)
iNdEx += skippy iNdEx += skippy
} }
} }
@ -624,6 +678,8 @@ func (m *Log_Content) Unmarshal(data []byte) error {
} }
return nil return nil
} }
// Unmarshal data to LogGroup
func (m *LogGroup) Unmarshal(data []byte) error { func (m *LogGroup) Unmarshal(data []byte) error {
l := len(data) l := len(data)
iNdEx := 0 iNdEx := 0
@ -786,7 +842,7 @@ func (m *LogGroup) Unmarshal(data []byte) error {
if (iNdEx + skippy) > l { if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
m.XXX_unrecognized = append(m.XXX_unrecognized, data[iNdEx:iNdEx+skippy]...) m.XXXUnrecognized = append(m.XXXUnrecognized, data[iNdEx:iNdEx+skippy]...)
iNdEx += skippy iNdEx += skippy
} }
} }
@ -796,6 +852,8 @@ func (m *LogGroup) Unmarshal(data []byte) error {
} }
return nil return nil
} }
// Unmarshal data to LogGroupList
func (m *LogGroupList) Unmarshal(data []byte) error { func (m *LogGroupList) Unmarshal(data []byte) error {
l := len(data) l := len(data)
iNdEx := 0 iNdEx := 0
@ -868,7 +926,7 @@ func (m *LogGroupList) Unmarshal(data []byte) error {
if (iNdEx + skippy) > l { if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
m.XXX_unrecognized = append(m.XXX_unrecognized, data[iNdEx:iNdEx+skippy]...) m.XXXUnrecognized = append(m.XXXUnrecognized, data[iNdEx:iNdEx+skippy]...)
iNdEx += skippy iNdEx += skippy
} }
} }
@ -878,6 +936,7 @@ func (m *LogGroupList) Unmarshal(data []byte) error {
} }
return nil return nil
} }
func skipLog(data []byte) (n int, err error) { func skipLog(data []byte) (n int, err error) {
l := len(data) l := len(data)
iNdEx := 0 iNdEx := 0
@ -940,7 +999,7 @@ func skipLog(data []byte) (n int, err error) {
case 3: case 3:
for { for {
var innerWire uint64 var innerWire uint64
var start int = iNdEx var start = iNdEx
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
return 0, ErrIntOverflowLog return 0, ErrIntOverflowLog
@ -977,8 +1036,3 @@ func skipLog(data []byte) (n int, err error) {
} }
panic("unreachable") panic("unreachable")
} }
var (
ErrInvalidLengthLog = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowLog = fmt.Errorf("proto: integer overflow")
)

View File

@ -1,5 +1,6 @@
package alils package alils
// InputDetail define log detail
type InputDetail struct { type InputDetail struct {
LogType string `json:"logType"` LogType string `json:"logType"`
LogPath string `json:"logPath"` LogPath string `json:"logPath"`
@ -14,11 +15,13 @@ type InputDetail struct {
TopicFormat string `json:"topicFormat"` TopicFormat string `json:"topicFormat"`
} }
// OutputDetail define the output detail
type OutputDetail struct { type OutputDetail struct {
Endpoint string `json:"endpoint"` Endpoint string `json:"endpoint"`
LogStoreName string `json:"logstoreName"` LogStoreName string `json:"logstoreName"`
} }
// LogConfig define Log Config
type LogConfig struct { type LogConfig struct {
Name string `json:"configName"` Name string `json:"configName"`
InputType string `json:"inputType"` InputType string `json:"inputType"`

View File

@ -1,5 +1,5 @@
/* /*
Package sls implements the SDK(v0.5.0) of Simple Log Service(abbr. SLS). Package alils implements the SDK(v0.5.0) of Simple Log Service(abbr. SLS).
For more description about SLS, please read this article: For more description about SLS, please read this article:
http://gitlab.alibaba-inc.com/sls/doc. http://gitlab.alibaba-inc.com/sls/doc.
@ -20,19 +20,20 @@ type errorMessage struct {
Message string `json:"errorMessage"` Message string `json:"errorMessage"`
} }
// LogProject Define the Ali Project detail
type LogProject struct { type LogProject struct {
Name string // Project name Name string // Project name
Endpoint string // IP or hostname of SLS endpoint Endpoint string // IP or hostname of SLS endpoint
AccessKeyId string AccessKeyID string
AccessKeySecret string AccessKeySecret string
} }
// NewLogProject creates a new SLS project. // NewLogProject creates a new SLS project.
func NewLogProject(name, endpoint, accessKeyId, accessKeySecret string) (p *LogProject, err error) { func NewLogProject(name, endpoint, AccessKeyID, accessKeySecret string) (p *LogProject, err error) {
p = &LogProject{ p = &LogProject{
Name: name, Name: name,
Endpoint: endpoint, Endpoint: endpoint,
AccessKeyId: accessKeyId, AccessKeyID: AccessKeyID,
AccessKeySecret: accessKeySecret, AccessKeySecret: accessKeySecret,
} }
return p, nil return p, nil

View File

@ -12,6 +12,7 @@ import (
"github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/proto"
) )
// LogStore Store the logs
type LogStore struct { type LogStore struct {
Name string `json:"logstoreName"` Name string `json:"logstoreName"`
TTL int TTL int
@ -23,6 +24,7 @@ type LogStore struct {
project *LogProject project *LogProject
} }
// Shard define the Log Shard
type Shard struct { type Shard struct {
ShardID int `json:"shardID"` ShardID int `json:"shardID"`
} }
@ -116,16 +118,16 @@ func (s *LogStore) PutLogs(lg *LogGroup) (err error) {
return return
} }
// GetCursor gets log cursor of one shard specified by shardId. // GetCursor gets log cursor of one shard specified by shardID.
// The from can be in three form: a) unix timestamp in seccond, b) "begin", c) "end". // The from can be in three form: a) unix timestamp in seccond, b) "begin", c) "end".
// For more detail please read: http://gitlab.alibaba-inc.com/sls/doc/blob/master/api/shard.md#logstore // For more detail please read: http://gitlab.alibaba-inc.com/sls/doc/blob/master/api/shard.md#logstore
func (s *LogStore) GetCursor(shardId int, from string) (cursor string, err error) { func (s *LogStore) GetCursor(shardID int, from string) (cursor string, err error) {
h := map[string]string{ h := map[string]string{
"x-sls-bodyrawsize": "0", "x-sls-bodyrawsize": "0",
} }
uri := fmt.Sprintf("/logstores/%v/shards/%v?type=cursor&from=%v", uri := fmt.Sprintf("/logstores/%v/shards/%v?type=cursor&from=%v",
s.Name, shardId, from) s.Name, shardID, from)
r, err := request(s.project, "GET", uri, h, nil) r, err := request(s.project, "GET", uri, h, nil)
if err != nil { if err != nil {
@ -163,10 +165,10 @@ func (s *LogStore) GetCursor(shardId int, from string) (cursor string, err error
return return
} }
// GetLogsBytes gets logs binary data from shard specified by shardId according cursor. // GetLogsBytes gets logs binary data from shard specified by shardID according cursor.
// The logGroupMaxCount is the max number of logGroup could be returned. // The logGroupMaxCount is the max number of logGroup could be returned.
// The nextCursor is the next curosr can be used to read logs at next time. // The nextCursor is the next curosr can be used to read logs at next time.
func (s *LogStore) GetLogsBytes(shardId int, cursor string, func (s *LogStore) GetLogsBytes(shardID int, cursor string,
logGroupMaxCount int) (out []byte, nextCursor string, err error) { logGroupMaxCount int) (out []byte, nextCursor string, err error) {
h := map[string]string{ h := map[string]string{
@ -176,7 +178,7 @@ func (s *LogStore) GetLogsBytes(shardId int, cursor string,
} }
uri := fmt.Sprintf("/logstores/%v/shards/%v?type=logs&cursor=%v&count=%v", uri := fmt.Sprintf("/logstores/%v/shards/%v?type=logs&cursor=%v&count=%v",
s.Name, shardId, cursor, logGroupMaxCount) s.Name, shardID, cursor, logGroupMaxCount)
r, err := request(s.project, "GET", uri, h, nil) r, err := request(s.project, "GET", uri, h, nil)
if err != nil { if err != nil {
@ -249,13 +251,13 @@ func LogsBytesDecode(data []byte) (gl *LogGroupList, err error) {
return return
} }
// GetLogs gets logs from shard specified by shardId according cursor. // GetLogs gets logs from shard specified by shardID according cursor.
// The logGroupMaxCount is the max number of logGroup could be returned. // The logGroupMaxCount is the max number of logGroup could be returned.
// The nextCursor is the next curosr can be used to read logs at next time. // The nextCursor is the next curosr can be used to read logs at next time.
func (s *LogStore) GetLogs(shardId int, cursor string, func (s *LogStore) GetLogs(shardID int, cursor string,
logGroupMaxCount int) (gl *LogGroupList, nextCursor string, err error) { logGroupMaxCount int) (gl *LogGroupList, nextCursor string, err error) {
out, nextCursor, err := s.GetLogsBytes(shardId, cursor, logGroupMaxCount) out, nextCursor, err := s.GetLogsBytes(shardID, cursor, logGroupMaxCount)
if err != nil { if err != nil {
return return
} }

View File

@ -8,18 +8,20 @@ import (
"net/http/httputil" "net/http/httputil"
) )
type MachinGroupAttribute struct { // MachineGroupAttribute define the Attribute
type MachineGroupAttribute struct {
ExternalName string `json:"externalName"` ExternalName string `json:"externalName"`
TopicName string `json:"groupTopic"` TopicName string `json:"groupTopic"`
} }
// MachineGroup define the machine Group
type MachineGroup struct { type MachineGroup struct {
Name string `json:"groupName"` Name string `json:"groupName"`
Type string `json:"groupType"` Type string `json:"groupType"`
MachineIdType string `json:"machineIdentifyType"` MachineIDType string `json:"machineIdentifyType"`
MachineIdList []string `json:"machineList"` MachineIDList []string `json:"machineList"`
Attribute MachinGroupAttribute `json:"groupAttribute"` Attribute MachineGroupAttribute `json:"groupAttribute"`
CreateTime uint32 CreateTime uint32
LastModifyTime uint32 LastModifyTime uint32
@ -27,12 +29,14 @@ type MachineGroup struct {
project *LogProject project *LogProject
} }
// Machine define the Machine
type Machine struct { type Machine struct {
IP string IP string
UniqueId string `json:"machine-uniqueid"` UniqueID string `json:"machine-uniqueid"`
UserdefinedId string `json:"userdefined-id"` UserdefinedID string `json:"userdefined-id"`
} }
// MachineList define the Machine List
type MachineList struct { type MachineList struct {
Total int Total int
Machines []*Machine Machines []*Machine

View File

@ -33,12 +33,12 @@ func request(project *LogProject, method, uri string, headers map[string]string,
} }
// Calc Authorization // Calc Authorization
// Authorization = "SLS <AccessKeyId>:<Signature>" // Authorization = "SLS <AccessKeyID>:<Signature>"
digest, err := signature(project, method, uri, headers) digest, err := signature(project, method, uri, headers)
if err != nil { if err != nil {
return return
} }
auth := fmt.Sprintf("SLS %v:%v", project.AccessKeyId, digest) auth := fmt.Sprintf("SLS %v:%v", project.AccessKeyID, digest)
headers["Authorization"] = auth headers["Authorization"] = auth
// Initialize http request // Initialize http request

View File

@ -170,7 +170,7 @@ func (w *fileLogWriter) initFd() error {
fd := w.fileWriter fd := w.fileWriter
fInfo, err := fd.Stat() fInfo, err := fd.Stat()
if err != nil { if err != nil {
return fmt.Errorf("get stat err: %s\n", err) return fmt.Errorf("get stat err: %s", err)
} }
w.maxSizeCurSize = int(fInfo.Size()) w.maxSizeCurSize = int(fInfo.Size())
w.dailyOpenTime = time.Now() w.dailyOpenTime = time.Now()

View File

@ -492,9 +492,9 @@ func (bl *BeeLogger) flush() {
} }
// beeLogger references the used application logger. // beeLogger references the used application logger.
var beeLogger *BeeLogger = NewLogger() var beeLogger = NewLogger()
// GetLogger returns the default BeeLogger // GetBeeLogger returns the default BeeLogger
func GetBeeLogger() *BeeLogger { func GetBeeLogger() *BeeLogger {
return beeLogger return beeLogger
} }
@ -534,6 +534,7 @@ func Reset() {
beeLogger.Reset() beeLogger.Reset()
} }
// Async set the beelogger with Async mode and hold msglen messages
func Async(msgLen ...int64) *BeeLogger { func Async(msgLen ...int64) *BeeLogger {
return beeLogger.Async(msgLen...) return beeLogger.Async(msgLen...)
} }

View File

@ -139,6 +139,11 @@ var (
reset = string([]byte{27, 91, 48, 109}) reset = string([]byte{27, 91, 48, 109})
) )
// ColorByStatus return color by http code
// 2xx return Green
// 3xx return White
// 4xx return Yellow
// 5xx return Red
func ColorByStatus(cond bool, code int) string { func ColorByStatus(cond bool, code int) string {
switch { switch {
case code >= 200 && code < 300: case code >= 200 && code < 300:
@ -152,6 +157,14 @@ func ColorByStatus(cond bool, code int) string {
} }
} }
// ColorByMethod return color by http code
// GET return Blue
// POST return Cyan
// PUT return Yellow
// DELETE return Red
// PATCH return Green
// HEAD return Magenta
// OPTIONS return WHITE
func ColorByMethod(cond bool, method string) string { func ColorByMethod(cond bool, method string) string {
switch method { switch method {
case "GET": case "GET":
@ -173,10 +186,10 @@ func ColorByMethod(cond bool, method string) string {
} }
} }
// Guard Mutex to guarantee atomicity of W32Debug(string) function // Guard Mutex to guarantee atomic of W32Debug(string) function
var mu sync.Mutex var mu sync.Mutex
// Helper method to output colored logs in Windows terminals // W32Debug Helper method to output colored logs in Windows terminals
func W32Debug(msg string) { func W32Debug(msg string) {
mu.Lock() mu.Lock()
defer mu.Unlock() defer mu.Unlock()

View File

@ -507,10 +507,9 @@ func (d *dbBase) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a
case DRPostgres: case DRPostgres:
if len(args) == 0 { if len(args) == 0 {
return 0, fmt.Errorf("`%s` use InsertOrUpdate must have a conflict column", a.DriverName) return 0, fmt.Errorf("`%s` use InsertOrUpdate must have a conflict column", a.DriverName)
} else {
args0 = strings.ToLower(args[0])
iouStr = fmt.Sprintf("ON CONFLICT (%s) DO UPDATE SET", args0)
} }
args0 = strings.ToLower(args[0])
iouStr = fmt.Sprintf("ON CONFLICT (%s) DO UPDATE SET", args0)
default: default:
return 0, fmt.Errorf("`%s` nonsupport InsertOrUpdate in beego", a.DriverName) return 0, fmt.Errorf("`%s` nonsupport InsertOrUpdate in beego", a.DriverName)
} }

View File

@ -250,7 +250,7 @@ func RegisterDriver(driverName string, typ DriverType) error {
drivers[driverName] = typ drivers[driverName] = typ
} else { } else {
if t != typ { if t != typ {
return fmt.Errorf("driverName `%s` db driver already registered and is other type\n", driverName) return fmt.Errorf("driverName `%s` db driver already registered and is other type", driverName)
} }
} }
return nil return nil
@ -261,7 +261,7 @@ func SetDataBaseTZ(aliasName string, tz *time.Location) error {
if al, ok := dataBaseCache.get(aliasName); ok { if al, ok := dataBaseCache.get(aliasName); ok {
al.TZ = tz al.TZ = tz
} else { } else {
return fmt.Errorf("DataBase alias name `%s` not registered\n", aliasName) return fmt.Errorf("DataBase alias name `%s` not registered", aliasName)
} }
return nil return nil
} }
@ -296,5 +296,5 @@ func GetDB(aliasNames ...string) (*sql.DB, error) {
if ok { if ok {
return al.DB, nil return al.DB, nil
} }
return nil, fmt.Errorf("DataBase of alias name `%s` not found\n", name) return nil, fmt.Errorf("DataBase of alias name `%s` not found", name)
} }

View File

@ -81,6 +81,7 @@ func Register(name string, provide Provider) {
provides[name] = provide provides[name] = provide
} }
// ManagerConfig define the session config
type ManagerConfig struct { type ManagerConfig struct {
CookieName string `json:"cookieName"` CookieName string `json:"cookieName"`
EnableSetCookie bool `json:"enableSetCookie,omitempty"` EnableSetCookie bool `json:"enableSetCookie,omitempty"`
@ -92,9 +93,9 @@ type ManagerConfig struct {
ProviderConfig string `json:"providerConfig"` ProviderConfig string `json:"providerConfig"`
Domain string `json:"domain"` Domain string `json:"domain"`
SessionIDLength int64 `json:"sessionIDLength"` SessionIDLength int64 `json:"sessionIDLength"`
EnableSidInHttpHeader bool `json:"enableSidInHttpHeader"` EnableSidInHTTPHeader bool `json:"EnableSidInHTTPHeader"`
SessionNameInHttpHeader string `json:"sessionNameInHttpHeader"` SessionNameInHTTPHeader string `json:"SessionNameInHTTPHeader"`
EnableSidInUrlQuery bool `json:"enableSidInUrlQuery"` EnableSidInURLQuery bool `json:"EnableSidInURLQuery"`
} }
// Manager contains Provider and its configuration. // Manager contains Provider and its configuration.
@ -125,14 +126,14 @@ func NewManager(provideName string, cf *ManagerConfig) (*Manager, error) {
cf.Maxlifetime = cf.Gclifetime cf.Maxlifetime = cf.Gclifetime
} }
if cf.EnableSidInHttpHeader { if cf.EnableSidInHTTPHeader {
if cf.SessionNameInHttpHeader == "" { if cf.SessionNameInHTTPHeader == "" {
panic(errors.New("SessionNameInHttpHeader is empty")) panic(errors.New("SessionNameInHTTPHeader is empty"))
} }
strMimeHeader := textproto.CanonicalMIMEHeaderKey(cf.SessionNameInHttpHeader) strMimeHeader := textproto.CanonicalMIMEHeaderKey(cf.SessionNameInHTTPHeader)
if cf.SessionNameInHttpHeader != strMimeHeader { if cf.SessionNameInHTTPHeader != strMimeHeader {
strErrMsg := "SessionNameInHttpHeader (" + cf.SessionNameInHttpHeader + ") has the wrong format, it should be like this : " + strMimeHeader strErrMsg := "SessionNameInHTTPHeader (" + cf.SessionNameInHTTPHeader + ") has the wrong format, it should be like this : " + strMimeHeader
panic(errors.New(strErrMsg)) panic(errors.New(strErrMsg))
} }
} }
@ -163,7 +164,7 @@ func (manager *Manager) getSid(r *http.Request) (string, error) {
cookie, errs := r.Cookie(manager.config.CookieName) cookie, errs := r.Cookie(manager.config.CookieName)
if errs != nil || cookie.Value == "" { if errs != nil || cookie.Value == "" {
var sid string var sid string
if manager.config.EnableSidInUrlQuery { if manager.config.EnableSidInURLQuery {
errs := r.ParseForm() errs := r.ParseForm()
if errs != nil { if errs != nil {
return "", errs return "", errs
@ -173,8 +174,8 @@ func (manager *Manager) getSid(r *http.Request) (string, error) {
} }
// if not found in Cookie / param, then read it from request headers // if not found in Cookie / param, then read it from request headers
if manager.config.EnableSidInHttpHeader && sid == "" { if manager.config.EnableSidInHTTPHeader && sid == "" {
sids, isFound := r.Header[manager.config.SessionNameInHttpHeader] sids, isFound := r.Header[manager.config.SessionNameInHTTPHeader]
if isFound && len(sids) != 0 { if isFound && len(sids) != 0 {
return sids[0], nil return sids[0], nil
} }
@ -226,9 +227,9 @@ func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (se
} }
r.AddCookie(cookie) r.AddCookie(cookie)
if manager.config.EnableSidInHttpHeader { if manager.config.EnableSidInHTTPHeader {
r.Header.Set(manager.config.SessionNameInHttpHeader, sid) r.Header.Set(manager.config.SessionNameInHTTPHeader, sid)
w.Header().Set(manager.config.SessionNameInHttpHeader, sid) w.Header().Set(manager.config.SessionNameInHTTPHeader, sid)
} }
return return
@ -236,9 +237,9 @@ func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (se
// SessionDestroy Destroy session by its id in http request cookie. // SessionDestroy Destroy session by its id in http request cookie.
func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request) { func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request) {
if manager.config.EnableSidInHttpHeader { if manager.config.EnableSidInHTTPHeader {
r.Header.Del(manager.config.SessionNameInHttpHeader) r.Header.Del(manager.config.SessionNameInHTTPHeader)
w.Header().Del(manager.config.SessionNameInHttpHeader) w.Header().Del(manager.config.SessionNameInHTTPHeader)
} }
cookie, err := r.Cookie(manager.config.CookieName) cookie, err := r.Cookie(manager.config.CookieName)
@ -306,9 +307,9 @@ func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Reque
} }
r.AddCookie(cookie) r.AddCookie(cookie)
if manager.config.EnableSidInHttpHeader { if manager.config.EnableSidInHTTPHeader {
r.Header.Set(manager.config.SessionNameInHttpHeader, sid) r.Header.Set(manager.config.SessionNameInHTTPHeader, sid)
w.Header().Set(manager.config.SessionNameInHttpHeader, sid) w.Header().Set(manager.config.SessionNameInHTTPHeader, sid)
} }
return return
@ -328,7 +329,7 @@ func (manager *Manager) sessionID() (string, error) {
b := make([]byte, manager.config.SessionIDLength) b := make([]byte, manager.config.SessionIDLength)
n, err := rand.Read(b) n, err := rand.Read(b)
if n != len(b) || err != nil { if n != len(b) || err != nil {
return "", fmt.Errorf("Could not successfully read from the system CSPRNG.") return "", fmt.Errorf("Could not successfully read from the system CSPRNG")
} }
return hex.EncodeToString(b), nil return hex.EncodeToString(b), nil
} }

View File

@ -11,16 +11,17 @@ import (
"github.com/ssdb/gossdb/ssdb" "github.com/ssdb/gossdb/ssdb"
) )
var ssdbProvider = &SsdbProvider{} var ssdbProvider = &Provider{}
type SsdbProvider struct { // Provider holds ssdb client and configs
type Provider struct {
client *ssdb.Client client *ssdb.Client
host string host string
port int port int
maxLifetime int64 maxLifetime int64
} }
func (p *SsdbProvider) connectInit() error { func (p *Provider) connectInit() error {
var err error var err error
if p.host == "" || p.port == 0 { if p.host == "" || p.port == 0 {
return errors.New("SessionInit First") return errors.New("SessionInit First")
@ -29,7 +30,8 @@ func (p *SsdbProvider) connectInit() error {
return err return err
} }
func (p *SsdbProvider) SessionInit(maxLifetime int64, savePath string) error { // SessionInit init the ssdb with the config
func (p *Provider) SessionInit(maxLifetime int64, savePath string) error {
p.maxLifetime = maxLifetime p.maxLifetime = maxLifetime
address := strings.Split(savePath, ":") address := strings.Split(savePath, ":")
p.host = address[0] p.host = address[0]
@ -41,7 +43,8 @@ func (p *SsdbProvider) SessionInit(maxLifetime int64, savePath string) error {
return p.connectInit() return p.connectInit()
} }
func (p *SsdbProvider) SessionRead(sid string) (session.Store, error) { // SessionRead return a ssdb client session Store
func (p *Provider) SessionRead(sid string) (session.Store, error) {
if p.client == nil { if p.client == nil {
if err := p.connectInit(); err != nil { if err := p.connectInit(); err != nil {
return nil, err return nil, err
@ -64,7 +67,8 @@ func (p *SsdbProvider) SessionRead(sid string) (session.Store, error) {
return rs, nil return rs, nil
} }
func (p *SsdbProvider) SessionExist(sid string) bool { // SessionExist judged whether sid is exist in session
func (p *Provider) SessionExist(sid string) bool {
if p.client == nil { if p.client == nil {
if err := p.connectInit(); err != nil { if err := p.connectInit(); err != nil {
panic(err) panic(err)
@ -80,7 +84,8 @@ func (p *SsdbProvider) SessionExist(sid string) bool {
return true return true
} }
func (p *SsdbProvider) SessionRegenerate(oldsid, sid string) (session.Store, error) { // SessionRegenerate regenerate session with new sid and delete oldsid
func (p *Provider) SessionRegenerate(oldsid, sid string) (session.Store, error) {
//conn.Do("setx", key, v, ttl) //conn.Do("setx", key, v, ttl)
if p.client == nil { if p.client == nil {
if err := p.connectInit(); err != nil { if err := p.connectInit(); err != nil {
@ -112,7 +117,8 @@ func (p *SsdbProvider) SessionRegenerate(oldsid, sid string) (session.Store, err
return rs, nil return rs, nil
} }
func (p *SsdbProvider) SessionDestroy(sid string) error { // SessionDestroy destroy the sid
func (p *Provider) SessionDestroy(sid string) error {
if p.client == nil { if p.client == nil {
if err := p.connectInit(); err != nil { if err := p.connectInit(); err != nil {
return err return err
@ -122,13 +128,16 @@ func (p *SsdbProvider) SessionDestroy(sid string) error {
return err return err
} }
func (p *SsdbProvider) SessionGC() { // SessionGC not implemented
func (p *Provider) SessionGC() {
} }
func (p *SsdbProvider) SessionAll() int { // SessionAll not implemented
func (p *Provider) SessionAll() int {
return 0 return 0
} }
// SessionStore holds the session information which stored in ssdb
type SessionStore struct { type SessionStore struct {
sid string sid string
lock sync.RWMutex lock sync.RWMutex
@ -137,12 +146,15 @@ type SessionStore struct {
client *ssdb.Client client *ssdb.Client
} }
// Set the key and value
func (s *SessionStore) Set(key, value interface{}) error { func (s *SessionStore) Set(key, value interface{}) error {
s.lock.Lock() s.lock.Lock()
defer s.lock.Unlock() defer s.lock.Unlock()
s.values[key] = value s.values[key] = value
return nil return nil
} }
// Get return the value by the key
func (s *SessionStore) Get(key interface{}) interface{} { func (s *SessionStore) Get(key interface{}) interface{} {
s.lock.Lock() s.lock.Lock()
defer s.lock.Unlock() defer s.lock.Unlock()
@ -152,30 +164,36 @@ func (s *SessionStore) Get(key interface{}) interface{} {
return nil return nil
} }
// Delete the key in session store
func (s *SessionStore) Delete(key interface{}) error { func (s *SessionStore) Delete(key interface{}) error {
s.lock.Lock() s.lock.Lock()
defer s.lock.Unlock() defer s.lock.Unlock()
delete(s.values, key) delete(s.values, key)
return nil return nil
} }
// Flush delete all keys and values
func (s *SessionStore) Flush() error { func (s *SessionStore) Flush() error {
s.lock.Lock() s.lock.Lock()
defer s.lock.Unlock() defer s.lock.Unlock()
s.values = make(map[interface{}]interface{}) s.values = make(map[interface{}]interface{})
return nil return nil
} }
// SessionID return the sessionID
func (s *SessionStore) SessionID() string { func (s *SessionStore) SessionID() string {
return s.sid return s.sid
} }
// SessionRelease Store the keyvalues into ssdb
func (s *SessionStore) SessionRelease(w http.ResponseWriter) { func (s *SessionStore) SessionRelease(w http.ResponseWriter) {
b, err := session.EncodeGob(s.values) b, err := session.EncodeGob(s.values)
if err != nil { if err != nil {
return return
} }
s.client.Do("setx", s.sid, string(b), s.maxLifetime) s.client.Do("setx", s.sid, string(b), s.maxLifetime)
} }
func init() { func init() {
session.Register("ssdb", ssdbProvider) session.Register("ssdb", ssdbProvider)
} }

View File

@ -100,7 +100,7 @@ type Parameter struct {
Default interface{} `json:"default,omitempty" yaml:"default,omitempty"` Default interface{} `json:"default,omitempty" yaml:"default,omitempty"`
} }
// A limited subset of JSON-Schema's items object. It is used by parameter definitions that are not located in "body". // ParameterItems A limited subset of JSON-Schema's items object. It is used by parameter definitions that are not located in "body".
// http://swagger.io/specification/#itemsObject // http://swagger.io/specification/#itemsObject
type ParameterItems struct { type ParameterItems struct {
Type string `json:"type,omitempty" yaml:"type,omitempty"` Type string `json:"type,omitempty" yaml:"type,omitempty"`