Skip to content

Commit

Permalink
Merge pull request #104 from go-goim/fix/util-id
Browse files Browse the repository at this point in the history
Fix/util id
  • Loading branch information
yusank authored Sep 2, 2022
2 parents 086fe4a + b599555 commit df633da
Show file tree
Hide file tree
Showing 15 changed files with 78 additions and 80 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ require (
)

require (
github.com/go-goim/api v0.0.7
github.com/go-goim/api v0.0.8
github.com/go-kratos/kratos/contrib/config/etcd/v2 v2.0.0-20220528114537-97c103a39562
github.com/panjf2000/ants/v2 v2.5.0
github.com/tsuna/gohbase v0.0.0-20220517082425-cb1f77f08e4f
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.8.1 h1:4+fr/el88TOO3ewCmQr8cx/CtZ/umlIRIs5M4NTNjf8=
github.com/gin-gonic/gin v1.8.1/go.mod h1:ji8BvRH1azfM+SYow9zQ6SZMvR8qOMZHmsCuWR9tTTk=
github.com/go-goim/api v0.0.7 h1:JnECTk4ait2Nkzv2YJx16+H8vmQMX4qFeo/sncuTOtE=
github.com/go-goim/api v0.0.7/go.mod h1:93A7t8glrNTyYuWA2n4IhalnCtgw4uQ9lGV3E2t17gk=
github.com/go-goim/api v0.0.8 h1:K2FTSMXFwGyjeCWHoQMJ+oNRsT6yEgwPef3YzoE/cs4=
github.com/go-goim/api v0.0.8/go.mod h1:93A7t8glrNTyYuWA2n4IhalnCtgw4uQ9lGV3E2t17gk=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
Expand Down
2 changes: 1 addition & 1 deletion pkg/app/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import (

// Application is a common app entry.
// All apps can use this Application as a base entry and add own fields and methods
// in their own app packages.
// in their own app packages.
type Application struct {
Core *kratos.App
Register registry.RegisterDiscover
Expand Down
42 changes: 22 additions & 20 deletions pkg/db/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,26 +41,28 @@ func ctxWithGormDB(ctx context.Context, tx *gorm.DB) context.Context {
}

// Transaction get gorm.DB from ctx and run Transaction Operation with ctx
// How to use:
// // 所有 db 操作的第一参数为 context.Context, 然后通过 ctx 读取 DB 对象
// if err := db.Transaction(context.Background(), func(ctx context.Context) error {
// if err := d.Create(ctx); err != nil {
// return err
// }
//
// d.Name = "123"
// return d.Update(ctx)
// }); err != nil {
// return
// }
//
// func (d *Domain) Create(ctx context.Context) error {
// return GetDBFromCtx(ctx).Create(d).Error
// }
//
// func (d *Domain) Update(ctx context.Context) error {
// return GetDBFromCtx(ctx).Updates(d).Error
// }
/*
How to use:
// 所有 db 操作的第一参数为 context.Context, 然后通过 ctx 读取 DB 对象
if err := db.Transaction(context.Background(), func(ctx context.Context) error {
if err := d.Create(ctx); err != nil {
return err
}
d.Name = "123"
return d.Update(ctx)
}); err != nil {
return
}
func (d *Domain) Create(ctx context.Context) error {
return GetDBFromCtx(ctx).Create(d).Error
}
func (d *Domain) Update(ctx context.Context) error {
return GetDBFromCtx(ctx).Updates(d).Error
}
*/
func Transaction(ctx context.Context, f func(context.Context) error) error {
if ctx == nil {
ctx = context.Background()
Expand Down
35 changes: 18 additions & 17 deletions pkg/db/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,23 +51,24 @@ func Pipeline(ctx context.Context, fn func(pipeline redisv8.Pipeliner) error) er
return err
}

// TxPipeline get redisv8.Client from ctx and run Transaction Pipeline Operation with ctx
// It's same as Pipeline, but wraps queued commands with MULTI/EXEC.
// How to use:
// var (
// get *redisv8.StringCmd
// )
// err := TxPipeline(ctx, func(pipeline redisv8.Pipeliner) error {
// pipeline.Set(ctx, "key", "value", 0)
// get = pipeline.Get(ctx, "key")
// return nil
// })
// if err != nil {
// return err
// }
//
// fmt.Println(get.Val())
// // Output: value
// TxPipeline get redisv8.Client from ctx and run Transaction Pipeline Operation with ctx.
// It's same as Pipeline, but wraps queued commands with MULTI/EXEC.
/*
How to use:
var (
get *redisv8.StringCmd
)
err := TxPipeline(ctx, func(pipeline redisv8.Pipeliner) error {
pipeline.Set(ctx, "key", "value", 0)
get = pipeline.Get(ctx, "key")
return nil
})
if err != nil {
return err
}
fmt.Println(get.Val())
*/
func TxPipeline(ctx context.Context, fn func(pipeline redisv8.Pipeliner) error) error {
if ctx == nil {
ctx = context.Background()
Expand Down
2 changes: 1 addition & 1 deletion pkg/goroutine/goroutine.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func init() {
}

// Submit new task to pool
// It will block if goroutine is up to max
// It will block if goroutine is up to max
func Submit(f func()) error {
return _defaultPool.Submit(f)
}
4 changes: 2 additions & 2 deletions pkg/mid/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import (
)

func TestNewJwtToken(t *testing.T) {
var uid int64 = 1
jwt, err := NewJwtToken(types.ID(uid))
var uid = types.ID(1)
jwt, err := NewJwtToken(uid)
assert.Nil(t, err)
assert.NotEmpty(t, jwt)

Expand Down
9 changes: 4 additions & 5 deletions pkg/types/id.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ var decodeBase58Map [256]byte
// Create maps for decoding Base58/Base32.
// This speeds up the process tremendously.
func init() {

for i := 0; i < len(decodeBase58Map); i++ {
decodeBase58Map[i] = 0xFF
}
Expand Down Expand Up @@ -119,7 +118,7 @@ func ParseBase16(id string) (ID, error) {

// Base32 uses the z-base-32 character set but encodes and decodes similar
// to base58, allowing it to create an even smaller result string.
// NOTE: There are many different base32 implementations so becareful when
// NOTE: There are many base32 implementations so be careful when
// doing any interoperation.
func (f ID) Base32() string {
if f < 32 {
Expand All @@ -141,7 +140,7 @@ func (f ID) Base32() string {
}

// ParseBase32 parses a base32 []byte into a snowflake ID
// NOTE: There are many different base32 implementations so becareful when
// NOTE: There are many base32 implementations so be careful when
// doing any interoperation.
func ParseBase32(b []byte) (ID, error) {
var id int64
Expand Down Expand Up @@ -246,7 +245,7 @@ func ParseIntBytes(id [8]byte) ID {

// MarshalJSON returns a json byte array string of the snowflake ID.
// Note: this is not regular MarshalJSON, it converts the ID to a base58 string,
// instead of a regular strconv.FormatInt(id,10).
// instead of a regular strconv.FormatInt(id,10).
func (f ID) MarshalJSON() ([]byte, error) {
b58 := f.Base58()
buff := make([]byte, 0, len(b58)+2)
Expand All @@ -258,7 +257,7 @@ func (f ID) MarshalJSON() ([]byte, error) {

// UnmarshalJSON converts a json byte array of a snowflake ID into an ID type.
// Note: this is not regular UnmarshalJSON, it converts the ID from a base58,
// instead of a regular strconv.ParseInt(id,10).
// instead of a regular strconv.ParseInt(id,10).
func (f *ID) UnmarshalJSON(b []byte) error {
if len(b) < 3 || b[0] != '"' || b[len(b)-1] != '"' {
return JSONSyntaxError{b}
Expand Down
23 changes: 12 additions & 11 deletions pkg/util/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ import (
)

// Session generate session id
// switch tpye {
// case messagev1.SessionType_SingleChat:
// 001fromUIDtoUID
// case messagev1.SessionType_GroupChat:
// 010groupID00000000
// }
// to is groupID when type is groupChat
/*
switch tpye {
case messagev1.SessionType_SingleChat:
001fromUIDtoUID
case messagev1.SessionType_GroupChat:
010groupID00000000
}
*/
func Session(tp messagev1.SessionType, from, to types.ID) string {
// check if tp is valid
if tp > 0xFF || tp < 0 {
Expand Down Expand Up @@ -61,19 +62,19 @@ var (
ErrInvalidSessionIDLength = fmt.Errorf("invalid session id length")
)

func ParseSession(s string) (tp int32, from, to types.ID, err error) {
func ParseSession(s string) (tp messagev1.SessionType, from, to types.ID, err error) {
// check if s is valid
if len(s) < 2+2*11 {
return 0, 0, 0, ErrInvalidSessionIDLength
}

// first 2 bytes is session type
tpStr := s[:2]
i64, err := strconv.ParseInt(tpStr, 16, 32)
i32, err := strconv.ParseInt(tpStr, 16, 32)
if err != nil {
return 0, 0, 0, err
}
tp = int32(i64)
tp = messagev1.SessionType(i32)

// check if tp is valid
if tp > 0xFF || tp < 0 {
Expand All @@ -95,7 +96,7 @@ func ParseSession(s string) (tp int32, from, to types.ID, err error) {
}

// if tp is group chat, to is group id
if messagev1.SessionType(tp) == messagev1.SessionType_GroupChat {
if tp == messagev1.SessionType_GroupChat {
to = from
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/util/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func TestParseSession(t *testing.T) {
tests := []struct {
name string
args args
wantTp int32
wantTp messagev1.SessionType
wantFrom types.ID
wantTo types.ID
wantErr assert.ErrorAssertionFunc
Expand Down
8 changes: 2 additions & 6 deletions pkg/util/sets.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,16 @@ func NewSet[T comparable]() *Set[T] {
}
}

func (s *Set[T]) Add(elem ...T) *Set[T] {
func (s *Set[T]) Add(elem ...T) {
for _, e := range elem {
s.m[e] = true
}

return s
}

func (s *Set[T]) Remove(elem ...T) *Set[T] {
func (s *Set[T]) Remove(elem ...T) {
for _, e := range elem {
delete(s.m, e)
}

return s
}

func (s *Set[T]) Contains(elem T) bool {
Expand Down
4 changes: 2 additions & 2 deletions pkg/web/request/jsonpb.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package request

import (
"fmt"
"io/ioutil"
"io"
"net/http"

"github.com/gin-gonic/gin/binding"
Expand Down Expand Up @@ -38,7 +38,7 @@ func (b PbJSONBinding) Name() string {
}

func (b PbJSONBinding) Bind(req *http.Request, obj interface{}) error {
buf, err := ioutil.ReadAll(req.Body)
buf, err := io.ReadAll(req.Body)
if err != nil {
return err
}
Expand Down
14 changes: 7 additions & 7 deletions tests/batch-user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"io"
"log"
"net/http"
"net/url"
Expand Down Expand Up @@ -43,7 +43,7 @@ func (u *user) register() error {
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
Expand Down Expand Up @@ -83,7 +83,7 @@ func (u *user) login() error {
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
Expand Down Expand Up @@ -130,7 +130,7 @@ func (u *user) addFriend(fuid string) error {
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
Expand Down Expand Up @@ -164,7 +164,7 @@ func (u *user) queryFriend(email string) (uid string, err error) {
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
Expand Down Expand Up @@ -208,7 +208,7 @@ func (u *user) queryFriendRequests() (ids []uint64, err error) {
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -264,7 +264,7 @@ func (u *user) acceptFriend(requestID uint64) error {
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
Expand Down
6 changes: 3 additions & 3 deletions tests/client-gui/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"io"
"log"
"net"
"net/http"
Expand Down Expand Up @@ -205,7 +205,7 @@ func login() (serverIP string, err error) {
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
Expand Down Expand Up @@ -245,7 +245,7 @@ func loadFriends() error {
logger.Println(rsp.StatusCode)
defer rsp.Body.Close()

b, err := ioutil.ReadAll(rsp.Body)
b, err := io.ReadAll(rsp.Body)
if err != nil {
logger.Println(err)
return err
Expand Down
1 change: 0 additions & 1 deletion tests/ws.go
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
package tests

0 comments on commit df633da

Please sign in to comment.