├── goctl
├── goctl
│ ├── model
│ │ ├── sql
│ │ │ ├── util
│ │ │ │ ├── xx.sql
│ │ │ │ ├── studeat.sql
│ │ │ │ ├── student.sql
│ │ │ │ ├── sub
│ │ │ │ │ └── sub.sql
│ │ │ │ ├── xx.sql1
│ │ │ │ ├── newline.go
│ │ │ │ ├── slice.go
│ │ │ │ ├── matcher.go
│ │ │ │ └── match_test.go
│ │ │ ├── template
│ │ │ │ ├── tag.go
│ │ │ │ ├── field.go
│ │ │ │ ├── errors.go
│ │ │ │ ├── tablename.go
│ │ │ │ ├── types.go
│ │ │ │ ├── new.go
│ │ │ │ ├── import.go
│ │ │ │ ├── insert.go
│ │ │ │ ├── update.go
│ │ │ │ └── delete.go
│ │ │ ├── test
│ │ │ │ └── model
│ │ │ │ │ └── vars.go
│ │ │ ├── CHANGELOG.md
│ │ │ ├── gen
│ │ │ │ ├── tag.go
│ │ │ │ ├── tablename.go
│ │ │ │ ├── testdata
│ │ │ │ │ └── user.sql
│ │ │ │ ├── new.go
│ │ │ │ ├── imports.go
│ │ │ │ └── types.go
│ │ │ ├── converter
│ │ │ │ └── types_test.go
│ │ │ ├── builderx
│ │ │ │ └── builder.go
│ │ │ ├── command
│ │ │ │ ├── migrationnotes
│ │ │ │ │ └── migrationnotes.go
│ │ │ │ └── testdata
│ │ │ │ │ └── user.sql
│ │ │ ├── example
│ │ │ │ └── makefile
│ │ │ └── parser
│ │ │ │ └── testdata
│ │ │ │ └── user.sql
│ │ └── mongo
│ │ │ ├── template
│ │ │ ├── error.tpl
│ │ │ └── template.go
│ │ │ └── generate
│ │ │ └── generate_test.go
│ ├── .gitignore
│ ├── api
│ │ ├── parser
│ │ │ ├── g4
│ │ │ │ ├── test
│ │ │ │ │ ├── apis
│ │ │ │ │ │ ├── empty.api
│ │ │ │ │ │ ├── syntax.api
│ │ │ │ │ │ ├── info.api
│ │ │ │ │ │ ├── types.api
│ │ │ │ │ │ └── service.api
│ │ │ │ │ └── grammar_test.go
│ │ │ │ ├── ast
│ │ │ │ │ ├── placeholder.go
│ │ │ │ │ └── importstack.go
│ │ │ │ └── gen
│ │ │ │ │ └── api
│ │ │ │ │ ├── baseparser_test.go
│ │ │ │ │ └── apiparser_parser9.go
│ │ │ ├── testdata
│ │ │ │ └── test.api
│ │ │ └── parser_test.go
│ │ ├── tsgen
│ │ │ ├── handler.tpl
│ │ │ ├── components.tpl
│ │ │ └── vars.go
│ │ ├── javagen
│ │ │ ├── vars.go
│ │ │ ├── bool.tpl
│ │ │ ├── getset.tpl
│ │ │ ├── component.tpl
│ │ │ └── packet.tpl
│ │ ├── gogen
│ │ │ ├── etc.tpl
│ │ │ ├── testdata
│ │ │ │ ├── import_api.api
│ │ │ │ ├── api_has_no_request.api
│ │ │ │ ├── nest_type_api.api
│ │ │ │ ├── anonymous_annotation.api
│ │ │ │ ├── ap_ino_info.api
│ │ │ │ ├── invalid_api_file.api
│ │ │ │ ├── api_jwt.api
│ │ │ │ ├── api_has_middleware.api
│ │ │ │ ├── has_import_api.api
│ │ │ │ ├── no_struct_tag_api.api
│ │ │ │ ├── has_inline_no_exist_test.api
│ │ │ │ ├── api_jwt_with_middleware.api
│ │ │ │ ├── has_comment_api_test.api
│ │ │ │ ├── api_route_test.api
│ │ │ │ ├── test_multi_service_template.api
│ │ │ │ └── test_api_template.api
│ │ │ ├── types.tpl
│ │ │ ├── svc.tpl
│ │ │ ├── vars.go
│ │ │ ├── middleware.tpl
│ │ │ ├── main.tpl
│ │ │ ├── logic.tpl
│ │ │ ├── handler.tpl
│ │ │ └── genetc.go
│ │ ├── new
│ │ │ └── api.tpl
│ │ ├── docgen
│ │ │ └── markdown.tpl
│ │ ├── spec
│ │ │ └── validate.go
│ │ ├── apigen
│ │ │ ├── util.go
│ │ │ └── api.tpl
│ │ ├── validate
│ │ │ └── validate.go
│ │ ├── dartgen
│ │ │ └── format.go
│ │ └── ktgen
│ │ │ ├── api.tpl
│ │ │ └── cmd.go
│ ├── compare
│ │ ├── testdata
│ │ │ ├── unformat.api
│ │ │ └── kotlin.api
│ │ ├── make.sh
│ │ ├── compare.go
│ │ └── cmd
│ │ │ └── cmd.go
│ ├── migrate
│ │ ├── cancel+polyfill.go
│ │ ├── cmd.go
│ │ ├── cancel.go
│ │ ├── proxy.go
│ │ └── version.go
│ ├── update
│ │ ├── etc
│ │ │ └── update-api.json
│ │ └── config
│ │ │ └── config.go
│ ├── rpc
│ │ ├── generator
│ │ │ ├── config.tpl
│ │ │ ├── etc.tpl
│ │ │ ├── base
│ │ │ │ └── common.proto
│ │ │ ├── svc.tpl
│ │ │ ├── rpc.tpl
│ │ │ ├── server.tpl
│ │ │ ├── prototmpl_test.go
│ │ │ ├── logic.tpl
│ │ │ ├── call.tpl
│ │ │ ├── main.tpl
│ │ │ ├── prototmpl.go
│ │ │ └── generator.go
│ │ └── parser
│ │ │ ├── rpc.go
│ │ │ ├── import.go
│ │ │ ├── option.go
│ │ │ ├── message.go
│ │ │ ├── package.go
│ │ │ ├── test_option2.proto
│ │ │ ├── test_option.proto
│ │ │ ├── test_invalid_response.proto
│ │ │ ├── test_invalid_request.proto
│ │ │ ├── service.go
│ │ │ ├── comment.go
│ │ │ ├── proto.go
│ │ │ ├── stream.proto
│ │ │ └── test.proto
│ ├── util
│ │ ├── pathx
│ │ │ ├── readlink+polyfill.go
│ │ │ └── path_test.go
│ │ ├── ctx
│ │ │ ├── context_test.go
│ │ │ └── modcheck.go
│ │ ├── head.go
│ │ ├── name
│ │ │ └── naming_test.go
│ │ ├── zipx
│ │ │ └── zipx.go
│ │ ├── git.go
│ │ └── stringx
│ │ │ └── string_test.go
│ ├── env
│ │ ├── install.go
│ │ └── env.go
│ ├── bug
│ │ ├── cmd.go
│ │ ├── env.go
│ │ ├── issue.go
│ │ └── bug.go
│ ├── upgrade
│ │ ├── cmd.go
│ │ └── upgrade.go
│ ├── goctl.go
│ ├── internal
│ │ ├── errorx
│ │ │ ├── errorx._test.go
│ │ │ └── errorx.go
│ │ └── version
│ │ │ └── version_test.go
│ ├── plugin
│ │ ├── demo
│ │ │ └── goctlplugin.go
│ │ └── plugin_test.go
│ ├── pkg
│ │ ├── golang
│ │ │ ├── install.go
│ │ │ └── bin.go
│ │ ├── downloader
│ │ │ └── downloader.go
│ │ ├── goctl
│ │ │ └── goctl.go
│ │ └── protocgengogrpc
│ │ │ └── protocgengogrpc.go
│ ├── vars
│ │ └── settings.go
│ ├── go.mod
│ ├── Makefile
│ ├── docker
│ │ ├── docker.tpl
│ │ └── template.go
│ └── Dockerfile
└── home
│ └── 1.3.6-beta
│ ├── model
│ ├── tag.tpl
│ ├── field.tpl
│ ├── interface-update.tpl
│ ├── interface-delete.tpl
│ ├── interface-insert.tpl
│ ├── table-name.tpl
│ ├── interface-find-one-by-field.tpl
│ ├── interface-find-one.tpl
│ ├── err.tpl
│ ├── model-gen.tpl
│ ├── model-new.tpl
│ ├── types.tpl
│ ├── import-no-cache.tpl
│ ├── import.tpl
│ ├── find-one-by-field-extra-method.tpl
│ ├── insert.tpl
│ ├── update.tpl
│ ├── delete.tpl
│ ├── var.tpl
│ └── model.tpl
│ ├── api
│ ├── etc.tpl
│ ├── route-addition.tpl
│ ├── types.tpl
│ ├── config.tpl
│ ├── routes.tpl
│ ├── context.tpl
│ ├── middleware.tpl
│ ├── main.tpl
│ ├── logic.tpl
│ ├── template.tpl
│ └── handler.tpl
│ ├── rpc
│ ├── config.tpl
│ ├── etc.tpl
│ ├── call-interface-func.tpl
│ ├── svc.tpl
│ ├── template.tpl
│ ├── logic-func.tpl
│ ├── server.tpl
│ ├── call-func.tpl
│ ├── logic.tpl
│ ├── server-func.tpl
│ ├── call.tpl
│ └── main.tpl
│ ├── mongo
│ └── err.tpl
│ ├── newapi
│ └── newtemplate.tpl
│ └── docker
│ └── docker.tpl
├── common
├── README.md
├── xmgo
│ ├── global
│ │ └── config.go
│ └── client.go
├── xcache
│ ├── global
│ │ ├── interface.go
│ │ ├── key_utils.go
│ │ ├── db.go
│ │ ├── err.go
│ │ └── expire.go
│ ├── dc
│ │ ├── interface.go
│ │ ├── model_mapping_test.go
│ │ ├── list_option.go
│ │ └── first_option.go
│ ├── rc
│ │ ├── interface.go
│ │ ├── options.go
│ │ └── knownMap.go
│ └── client.go
├── xkafka
│ └── config.go
├── types
│ ├── errors.go
│ ├── conversation.go
│ ├── contenttype.go
│ └── rediskey.go
├── xorm
│ ├── global
│ │ ├── conf.go
│ │ ├── generateId.go
│ │ └── basemodel.go
│ ├── where.go
│ ├── client.go
│ └── err
│ │ └── duplicate.go
├── utils
│ ├── rand
│ │ ├── int_test.go
│ │ ├── int.go
│ │ ├── str.go
│ │ └── time.go
│ ├── num
│ │ └── contains.go
│ ├── str
│ │ ├── contain.go
│ │ └── difference.go
│ ├── encrypt
│ │ ├── md5.go
│ │ └── hash.go
│ ├── time
│ │ ├── now.go
│ │ └── format.go
│ ├── test
│ │ └── output.go
│ ├── map.go
│ ├── callerfunc.go
│ ├── env
│ │ └── env.go
│ └── statistics
│ │ └── statistics.go
├── xerr
│ ├── errcode.go
│ ├── errmsg.go
│ └── err.go
├── ctxdata
│ └── ctxData.go
├── fastjson
│ └── fastjson.go
├── xtrace
│ └── span.go
├── xetcd
│ ├── gozero.go
│ └── gozero_test.go
└── xhttp
│ └── responsebean.go
├── app
├── msg
│ └── cmd
│ │ └── rpc
│ │ ├── etc
│ │ └── ws.yaml
│ │ ├── pb
│ │ └── gencode.sh
│ │ ├── internal
│ │ ├── server
│ │ │ └── exampleServer.go
│ │ └── logic
│ │ │ ├── sendMsgStruct.go
│ │ │ ├── delMsgListLogic.go
│ │ │ ├── getMaxAndMinSeqLogic.go
│ │ │ └── pullMessageBySeqListLogic.go
│ │ └── chat.go
├── auth
│ └── cmd
│ │ └── rpc
│ │ ├── internal
│ │ ├── config
│ │ │ └── config.go
│ │ ├── svc
│ │ │ └── serviceContext.go
│ │ ├── server
│ │ │ └── authServiceServer.go
│ │ └── logic
│ │ │ └── verifyTokenLogic.go
│ │ ├── pb
│ │ ├── gencode.sh
│ │ └── auth.proto
│ │ ├── etc
│ │ └── auth.yaml
│ │ ├── authservice
│ │ └── authService.go
│ │ └── auth.go
├── im-user
│ └── cmd
│ │ └── rpc
│ │ ├── pb
│ │ └── gencode.sh
│ │ ├── internal
│ │ ├── config
│ │ │ └── config.go
│ │ ├── svc
│ │ │ └── serviceContext.go
│ │ └── logic
│ │ │ ├── ifAInBBlacklistLogic.go
│ │ │ ├── ifAInBFriendListLogic.go
│ │ │ └── getSingleConversationRecvMsgOptsLogic.go
│ │ └── etc
│ │ └── imuser.yaml
├── conversation
│ └── cmd
│ │ └── rpc
│ │ ├── internal
│ │ ├── config
│ │ │ └── config.go
│ │ ├── svc
│ │ │ └── serviceContext.go
│ │ ├── logic
│ │ │ └── modifyConversationFieldLogic.go
│ │ └── server
│ │ │ └── conversationServiceServer.go
│ │ ├── pb
│ │ └── gencode.sh
│ │ └── etc
│ │ └── conversation.yaml
├── msg-callback
│ └── cmd
│ │ └── rpc
│ │ ├── internal
│ │ ├── config
│ │ │ └── config.go
│ │ ├── svc
│ │ │ └── serviceContext.go
│ │ └── logic
│ │ │ ├── callbackWordFilterLogic.go
│ │ │ ├── callbackAfterSendGroupMsgLogic.go
│ │ │ ├── callbackBeforeSendGroupMsgLogic.go
│ │ │ ├── callbackAfterSendSuperGroupMsgLogic.go
│ │ │ ├── callbackAfterSendSingleMsgLogic.go
│ │ │ ├── callbackBeforeSendSingleMsgLogic.go
│ │ │ ├── callbackBeforeSendSuperGroupMsgLogic.go
│ │ │ └── callbackAtAllInSuperGroupLogic.go
│ │ ├── pb
│ │ └── gencode.sh
│ │ └── etc
│ │ └── msgcallback.yaml
├── msg-gateway
│ └── cmd
│ │ └── wsrpc
│ │ ├── internal
│ │ ├── rpcconfig
│ │ │ └── config.go
│ │ ├── types
│ │ │ └── types.go
│ │ ├── rpcsvc
│ │ │ └── serviceContext.go
│ │ ├── wslogic
│ │ │ └── init.go
│ │ ├── wsconfig
│ │ │ └── config.go
│ │ ├── handler
│ │ │ └── routes.go
│ │ ├── wssvc
│ │ │ └── servicecontext.go
│ │ └── rpclogic
│ │ │ └── getUsersOnlineStatusLogic.go
│ │ ├── pb
│ │ └── gencode.sh
│ │ └── etc
│ │ ├── msggateway-rpc.yaml
│ │ └── msggateway-ws.yaml
├── msg-push
│ └── cmd
│ │ └── rpc
│ │ ├── pb
│ │ ├── gencode.sh
│ │ └── msgpush.proto
│ │ ├── internal
│ │ ├── sdk
│ │ │ ├── push_interface.go
│ │ │ └── jpush
│ │ │ │ ├── requestBody
│ │ │ │ ├── options.go
│ │ │ │ ├── message.go
│ │ │ │ ├── pushObj.go
│ │ │ │ └── notification.go
│ │ │ │ └── common
│ │ │ │ └── JGPlatform.go
│ │ ├── config
│ │ │ └── config.go
│ │ └── svc
│ │ │ └── serviceContext.go
│ │ └── msgpushservice
│ │ └── msgPushService.go
└── msg-transfer
│ └── cmd
│ ├── history
│ ├── model
│ │ └── chatmsg.go
│ ├── internal
│ │ ├── repository
│ │ │ └── seq.go
│ │ ├── server
│ │ │ └── types.go
│ │ ├── svc
│ │ │ └── serviceContext.go
│ │ └── config
│ │ │ └── config.go
│ └── history.go
│ └── persistent
│ └── etc
│ └── persistent.yaml
├── README.md
├── .gitignore
└── deploy
└── local
└── prometheus
└── prometheus.yml
/goctl/goctl/model/sql/util/xx.sql:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/goctl/goctl/.gitignore:
--------------------------------------------------------------------------------
1 | .vscode
2 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/util/studeat.sql:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/util/student.sql:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/util/sub/sub.sql:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/util/xx.sql1:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/common/README.md:
--------------------------------------------------------------------------------
1 | # common
2 |
3 | 该项目的通用库
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/g4/test/apis/empty.api:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/tag.tpl:
--------------------------------------------------------------------------------
1 | `db:"{{.field}}"`
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/g4/test/apis/syntax.api:
--------------------------------------------------------------------------------
1 | syntax = "v1"
--------------------------------------------------------------------------------
/goctl/goctl/api/tsgen/handler.tpl:
--------------------------------------------------------------------------------
1 | {{.imports}}
2 |
3 | {{.apis}}
4 |
--------------------------------------------------------------------------------
/goctl/goctl/api/javagen/vars.go:
--------------------------------------------------------------------------------
1 | package javagen
2 |
3 | const modelDir = "model"
4 |
--------------------------------------------------------------------------------
/goctl/goctl/compare/testdata/unformat.api:
--------------------------------------------------------------------------------
1 | syntax = "v1"
2 |
3 | type Foo struct{}
4 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/etc.tpl:
--------------------------------------------------------------------------------
1 | Name: {{.serviceName}}
2 | Host: {{.host}}
3 | Port: {{.port}}
4 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/etc.tpl:
--------------------------------------------------------------------------------
1 | Name: {{.serviceName}}
2 | Host: {{.host}}
3 | Port: {{.port}}
4 |
--------------------------------------------------------------------------------
/common/xmgo/global/config.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | type MongoConfig struct {
4 | Uri string
5 | }
6 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/field.tpl:
--------------------------------------------------------------------------------
1 | {{.name}} {{.type}} {{.tag}} {{if .hasComment}}// {{.comment}}{{end}}
--------------------------------------------------------------------------------
/goctl/goctl/api/tsgen/components.tpl:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT.
2 |
3 | {{.componentTypes}}
4 |
--------------------------------------------------------------------------------
/common/xcache/global/interface.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | type IGetId interface {
4 | GetIdString() string
5 | }
6 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/interface-update.tpl:
--------------------------------------------------------------------------------
1 | Update(ctx context.Context, data *{{.upperStartCamelObject}}) error
--------------------------------------------------------------------------------
/common/xcache/dc/interface.go:
--------------------------------------------------------------------------------
1 | package dc
2 |
3 | type IDetailExpired interface {
4 | DetailExpiredSecond() int
5 | }
6 |
--------------------------------------------------------------------------------
/common/xcache/rc/interface.go:
--------------------------------------------------------------------------------
1 | package rc
2 |
3 | type IRelationExpired interface {
4 | RelationExpiredSecond() int
5 | }
6 |
--------------------------------------------------------------------------------
/common/xkafka/config.go:
--------------------------------------------------------------------------------
1 | package xkafka
2 |
3 | type ProducerConfig struct {
4 | Brokers []string
5 | Topic string
6 | }
7 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/import_api.api:
--------------------------------------------------------------------------------
1 | type ImportData struct {
2 | Name string `path:"name,options=you|me"`
3 | }
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/interface-delete.tpl:
--------------------------------------------------------------------------------
1 | Delete(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) error
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/interface-insert.tpl:
--------------------------------------------------------------------------------
1 | Insert(ctx context.Context, data *{{.upperStartCamelObject}}) (sql.Result,error)
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/api_has_no_request.api:
--------------------------------------------------------------------------------
1 | service A-api {
2 | @handler GreetHandler
3 | post /greet/ping ()
4 | }
--------------------------------------------------------------------------------
/app/msg/cmd/rpc/etc/ws.yaml:
--------------------------------------------------------------------------------
1 | Name: ws.rpc
2 | ListenOn: 127.0.0.1:8080
3 | Etcd:
4 | Hosts:
5 | - 127.0.0.1:2379
6 | Key: ws.rpc
7 |
--------------------------------------------------------------------------------
/goctl/goctl/api/tsgen/vars.go:
--------------------------------------------------------------------------------
1 | package tsgen
2 |
3 | const (
4 | packagePrefix = "components."
5 | pathPrefix = "pathPrefix"
6 | )
7 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/template/tag.go:
--------------------------------------------------------------------------------
1 | package template
2 |
3 | // Tag defines a tag template text
4 | const Tag = "`db:\"{{.field}}\"`"
5 |
--------------------------------------------------------------------------------
/goctl/goctl/migrate/cancel+polyfill.go:
--------------------------------------------------------------------------------
1 | //go:build windows
2 | // +build windows
3 |
4 | package migrate
5 |
6 | func cancelOnSignals() {
7 | }
8 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/route-addition.tpl:
--------------------------------------------------------------------------------
1 |
2 | server.AddRoutes(
3 | {{.routes}} {{.jwt}}{{.signature}} {{.prefix}} {{.timeout}}
4 | )
5 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/table-name.tpl:
--------------------------------------------------------------------------------
1 |
2 | func (m *default{{.upperStartCamelObject}}Model) tableName() string {
3 | return m.table
4 | }
5 |
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/g4/test/apis/info.api:
--------------------------------------------------------------------------------
1 | info(
2 | author: songmeizi
3 | desc: "the sample of
4 | info"
5 | date: "2020-01-06"
6 | )
7 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/interface-find-one-by-field.tpl:
--------------------------------------------------------------------------------
1 | FindOneBy{{.upperField}}(ctx context.Context, {{.in}}) (*{{.upperStartCamelObject}}, error)
--------------------------------------------------------------------------------
/goctl/goctl/compare/make.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | wd=`dirname $0`
4 | GOBIN="$GOPATH/bin"
5 | EXE=goctl-compare
6 | go build -o $EXE $wd
7 | mv $EXE $GOBIN
8 |
--------------------------------------------------------------------------------
/common/types/errors.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | import "github.com/showurl/Zero-IM-Server/common/xerr"
4 |
5 | var WSDataError = xerr.New(3001, "ws data error")
6 |
--------------------------------------------------------------------------------
/goctl/goctl/update/etc/update-api.json:
--------------------------------------------------------------------------------
1 | {
2 | "Name": "update-api",
3 | "ListenOn": "localhost:7777",
4 | "FileDir": ".",
5 | "FilePath": "/"
6 | }
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/interface-find-one.tpl:
--------------------------------------------------------------------------------
1 | FindOne(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) (*{{.upperStartCamelObject}}, error)
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/types.tpl:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT.
2 | package types{{if .containsTime}}
3 | import (
4 | "time"
5 | ){{end}}
6 | {{.types}}
7 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/generator/config.tpl:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import "github.com/zeromicro/go-zero/zrpc"
4 |
5 | type Config struct {
6 | zrpc.RpcServerConf
7 | }
8 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/err.tpl:
--------------------------------------------------------------------------------
1 | package {{.pkg}}
2 |
3 | import "github.com/zeromicro/go-zero/core/stores/sqlx"
4 |
5 | var ErrNotFound = sqlx.ErrNotFound
6 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/config.tpl:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import "github.com/zeromicro/go-zero/zrpc"
4 |
5 | type Config struct {
6 | zrpc.RpcServerConf
7 | }
8 |
--------------------------------------------------------------------------------
/app/auth/cmd/rpc/internal/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import "github.com/zeromicro/go-zero/zrpc"
4 |
5 | type Config struct {
6 | zrpc.RpcServerConf
7 | }
8 |
--------------------------------------------------------------------------------
/app/im-user/cmd/rpc/pb/gencode.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | goctl rpc protoc *.proto -v --go_out=.. --go-grpc_out=.. --zrpc_out=.. --style=goZero --home ../../../../../goctl/home
3 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/generator/etc.tpl:
--------------------------------------------------------------------------------
1 | Name: {{.serviceName}}.rpc
2 | ListenOn: 127.0.0.1:8080
3 | Etcd:
4 | Hosts:
5 | - 127.0.0.1:2379
6 | Key: {{.serviceName}}.rpc
7 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/rpc.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | import "github.com/emicklei/proto"
4 |
5 | // RPC embeds proto.RPC
6 | type RPC struct {
7 | *proto.RPC
8 | }
9 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/types.tpl:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT.
2 | package types{{if .containsTime}}
3 | import (
4 | "time"
5 | ){{end}}
6 | {{.types}}
7 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/etc.tpl:
--------------------------------------------------------------------------------
1 | Name: {{.serviceName}}.rpc
2 | ListenOn: 127.0.0.1:8080
3 | Etcd:
4 | Hosts:
5 | - 127.0.0.1:2379
6 | Key: {{.serviceName}}.rpc
7 |
--------------------------------------------------------------------------------
/app/im-user/cmd/rpc/internal/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import "github.com/zeromicro/go-zero/zrpc"
4 |
5 | type Config struct {
6 | zrpc.RpcServerConf
7 | }
8 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/generator/base/common.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package common;
4 | option go_package="./common";
5 |
6 | message User {
7 | string name = 1;
8 | }
9 |
--------------------------------------------------------------------------------
/app/auth/cmd/rpc/pb/gencode.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | goctl rpc protoc -I=./ auth.proto -v --go_out=.. --go-grpc_out=.. --zrpc_out=.. --style=goZero --home ../../../../../goctl/home
3 |
--------------------------------------------------------------------------------
/app/conversation/cmd/rpc/internal/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import "github.com/zeromicro/go-zero/zrpc"
4 |
5 | type Config struct {
6 | zrpc.RpcServerConf
7 | }
8 |
--------------------------------------------------------------------------------
/app/msg-callback/cmd/rpc/internal/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import "github.com/zeromicro/go-zero/zrpc"
4 |
5 | type Config struct {
6 | zrpc.RpcServerConf
7 | }
8 |
--------------------------------------------------------------------------------
/common/xorm/global/conf.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | type MysqlConfig struct {
4 | Addr string
5 | MaxIdleConns int
6 | MaxOpenConns int
7 | LogLevel string
8 | }
9 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/import.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | import "github.com/emicklei/proto"
4 |
5 | // Import embeds proto.Import
6 | type Import struct {
7 | *proto.Import
8 | }
9 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/option.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | import "github.com/emicklei/proto"
4 |
5 | // Option embeds proto.Option
6 | type Option struct {
7 | *proto.Option
8 | }
9 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/config.tpl:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import {{.authImport}}
4 |
5 | type Config struct {
6 | rest.RestConf
7 | {{.auth}}
8 | {{.jwtTrans}}
9 | }
10 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/message.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | import "github.com/emicklei/proto"
4 |
5 | // Message embeds proto.Message
6 | type Message struct {
7 | *proto.Message
8 | }
9 |
--------------------------------------------------------------------------------
/goctl/goctl/util/pathx/readlink+polyfill.go:
--------------------------------------------------------------------------------
1 | //go:build windows
2 | // +build windows
3 |
4 | package pathx
5 |
6 | func ReadLink(name string) (string, error) {
7 | return name, nil
8 | }
9 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/mongo/err.tpl:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import "errors"
4 |
5 | var ErrNotFound = errors.New("not found")
6 | var ErrInvalidObjectId = errors.New("invalid objectId")
7 |
--------------------------------------------------------------------------------
/app/conversation/cmd/rpc/pb/gencode.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | goctl rpc protoc -I=./ conversation.proto -v --go_out=.. --go-grpc_out=.. --zrpc_out=.. --style=goZero --home ../../../../../goctl/home
3 |
--------------------------------------------------------------------------------
/app/msg-callback/cmd/rpc/pb/gencode.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | goctl rpc protoc -I=./ msgcallback.proto -v --go_out=.. --go-grpc_out=.. --zrpc_out=.. --style=goZero --home ../../../../../goctl/home
3 |
--------------------------------------------------------------------------------
/goctl/goctl/model/mongo/template/error.tpl:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import "errors"
4 |
5 | var ErrNotFound = errors.New("not found")
6 | var ErrInvalidObjectId = errors.New("invalid objectId")
7 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/package.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | import "github.com/emicklei/proto"
4 |
5 | // Package defines the protobuf package.
6 | type Package struct {
7 | *proto.Package
8 | }
9 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/template/field.go:
--------------------------------------------------------------------------------
1 | package template
2 |
3 | // Field defines a filed template for types
4 | const Field = `{{.name}} {{.type}} {{.tag}} {{if .hasComment}}// {{.comment}}{{end}}`
5 |
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/internal/rpcconfig/config.go:
--------------------------------------------------------------------------------
1 | package rpcconfig
2 |
3 | import (
4 | "github.com/zeromicro/go-zero/zrpc"
5 | )
6 |
7 | type Config struct {
8 | zrpc.RpcServerConf
9 | }
10 |
--------------------------------------------------------------------------------
/common/utils/rand/int_test.go:
--------------------------------------------------------------------------------
1 | package randUtils
2 |
3 | import "testing"
4 |
5 | func TestRandInt(t *testing.T) {
6 | for i := 0; i < 100; i++ {
7 | t.Logf("%d", RandInt(0, 10))
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/test_option2.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package stream;
4 |
5 |
6 | message placeholder {}
7 |
8 | service greet {
9 | rpc hello (placeholder) returns (placeholder);
10 | }
--------------------------------------------------------------------------------
/app/msg-push/cmd/rpc/pb/gencode.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | goctl rpc protoc -I=./ -I=../../../../msg/cmd/rpc/pb msgpush.proto -v --go_out=.. --go-grpc_out=.. --zrpc_out=.. --style=goZero --home ../../../../../goctl/home
3 |
4 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/test/model/vars.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import "github.com/zeromicro/go-zero/core/stores/sqlx"
4 |
5 | // ErrNotFound types an alias for sqlx.ErrNotFound
6 | var ErrNotFound = sqlx.ErrNotFound
7 |
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/g4/ast/placeholder.go:
--------------------------------------------------------------------------------
1 | package ast
2 |
3 | // Holder defines a default instance for PlaceHolder
4 | var Holder PlaceHolder
5 |
6 | // PlaceHolder defines an empty struct
7 | type PlaceHolder struct{}
8 |
--------------------------------------------------------------------------------
/goctl/goctl/env/install.go:
--------------------------------------------------------------------------------
1 | package env
2 |
3 | import (
4 | "github.com/spf13/cobra"
5 | )
6 |
7 | func install(_ *cobra.Command, _ []string) error {
8 | return Prepare(true, boolVarForce, boolVarVerbose)
9 | }
10 |
--------------------------------------------------------------------------------
/common/xcache/dc/model_mapping_test.go:
--------------------------------------------------------------------------------
1 | package dc
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestDbMapping_FirstByID(t *testing.T) {
8 | db := GetDbMapping(nil, nil)
9 | db.FirstByID(nil, WithFieldId(""))
10 | }
11 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/util/newline.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import "strings"
4 |
5 | // TrimNewLine trims \r and \n chars.
6 | func TrimNewLine(s string) string {
7 | return strings.NewReplacer("\r", "", "\n", "").Replace(s)
8 | }
9 |
--------------------------------------------------------------------------------
/app/msg-push/cmd/rpc/internal/sdk/push_interface.go:
--------------------------------------------------------------------------------
1 | package sdk
2 |
3 | import "context"
4 |
5 | type OfflinePusher interface {
6 | Push(ctx context.Context, userIDList []string, alert, detailContent string) (resp string, err error)
7 | }
8 |
--------------------------------------------------------------------------------
/common/utils/num/contains.go:
--------------------------------------------------------------------------------
1 | package numUtils
2 |
3 | func IsContainInt32(target int32, List []int32) bool {
4 | for _, element := range List {
5 | if target == element {
6 | return true
7 | }
8 | }
9 | return false
10 | }
11 |
--------------------------------------------------------------------------------
/common/xcache/dc/list_option.go:
--------------------------------------------------------------------------------
1 | package dc
2 |
3 | func defaultListOption() *FirstOption {
4 | return &FirstOption{
5 | where: "",
6 | args: []interface{}{},
7 | keySuffix: "",
8 | fieldId: "id",
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/common/utils/str/contain.go:
--------------------------------------------------------------------------------
1 | package strUtils
2 |
3 | func IsContain(target string, List []string) bool {
4 | for _, element := range List {
5 |
6 | if target == element {
7 | return true
8 | }
9 | }
10 | return false
11 | }
12 |
--------------------------------------------------------------------------------
/common/xcache/global/key_utils.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | import (
4 | "strings"
5 | )
6 |
7 | func MergeKey(elements ...string) string {
8 | if len(elements) == 0 {
9 | return ""
10 | }
11 | return strings.Join(elements, ":")
12 | }
13 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/nest_type_api.api:
--------------------------------------------------------------------------------
1 | type Request {
2 | Name string `path:"name,options=you|me"`
3 | XXX struct {
4 | }
5 | }
6 |
7 | service A-api {
8 | @handler GreetHandler
9 | get /greet/from/:name(Request)
10 | }
--------------------------------------------------------------------------------
/goctl/goctl/bug/cmd.go:
--------------------------------------------------------------------------------
1 | package bug
2 |
3 | import "github.com/spf13/cobra"
4 |
5 | // Cmd describes a bug command.
6 | var Cmd = &cobra.Command{
7 | Use: "bug",
8 | Short: "Report a bug",
9 | Args: cobra.NoArgs,
10 | RunE: runE,
11 | }
12 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change log
2 |
3 | ## 2020-10-19
4 |
5 | * 增加template
6 |
7 | ## 2020-08-20
8 |
9 | * 新增支持通过连接数据库生成model
10 | * 支持数据库多表生成
11 | * 优化stringx
12 |
13 | ## 2020-08-19
14 |
15 | * 重构model代码生成逻辑
16 | * 实现从ddl解析表信息生成代码
17 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/template/errors.go:
--------------------------------------------------------------------------------
1 | package template
2 |
3 | // Error defines an error template
4 | const Error = `package {{.pkg}}
5 |
6 | import "github.com/zeromicro/go-zero/core/stores/sqlx"
7 |
8 | var ErrNotFound = sqlx.ErrNotFound
9 | `
10 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/call-interface-func.tpl:
--------------------------------------------------------------------------------
1 | {{if .hasComment}}{{.comment}}
2 | {{end}}{{.method}}(ctx context.Context{{if .hasReq}}, in *{{.pbRequest}}{{end}}, opts ...grpc.CallOption) ({{if .notStream}}*{{.pbResponse}}, {{else}}{{.streamBody}},{{end}} error)
--------------------------------------------------------------------------------
/app/msg-push/cmd/rpc/internal/sdk/jpush/requestBody/options.go:
--------------------------------------------------------------------------------
1 | package requestBody
2 |
3 | type Options struct {
4 | ApnsProduction bool `json:"apns_production"`
5 | }
6 |
7 | func (o *Options) SetApnsProduction(c bool) {
8 | o.ApnsProduction = c
9 | }
10 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/template/tablename.go:
--------------------------------------------------------------------------------
1 | package template
2 |
3 | // TableName defines a template that generate the tableName method.
4 | const TableName = `
5 | func (m *default{{.upperStartCamelObject}}Model) tableName() string {
6 | return m.table
7 | }
8 | `
9 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/test_option.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package stream;
4 |
5 | option go_package = "github.com/zeromicro/go-zero";
6 |
7 | message placeholder {}
8 |
9 | service greet {
10 | rpc hello (placeholder) returns (placeholder);
11 | }
--------------------------------------------------------------------------------
/goctl/goctl/upgrade/cmd.go:
--------------------------------------------------------------------------------
1 | package upgrade
2 |
3 | import "github.com/spf13/cobra"
4 |
5 | // Cmd describes a upgrade command.
6 | var Cmd = &cobra.Command{
7 | Use: "upgrade",
8 | Short: "Upgrade goctl to latest version",
9 | RunE: upgrade,
10 | }
11 |
--------------------------------------------------------------------------------
/common/utils/encrypt/md5.go:
--------------------------------------------------------------------------------
1 | package encrypt
2 |
3 | import (
4 | "crypto/md5"
5 | "encoding/hex"
6 | )
7 |
8 | func Md5(s string) string {
9 | h := md5.New()
10 | h.Write([]byte(s))
11 | cipher := h.Sum(nil)
12 | return hex.EncodeToString(cipher)
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/test_invalid_response.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package test;
4 | option go_package = "go";
5 |
6 | import "base.proto";
7 |
8 | message Req{}
9 |
10 |
11 | service TestService {
12 | rpc TestRpcTwo (Req) returns (base.Reply);
13 | }
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/test_invalid_request.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package test;
4 | option go_package = "go";
5 |
6 | import "base.proto";
7 |
8 | message Reply{}
9 |
10 |
11 | service TestService {
12 | rpc TestRpcTwo (base.Req) returns (Reply);
13 | }
--------------------------------------------------------------------------------
/goctl/goctl/rpc/generator/svc.tpl:
--------------------------------------------------------------------------------
1 | package svc
2 |
3 | import {{.imports}}
4 |
5 | type ServiceContext struct {
6 | Config config.Config
7 | }
8 |
9 | func NewServiceContext(c config.Config) *ServiceContext {
10 | return &ServiceContext{
11 | Config:c,
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/model-gen.tpl:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT!
2 |
3 | package {{.pkg}}
4 | {{.imports}}
5 | {{.vars}}
6 | {{.types}}
7 | {{.new}}
8 | {{.insert}}
9 | {{.find}}
10 | {{.update}}
11 | {{.delete}}
12 | {{.extraMethod}}
13 | {{.tableName}}
14 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/svc.tpl:
--------------------------------------------------------------------------------
1 | package svc
2 |
3 | import {{.imports}}
4 |
5 | type ServiceContext struct {
6 | Config config.Config
7 | }
8 |
9 | func NewServiceContext(c config.Config) *ServiceContext {
10 | return &ServiceContext{
11 | Config:c,
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/common/xcache/global/db.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | type DB int
4 |
5 | func (d DB) Int() int {
6 | return int(d)
7 | }
8 |
9 | const (
10 | DB0Default DB = iota // 默认
11 | DB1Token // Token
12 | DB2String // String
13 | DB2ZSet // ZSet
14 | )
15 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/service.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | import "github.com/emicklei/proto"
4 |
5 | // Service describes the rpc service, which is the relevant
6 | // content after the translation of the proto file
7 | type Service struct {
8 | *proto.Service
9 | RPC []*RPC
10 | }
11 |
--------------------------------------------------------------------------------
/goctl/goctl/update/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import "github.com/zeromicro/go-zero/core/logx"
4 |
5 | // Config defines a service configure for goctl update
6 | type Config struct {
7 | logx.LogConf
8 | ListenOn string
9 | FileDir string
10 | FilePath string
11 | }
12 |
--------------------------------------------------------------------------------
/common/xerr/errcode.go:
--------------------------------------------------------------------------------
1 | package xerr
2 |
3 | // 成功返回
4 | const OK = 200
5 |
6 | // 全局错误码
7 | // 前3位代表业务,后三位代表具体功能
8 | const BAD_REUQEST_ERROR = 500
9 | const REUQES_PARAM_ERROR = 400
10 |
11 | // usercenter
12 | const USER_NOT_EXIST = 10001
13 |
14 | // auth
15 | const AUTH_ERROR = 20001
16 |
--------------------------------------------------------------------------------
/goctl/goctl/api/new/api.tpl:
--------------------------------------------------------------------------------
1 | type Request {
2 | Name string `path:"name,options=you|me"`
3 | }
4 |
5 | type Response {
6 | Message string `json:"message"`
7 | }
8 |
9 | service {{.name}}-api {
10 | @handler {{.handler}}Handler
11 | get /from/:name(Request) returns (Response)
12 | }
13 |
--------------------------------------------------------------------------------
/goctl/goctl/goctl.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/zeromicro/go-zero/core/load"
5 | "github.com/zeromicro/go-zero/core/logx"
6 | "github.com/zeromicro/go-zero/tools/goctl/cmd"
7 | )
8 |
9 | func main() {
10 | logx.Disable()
11 | load.Disable()
12 | cmd.Execute()
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/comment.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | import "github.com/emicklei/proto"
4 |
5 | // GetComment returns content with prefix //
6 | func GetComment(comment *proto.Comment) string {
7 | if comment == nil {
8 | return ""
9 | }
10 | return "// " + comment.Message()
11 | }
12 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/proto.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | // Proto describes a proto file,
4 | type Proto struct {
5 | Src string
6 | Name string
7 | Package Package
8 | PbPackage string
9 | GoPackage string
10 | Import []Import
11 | Message []Message
12 | Service Service
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/newapi/newtemplate.tpl:
--------------------------------------------------------------------------------
1 | type Request {
2 | Name string `path:"name,options=you|me"`
3 | }
4 |
5 | type Response {
6 | Message string `json:"message"`
7 | }
8 |
9 | service {{.name}}-api {
10 | @handler {{.handler}}Handler
11 | get /from/:name(Request) returns (Response)
12 | }
13 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Zero-IM-Server
2 | 基于 [Open-IM-Server](https://github.com/OpenIMSDK/Open-IM-Server) 实现的 IM 服务
3 |
4 | ## 修改部分
5 | ### 服务注册发现
6 | > 使用go-zero微服务框架 开发更方便 自带 `链路追踪` `服务发现` `服务负载`
7 |
8 | 
9 |
10 | > 不依赖 `mysql` 所有业务逻辑均请求业务rpc服务
11 |
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/pb/gencode.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | goctl rpc protoc -I=./ -I=../../../../msg/cmd/rpc/pb msg-gateway.proto -v --go_out=.. --go-grpc_out=.. --zrpc_out=.. --style=goZero --home ../../../../../goctl/home
3 | #protoc -I=../../../../msg/cmd/rpc/pb msg-gateway.proto --proto_path ./ --go_out .. --go-grpc_out ..
4 |
--------------------------------------------------------------------------------
/app/msg-transfer/cmd/history/model/chatmsg.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | type MsgInfo struct {
4 | SendTime int64
5 | Msg []byte
6 | }
7 |
8 | type UserChat struct {
9 | UID string
10 | Msg []MsgInfo
11 | }
12 |
13 | type GroupChat struct {
14 | GroupID string `bson:"groupid"`
15 | Msg []MsgInfo
16 | }
17 |
--------------------------------------------------------------------------------
/goctl/goctl/internal/errorx/errorx._test.go:
--------------------------------------------------------------------------------
1 | package errorx
2 |
3 | import (
4 | "errors"
5 | "testing"
6 |
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestWrap(t *testing.T) {
11 | err := errors.New("foo")
12 | err = Wrap(err)
13 | _, ok := err.(*GoctlError)
14 | assert.True(t, ok)
15 | }
16 |
--------------------------------------------------------------------------------
/common/xorm/where.go:
--------------------------------------------------------------------------------
1 | package xorm
2 |
3 | type GormWhere struct {
4 | Where string
5 | args []interface{}
6 | }
7 |
8 | func NewGormWhere() []GormWhere {
9 | return make([]GormWhere, 0)
10 | }
11 |
12 | func Where(where string, args ...interface{}) GormWhere {
13 | return GormWhere{Where: where, args: args}
14 | }
15 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/anonymous_annotation.api:
--------------------------------------------------------------------------------
1 | type Request struct {
2 | Name string `path:"name,options=you|me"`
3 | }
4 |
5 | type Response struct {
6 | Message string `json:"message"`
7 | }
8 |
9 | service A-api {
10 | @handler GreetHandler
11 | get /greet/from/:name(Request) returns (Response)
12 | }
--------------------------------------------------------------------------------
/goctl/goctl/rpc/generator/rpc.tpl:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package {{.package}};
4 | option go_package="./{{.package}}";
5 |
6 | message Request {
7 | string ping = 1;
8 | }
9 |
10 | message Response {
11 | string pong = 1;
12 | }
13 |
14 | service {{.serviceName}} {
15 | rpc Ping(Request) returns(Response);
16 | }
17 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/routes.tpl:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT.
2 | package handler
3 |
4 | import (
5 | "net/http"{{if .hasTimeout}}
6 | "time"{{end}}
7 |
8 | {{.importPackages}}
9 | )
10 |
11 | func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
12 | {{.routesAdditions}}
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/template.tpl:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package {{.package}};
4 | option go_package="./{{.package}}";
5 |
6 | message Request {
7 | string ping = 1;
8 | }
9 |
10 | message Response {
11 | string pong = 1;
12 | }
13 |
14 | service {{.serviceName}} {
15 | rpc Ping(Request) returns(Response);
16 | }
17 |
--------------------------------------------------------------------------------
/goctl/goctl/api/javagen/bool.tpl:
--------------------------------------------------------------------------------
1 |
2 | {{.indent}}{{.decorator}}
3 | {{.indent}}public {{.returnType}} is{{.property}}() {
4 | {{.indent}} return this.{{.tagValue}};
5 | {{.indent}}}
6 |
7 | {{.indent}}public void set{{.property}}({{.type}} {{.propertyValue}}) {
8 | {{.indent}} this.{{.tagValue}} = {{.propertyValue}};
9 | {{.indent}}}
10 |
--------------------------------------------------------------------------------
/goctl/goctl/api/javagen/getset.tpl:
--------------------------------------------------------------------------------
1 |
2 | {{.indent}}{{.decorator}}
3 | {{.indent}}public {{.returnType}} get{{.property}}() {
4 | {{.indent}} return this.{{.tagValue}};
5 | {{.indent}}}
6 |
7 | {{.indent}}public void set{{.property}}({{.type}} {{.propertyValue}}) {
8 | {{.indent}} this.{{.tagValue}} = {{.propertyValue}};
9 | {{.indent}}}
10 |
--------------------------------------------------------------------------------
/app/auth/cmd/rpc/internal/svc/serviceContext.go:
--------------------------------------------------------------------------------
1 | package svc
2 |
3 | import "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/internal/config"
4 |
5 | type ServiceContext struct {
6 | Config config.Config
7 | }
8 |
9 | func NewServiceContext(c config.Config) *ServiceContext {
10 | return &ServiceContext{
11 | Config: c,
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/goctl/api/docgen/markdown.tpl:
--------------------------------------------------------------------------------
1 | ### {{.index}}. {{.routeComment}}
2 |
3 | 1. route definition
4 |
5 | - Url: {{.uri}}
6 | - Method: {{.method}}
7 | - Request: {{.requestType}}
8 | - Response: {{.responseType}}
9 |
10 | 2. request definition
11 |
12 | {{.requestContent}}
13 |
14 | 3. response definition
15 |
16 | {{.responseContent}}
17 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/svc.tpl:
--------------------------------------------------------------------------------
1 | package svc
2 |
3 | import (
4 | {{.configImport}}
5 | )
6 |
7 | type ServiceContext struct {
8 | Config {{.config}}
9 | {{.middleware}}
10 | }
11 |
12 | func NewServiceContext(c {{.config}}) *ServiceContext {
13 | return &ServiceContext{
14 | Config: c,
15 | {{.middlewareAssignment}}
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/util/slice.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | // TrimStringSlice returns a copy slice without empty string item
4 | func TrimStringSlice(list []string) []string {
5 | var out []string
6 | for _, item := range list {
7 | if len(item) == 0 {
8 | continue
9 | }
10 | out = append(out, item)
11 | }
12 | return out
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/goctl/model/mongo/template/template.go:
--------------------------------------------------------------------------------
1 | package template
2 |
3 | import _ "embed"
4 |
5 | // Text provides the default template for model to generate.
6 | //go:embed model.tpl
7 | var Text string
8 |
9 | // Error provides the default template for error definition in mongo code generation.
10 | //go:embed error.tpl
11 | var Error string
12 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/context.tpl:
--------------------------------------------------------------------------------
1 | package svc
2 |
3 | import (
4 | {{.configImport}}
5 | )
6 |
7 | type ServiceContext struct {
8 | Config {{.config}}
9 | {{.middleware}}
10 | }
11 |
12 | func NewServiceContext(c {{.config}}) *ServiceContext {
13 | return &ServiceContext{
14 | Config: c,
15 | {{.middlewareAssignment}}
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/im-user/cmd/rpc/internal/svc/serviceContext.go:
--------------------------------------------------------------------------------
1 | package svc
2 |
3 | import "github.com/showurl/Zero-IM-Server/app/im-user/cmd/rpc/internal/config"
4 |
5 | type ServiceContext struct {
6 | Config config.Config
7 | }
8 |
9 | func NewServiceContext(c config.Config) *ServiceContext {
10 | return &ServiceContext{
11 | Config: c,
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/ap_ino_info.api:
--------------------------------------------------------------------------------
1 | type Request struct {
2 | Name string `path:"name,options=you|me"`
3 | }
4 |
5 | type Response struct {
6 | Message string `json:"message"`
7 | }
8 |
9 | service A-api {
10 | @server(
11 | handler: GreetHandler
12 | )
13 | get /greet/from/:name(Request) returns (Response)
14 | }
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/invalid_api_file.api:
--------------------------------------------------------------------------------
1 | type Request struct {
2 | Name string `path:"name,options=you|me"`
3 | }
4 |
5 | type Response struct {
6 | Message string `json:"message"`
7 | }
8 |
9 | service A-api
10 | @server(
11 | handler: GreetHandler
12 | )
13 | get /greet/from/:name(Request) returns (Response)
14 | }
--------------------------------------------------------------------------------
/common/ctxdata/ctxData.go:
--------------------------------------------------------------------------------
1 | package ctxdata
2 |
3 | import (
4 | "context"
5 | )
6 |
7 | // CtxKeyJwtUserId get uid from ctx
8 | var CtxKeyJwtUserId = "jwtUserId"
9 |
10 | func GetUidFromCtx(ctx context.Context) int64 {
11 | var uid int64
12 | if jsonUid, ok := ctx.Value(CtxKeyJwtUserId).(int64); ok {
13 | uid = jsonUid
14 | }
15 | return uid
16 | }
17 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/model-new.tpl:
--------------------------------------------------------------------------------
1 |
2 | func new{{.upperStartCamelObject}}Model(conn sqlx.SqlConn{{if .withCache}}, c cache.CacheConf{{end}}) *default{{.upperStartCamelObject}}Model {
3 | return &default{{.upperStartCamelObject}}Model{
4 | {{if .withCache}}CachedConn: sqlc.NewConn(conn, c){{else}}conn:conn{{end}},
5 | table: {{.table}},
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/app/conversation/cmd/rpc/internal/svc/serviceContext.go:
--------------------------------------------------------------------------------
1 | package svc
2 |
3 | import "github.com/showurl/Zero-IM-Server/app/conversation/cmd/rpc/internal/config"
4 |
5 | type ServiceContext struct {
6 | Config config.Config
7 | }
8 |
9 | func NewServiceContext(c config.Config) *ServiceContext {
10 | return &ServiceContext{
11 | Config: c,
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/app/msg-callback/cmd/rpc/internal/svc/serviceContext.go:
--------------------------------------------------------------------------------
1 | package svc
2 |
3 | import "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/internal/config"
4 |
5 | type ServiceContext struct {
6 | Config config.Config
7 | }
8 |
9 | func NewServiceContext(c config.Config) *ServiceContext {
10 | return &ServiceContext{
11 | Config: c,
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/internal/types/types.go:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT.
2 | package types
3 |
4 | type Request struct {
5 | Token string `form:"token"`
6 | SendID string `form:"sendID"`
7 | PlatformID string `form:"platformID"`
8 | }
9 | type Response struct {
10 | Uid string
11 | ErrMsg string
12 | Success bool
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/goctl/compare/testdata/kotlin.api:
--------------------------------------------------------------------------------
1 | syntax = "v1"
2 |
3 | info(
4 | title: "type title here"
5 | desc: "type desc here"
6 | author: "type author here"
7 | email: "type email here"
8 | version: "type version here"
9 | )
10 |
11 | type req{}
12 | type reply{}
13 |
14 | service kotlin-api{
15 | @handler ping
16 | post /ping
17 | }
18 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/types.tpl:
--------------------------------------------------------------------------------
1 |
2 | type (
3 | {{.lowerStartCamelObject}}Model interface{
4 | {{.method}}
5 | }
6 |
7 | default{{.upperStartCamelObject}}Model struct {
8 | {{if .withCache}}sqlc.CachedConn{{else}}conn sqlx.SqlConn{{end}}
9 | table string
10 | }
11 |
12 | {{.upperStartCamelObject}} struct {
13 | {{.fields}}
14 | }
15 | )
16 |
--------------------------------------------------------------------------------
/common/utils/rand/int.go:
--------------------------------------------------------------------------------
1 | package randUtils
2 |
3 | import (
4 | "math/rand"
5 | "time"
6 | )
7 |
8 | // RandInt 随机int
9 | func RandInt(i int, j int) int {
10 | rand.Seed(time.Now().UnixNano())
11 | return i + rand.Intn(j-i)
12 | }
13 |
14 | func RandInt64(i int64, j int64) int64 {
15 | rand.Seed(time.Now().UnixNano())
16 | return i + rand.Int63n(j-i)
17 | }
18 |
--------------------------------------------------------------------------------
/goctl/goctl/env/env.go:
--------------------------------------------------------------------------------
1 | package env
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/spf13/cobra"
7 | "github.com/zeromicro/go-zero/tools/goctl/pkg/env"
8 | )
9 |
10 | func write(_ *cobra.Command, _ []string) error {
11 | if len(sliceVarWriteValue) > 0 {
12 | return env.WriteEnv(sliceVarWriteValue)
13 | }
14 | fmt.Println(env.Print())
15 | return nil
16 | }
17 |
--------------------------------------------------------------------------------
/common/utils/time/now.go:
--------------------------------------------------------------------------------
1 | package timeUtils
2 |
3 | import (
4 | "time"
5 | )
6 |
7 | func NowStrDatetime() string {
8 | return Now().Format("2006-01-02 15:04:05")
9 | }
10 |
11 | func Now() time.Time {
12 | return time.Now()
13 | }
14 |
15 | //Get the current timestamp by Mill
16 | func GetCurrentTimestampByMill() int64 {
17 | return Now().UnixNano() / 1e6
18 | }
19 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/import-no-cache.tpl:
--------------------------------------------------------------------------------
1 | import (
2 | "context"
3 | "database/sql"
4 | "fmt"
5 | "strings"
6 | {{if .time}}"time"{{end}}
7 |
8 | "github.com/zeromicro/go-zero/core/stores/builder"
9 | "github.com/zeromicro/go-zero/core/stores/sqlc"
10 | "github.com/zeromicro/go-zero/core/stores/sqlx"
11 | "github.com/zeromicro/go-zero/core/stringx"
12 | )
13 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/api_jwt.api:
--------------------------------------------------------------------------------
1 | type Request struct {
2 | Name string `path:"name,options=you|me"`
3 | }
4 |
5 | type Response struct {
6 | Message string `json:"message"`
7 | }
8 |
9 | @server(
10 | jwt: Auth
11 | signature: true
12 | )
13 | service A-api {
14 | @handler GreetHandler
15 | get /greet/from/:name(Request) returns (Response)
16 | }
--------------------------------------------------------------------------------
/common/utils/test/output.go:
--------------------------------------------------------------------------------
1 | package testUtils
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "github.com/showurl/Zero-IM-Server/common/fastjson"
7 | )
8 |
9 | func OutputJson(v interface{}) string {
10 | buf, _ := fastjson.Marshal(v)
11 | var bb bytes.Buffer
12 | _ = json.Indent(&bb, buf, "", " ")
13 | s := bb.String()
14 | //fmt.Println(s)
15 | return s
16 | }
17 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/api_has_middleware.api:
--------------------------------------------------------------------------------
1 | type Request struct {
2 | Name string `path:"name,options=you|me"`
3 | }
4 |
5 | type Response struct {
6 | Message string `json:"message"`
7 | }
8 |
9 | @server(
10 | middleware: TokenValidate
11 | )
12 | service A-api {
13 | @handler GreetHandler
14 | get /greet/from/:name(Request) returns (Response)
15 | }
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/stream.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package test;
4 |
5 | message Req{
6 | string input = 1;
7 | }
8 |
9 | message Reply{
10 | string output = 1;
11 | }
12 | service TestService{
13 | rpc ServerStream (Req) returns (stream Reply);
14 | rpc ClientStream (stream Req) returns (Reply);
15 | rpc Stream (stream Req) returns (stream Reply);
16 | }
17 |
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/internal/rpcsvc/serviceContext.go:
--------------------------------------------------------------------------------
1 | package rpcsvc
2 |
3 | import (
4 | "github.com/showurl/Zero-IM-Server/app/msg-gateway/cmd/wsrpc/internal/rpcconfig"
5 | )
6 |
7 | type ServiceContext struct {
8 | Config rpcconfig.Config
9 | }
10 |
11 | func NewServiceContext(c rpcconfig.Config) *ServiceContext {
12 | return &ServiceContext{
13 | Config: c,
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/app/msg-push/cmd/rpc/pb/msgpush.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | option go_package = "./pb";
4 | import "ws.proto";
5 | package pb;
6 |
7 | message PushMsgReq {
8 | server_api_params.MsgData msgData = 2;
9 | string pushToUserID = 3;
10 | }
11 | message PushMsgResp{
12 | int32 ResultCode = 1;
13 | }
14 | service msgPushService {
15 | rpc PushMsg(PushMsgReq) returns (PushMsgResp);
16 | }
--------------------------------------------------------------------------------
/common/fastjson/fastjson.go:
--------------------------------------------------------------------------------
1 | package fastjson
2 |
3 | import (
4 | "encoding/json"
5 | jsoniter "github.com/json-iterator/go"
6 | )
7 |
8 | var fJson = jsoniter.ConfigCompatibleWithStandardLibrary
9 |
10 | func Marshal(v interface{}) ([]byte, error) {
11 | return json.Marshal(v)
12 | }
13 |
14 | func Unmarshal(data []byte, v interface{}) error {
15 | return fJson.Unmarshal(data, v)
16 | }
17 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/has_import_api.api:
--------------------------------------------------------------------------------
1 | import "importApi.api"
2 |
3 | type Request struct {
4 | Name string `path:"name,options=you|me"`
5 | }
6 |
7 | type Response struct {
8 | Message string `json:"message"` // message
9 | }
10 |
11 | service A-api {
12 | @server(
13 | handler: GreetHandler
14 | )
15 | get /greet/from/:name(Request) returns (Response)
16 | }
--------------------------------------------------------------------------------
/goctl/goctl/plugin/demo/goctlplugin.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/zeromicro/go-zero/tools/goctl/plugin"
7 | )
8 |
9 | func main() {
10 | plugin, err := plugin.NewPlugin()
11 | if err != nil {
12 | panic(err)
13 | }
14 |
15 | if plugin.Api != nil {
16 | fmt.Printf("api: %+v \n", plugin.Api)
17 | }
18 | fmt.Println("Enjoy anything you want.")
19 | }
20 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/logic-func.tpl:
--------------------------------------------------------------------------------
1 | {{if .hasComment}}{{.comment}}{{end}}
2 | func (l *{{.logicName}}) {{.method}} ({{if .hasReq}}in {{.request}}{{if .stream}},stream {{.streamBody}}{{end}}{{else}}stream {{.streamBody}}{{end}}) ({{if .hasReply}}{{.response}},{{end}} error) {
3 | // todo: add your logic here and delete this line
4 |
5 | return {{if .hasReply}}&{{.responseType}}{},{{end}} nil
6 | }
7 |
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/internal/wslogic/init.go:
--------------------------------------------------------------------------------
1 | package wslogic
2 |
3 | import (
4 | "github.com/go-playground/validator/v10"
5 | "sync"
6 | )
7 |
8 | var (
9 | rwLock *sync.RWMutex
10 | validate *validator.Validate
11 | sendMsgAllCount uint64
12 | userCount uint64
13 | )
14 |
15 | func init() {
16 | rwLock = new(sync.RWMutex)
17 | validate = validator.New()
18 | }
19 |
--------------------------------------------------------------------------------
/app/auth/cmd/rpc/etc/auth.yaml:
--------------------------------------------------------------------------------
1 | Name: auth-rpc
2 | ListenOn: 192.168.2.77:10160
3 |
4 | Log:
5 | ServiceName: auth-rpc
6 | Level: info
7 |
8 | Prometheus:
9 | Host: 0.0.0.0
10 | Port: 10161
11 | Path: /metrics
12 |
13 | Telemetry:
14 | Name: auth-rpc
15 | #Endpoint: http://jaeger:14268/api/traces
16 | Endpoint: http://127.0.0.1:14268/api/traces
17 | Sampler: 1.0
18 | Batcher: jaeger
19 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/no_struct_tag_api.api:
--------------------------------------------------------------------------------
1 | type Request {
2 | Name string `path:"name,options=you|me"`
3 | }
4 |
5 | type XXX {}
6 |
7 | type (
8 | Response {
9 | Message string `json:"message"`
10 | }
11 |
12 | A {}
13 |
14 | B struct {}
15 | )
16 |
17 | service A-api {
18 | @handler GreetHandler
19 | get /greet/from/:name(Request) returns (Response)
20 | }
--------------------------------------------------------------------------------
/app/msg-push/cmd/rpc/internal/sdk/jpush/common/JGPlatform.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import (
4 | "encoding/base64"
5 | "fmt"
6 | )
7 |
8 | func GetAuthorization(Appkey string, MasterSecret string) string {
9 | str := fmt.Sprintf("%s:%s", Appkey, MasterSecret)
10 | buf := []byte(str)
11 | Authorization := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString(buf))
12 | return Authorization
13 | }
14 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/vars.go:
--------------------------------------------------------------------------------
1 | package gogen
2 |
3 | const (
4 | interval = "internal/"
5 | typesPacket = "types"
6 | configDir = interval + "config"
7 | contextDir = interval + "svc"
8 | handlerDir = interval + "handler"
9 | logicDir = interval + "logic"
10 | middlewareDir = interval + "middleware"
11 | typesDir = interval + typesPacket
12 | groupProperty = "group"
13 | )
14 |
--------------------------------------------------------------------------------
/app/im-user/cmd/rpc/etc/imuser.yaml:
--------------------------------------------------------------------------------
1 | Name: imuser-rpc
2 | ListenOn: 192.168.2.77:10240
3 |
4 | Log:
5 | ServiceName: imuser-rpc
6 | Level: info
7 |
8 | Prometheus:
9 | Host: 0.0.0.0
10 | Port: 10241
11 | Path: /metrics
12 |
13 | Telemetry:
14 | Name: imuser-rpc
15 | #Endpoint: http://jaeger:14268/api/traces
16 | Endpoint: http://127.0.0.1:14268/api/traces
17 | Sampler: 1.0
18 | Batcher: jaeger
19 |
--------------------------------------------------------------------------------
/common/utils/map.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | func GetSwitchFromOptions(Options map[string]bool, key string) (result bool) {
4 | if flag, ok := Options[key]; !ok || flag {
5 | return true
6 | }
7 | return false
8 | }
9 |
10 | func SetSwitchFromOptions(options map[string]bool, key string, value bool) {
11 | if options == nil {
12 | options = make(map[string]bool, 5)
13 | }
14 | options[key] = value
15 | }
16 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/has_inline_no_exist_test.api:
--------------------------------------------------------------------------------
1 | type Request struct {
2 | Inline
3 | Name string `path:"name,options=you|me"`
4 | }
5 |
6 | type Response struct {
7 | Message string `json:"message"` // message
8 | }
9 |
10 | service A-api {
11 | @doc ("helloworld")
12 | @server(
13 | handler: GreetHandler
14 | )
15 | get /greet/from/:name(Request) returns (Response)
16 | }
--------------------------------------------------------------------------------
/goctl/goctl/api/spec/validate.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | import "errors"
4 |
5 | var ErrMissingService = errors.New("missing service")
6 |
7 | // Validate validates Validate the integrity of the spec.
8 | func (s *ApiSpec) Validate() error {
9 | if len(s.Service.Name) == 0 {
10 | return ErrMissingService
11 | }
12 | if len(s.Service.Groups) == 0 {
13 | return ErrMissingService
14 | }
15 | return nil
16 | }
17 |
--------------------------------------------------------------------------------
/goctl/goctl/pkg/golang/install.go:
--------------------------------------------------------------------------------
1 | package golang
2 |
3 | import (
4 | "os"
5 | "os/exec"
6 | )
7 |
8 | func Install(git string) error {
9 | cmd := exec.Command("go", "install", git)
10 | env := os.Environ()
11 | env = append(env, "GO111MODULE=on", "GOPROXY=https://goproxy.cn,direct")
12 | cmd.Env = env
13 | cmd.Stdout = os.Stdout
14 | cmd.Stderr = os.Stderr
15 | err := cmd.Run()
16 | return err
17 | }
18 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/import.tpl:
--------------------------------------------------------------------------------
1 | import (
2 | "context"
3 | "database/sql"
4 | "fmt"
5 | "strings"
6 | {{if .time}}"time"{{end}}
7 |
8 | "github.com/zeromicro/go-zero/core/stores/builder"
9 | "github.com/zeromicro/go-zero/core/stores/cache"
10 | "github.com/zeromicro/go-zero/core/stores/sqlc"
11 | "github.com/zeromicro/go-zero/core/stores/sqlx"
12 | "github.com/zeromicro/go-zero/core/stringx"
13 | )
14 |
--------------------------------------------------------------------------------
/app/msg/cmd/rpc/pb/gencode.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | goctl rpc protoc -I=./ chat.proto -v --go_out=.. --go-grpc_out=.. --zrpc_out=.. --style=goZero --home ../../../../../goctl/home
3 | goctl rpc protoc -I=./ ws.proto -v --go_out=.. --go-grpc_out=.. --zrpc_out=.. --style=goZero --home ../../../../../goctl/home
4 | sed -i "" 's#pb "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/pb"##g' chat.pb.go
5 | sed -i "" 's#pb.##g' chat.pb.go
6 |
--------------------------------------------------------------------------------
/common/xerr/errmsg.go:
--------------------------------------------------------------------------------
1 | package xerr
2 |
3 | var message map[int]string
4 |
5 | func init() {
6 | message = make(map[int]string)
7 | message[OK] = "SUCCESS"
8 | message[BAD_REUQEST_ERROR] = "服务器繁忙,请稍后再试"
9 | message[REUQES_PARAM_ERROR] = "参数错误"
10 | }
11 |
12 | func MapErrMsg(errcode int) string {
13 | if msg, ok := message[errcode]; ok {
14 | return msg
15 | } else {
16 | return "服务器繁忙,请稍后再试"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/api_jwt_with_middleware.api:
--------------------------------------------------------------------------------
1 | type Request struct {
2 | Name string `path:"name,options=you|me"`
3 | }
4 |
5 | type Response struct {
6 | Message string `json:"message"`
7 | }
8 |
9 | @server(
10 | jwt: Auth
11 | jwtTransition: Trans
12 | middleware: TokenValidate
13 | )
14 | service A-api {
15 | @handler GreetHandler
16 | get /greet/from/:name(Request) returns (Response)
17 | }
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/internal/wsconfig/config.go:
--------------------------------------------------------------------------------
1 | package wsconfig
2 |
3 | import (
4 | "github.com/zeromicro/go-zero/rest"
5 | "github.com/zeromicro/go-zero/zrpc"
6 | )
7 |
8 | type Config struct {
9 | rest.RestConf
10 | AuthRpc zrpc.RpcClientConf
11 | MsgRpc zrpc.RpcClientConf
12 | Websocket WebsocketConfig
13 | }
14 | type WebsocketConfig struct {
15 | MaxConnNum int
16 | TimeOut int
17 | MaxMsgLen int
18 | }
19 |
--------------------------------------------------------------------------------
/app/msg-transfer/cmd/persistent/etc/persistent.yaml:
--------------------------------------------------------------------------------
1 | Name: msgtransfer-persistent
2 |
3 | Log:
4 | ServiceName: msgtransfer-persistent
5 | Level: info
6 |
7 | Prometheus:
8 | Host: 0.0.0.0
9 | Port: 10261
10 | Path: /metrics
11 |
12 | Telemetry:
13 | Name: msgtransfer-persistent
14 | #Endpoint: http://jaeger:14268/api/traces
15 | Endpoint: http://127.0.0.1:14268/api/traces
16 | Sampler: 1.0
17 | Batcher: jaeger
18 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/parser/test.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package test;
4 | option go_package = "go";
5 |
6 | import "base.proto";
7 |
8 | message TestMessage{}
9 | message TestReq{}
10 | message TestReply{}
11 | message Inline {
12 | message Inner{}
13 | }
14 |
15 | enum TestEnum {
16 | unknown = 0;
17 | male = 1;
18 | female = 2;
19 | }
20 |
21 | service TestService{
22 | rpc TestRpcOne (TestReq)returns(TestReply);
23 | }
--------------------------------------------------------------------------------
/app/msg-callback/cmd/rpc/etc/msgcallback.yaml:
--------------------------------------------------------------------------------
1 | Name: msgcallback-rpc
2 | ListenOn: 192.168.2.77:10250
3 |
4 | Log:
5 | ServiceName: msgcallback-rpc
6 | Level: info
7 |
8 | Prometheus:
9 | Host: 0.0.0.0
10 | Port: 10251
11 | Path: /metrics
12 |
13 | Telemetry:
14 | Name: msgcallback-rpc
15 | #Endpoint: http://jaeger:14268/api/traces
16 | Endpoint: http://127.0.0.1:14268/api/traces
17 | Sampler: 1.0
18 | Batcher: jaeger
19 |
--------------------------------------------------------------------------------
/app/auth/cmd/rpc/pb/auth.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | option go_package = "./pb";
4 |
5 | package pb;
6 |
7 | message VerifyTokenReq {
8 | string token = 1;
9 | string platform = 2;
10 | string sendID = 3;
11 | }
12 | message VerifyTokenResp {
13 | string uid = 1;
14 | bool success = 2;
15 | string errMsg = 3;
16 | }
17 |
18 | service authService {
19 | rpc VerifyToken(VerifyTokenReq) returns (VerifyTokenResp) {}
20 | }
21 |
--------------------------------------------------------------------------------
/app/conversation/cmd/rpc/etc/conversation.yaml:
--------------------------------------------------------------------------------
1 | Name: conversation-rpc
2 | ListenOn: 192.168.2.77:10230
3 |
4 | Log:
5 | ServiceName: conversation-rpc
6 | Level: info
7 |
8 | Prometheus:
9 | Host: 0.0.0.0
10 | Port: 10231
11 | Path: /metrics
12 |
13 | Telemetry:
14 | Name: conversation-rpc
15 | #Endpoint: http://jaeger:14268/api/traces
16 | Endpoint: http://127.0.0.1:14268/api/traces
17 | Sampler: 1.0
18 | Batcher: jaeger
19 |
--------------------------------------------------------------------------------
/common/types/conversation.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | func GetConversationIDBySessionType(sourceID string, sessionType int) string {
4 | switch sessionType {
5 | case SingleChatType:
6 | return "single_" + sourceID
7 | case GroupChatType:
8 | return "group_" + sourceID
9 | case SuperGroupChatType:
10 | return "supergroup_" + sourceID
11 | case NotificationChatType:
12 | return "notification_" + sourceID
13 | }
14 | return ""
15 | }
16 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/generator/server.tpl:
--------------------------------------------------------------------------------
1 | {{.head}}
2 |
3 | package server
4 |
5 | import (
6 | {{if .notStream}}"context"{{end}}
7 |
8 | {{.imports}}
9 | )
10 |
11 | type {{.server}}Server struct {
12 | svcCtx *svc.ServiceContext
13 | {{.unimplementedServer}}
14 | }
15 |
16 | func New{{.server}}Server(svcCtx *svc.ServiceContext) *{{.server}}Server {
17 | return &{{.server}}Server{
18 | svcCtx: svcCtx,
19 | }
20 | }
21 |
22 | {{.funcs}}
23 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/server.tpl:
--------------------------------------------------------------------------------
1 | {{.head}}
2 |
3 | package server
4 |
5 | import (
6 | {{if .notStream}}"context"{{end}}
7 |
8 | {{.imports}}
9 | )
10 |
11 | type {{.server}}Server struct {
12 | svcCtx *svc.ServiceContext
13 | {{.unimplementedServer}}
14 | }
15 |
16 | func New{{.server}}Server(svcCtx *svc.ServiceContext) *{{.server}}Server {
17 | return &{{.server}}Server{
18 | svcCtx: svcCtx,
19 | }
20 | }
21 |
22 | {{.funcs}}
23 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Test binary, built with `go test -c`
9 | *.test
10 |
11 | # Output of the go coverage tool, specifically when used with LiteIDE
12 | *.out
13 |
14 | # Dependency directories (remove the comment below to include it)
15 | # vendor/
16 | *.tar.gz
17 | *.zip
18 | *bin/
19 | *.idea/
20 | *bin
21 | *wrk/
22 | *.png
23 | *.jpg
24 | *.jpeg
25 | .DS_Store
--------------------------------------------------------------------------------
/goctl/goctl/compare/compare.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "github.com/zeromicro/go-zero/tools/goctl/compare/cmd"
4 |
5 | // EXPRIMENTAL: compare goctl generated code results between old and new, it will be removed in the feature.
6 | // TODO: BEFORE RUNNING: export DSN=$datasource, the database must be gozero, and there has no limit for tables.
7 | // TODO: AFTER RUNNING: diff --recursive old_fs new_fs
8 |
9 | func main() {
10 | cmd.Execute()
11 | }
12 |
--------------------------------------------------------------------------------
/goctl/goctl/pkg/downloader/downloader.go:
--------------------------------------------------------------------------------
1 | package downloader
2 |
3 | import (
4 | "io"
5 | "net/http"
6 | "os"
7 | )
8 |
9 | func Download(url, filename string) error {
10 | resp, err := http.Get(url)
11 | if err != nil {
12 | return err
13 | }
14 | defer resp.Body.Close()
15 |
16 | f, err := os.Create(filename)
17 | if err != nil {
18 | return err
19 | }
20 | defer f.Close()
21 | _, err = io.Copy(f, resp.Body)
22 | return err
23 | }
24 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/template/types.go:
--------------------------------------------------------------------------------
1 | package template
2 |
3 | // Types defines a template for types in model.
4 | const Types = `
5 | type (
6 | {{.lowerStartCamelObject}}Model interface{
7 | {{.method}}
8 | }
9 |
10 | default{{.upperStartCamelObject}}Model struct {
11 | {{if .withCache}}sqlc.CachedConn{{else}}conn sqlx.SqlConn{{end}}
12 | table string
13 | }
14 |
15 | {{.upperStartCamelObject}} struct {
16 | {{.fields}}
17 | }
18 | )
19 | `
20 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/has_comment_api_test.api:
--------------------------------------------------------------------------------
1 | type Inline struct {
2 |
3 | }
4 |
5 | type Request struct {
6 | Inline
7 | Name string `path:"name,options=you|me"` // name in path
8 | }
9 |
10 | type Response struct {
11 | Message string `json:"msg"` // message
12 | }
13 |
14 | service A-api {
15 | @doc ("helloworld")
16 | @server(
17 | handler: GreetHandler
18 | )
19 | get /greet/from/:name(Request) returns (Response)
20 | }
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/template/new.go:
--------------------------------------------------------------------------------
1 | package template
2 |
3 | // New defines the template for creating model instance.
4 | const New = `
5 | func new{{.upperStartCamelObject}}Model(conn sqlx.SqlConn{{if .withCache}}, c cache.CacheConf{{end}}) *default{{.upperStartCamelObject}}Model {
6 | return &default{{.upperStartCamelObject}}Model{
7 | {{if .withCache}}CachedConn: sqlc.NewConn(conn, c){{else}}conn:conn{{end}},
8 | table: {{.table}},
9 | }
10 | }
11 | `
12 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/call-func.tpl:
--------------------------------------------------------------------------------
1 |
2 | {{if .hasComment}}{{.comment}}{{end}}
3 | func (m *default{{.serviceName}}) {{.method}}(ctx context.Context{{if .hasReq}}, in *{{.pbRequest}}{{end}}, opts ...grpc.CallOption) ({{if .notStream}}*{{.pbResponse}}, {{else}}{{.streamBody}},{{end}} error) {
4 | client := {{if .isCallPkgSameToGrpcPkg}}{{else}}{{.package}}.{{end}}New{{.rpcServiceName}}Client(m.cli.Conn())
5 | return client.{{.method}}(ctx{{if .hasReq}}, in{{end}}, opts...)
6 | }
7 |
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/g4/test/apis/types.api:
--------------------------------------------------------------------------------
1 | type Foo{
2 | }
3 |
4 | type Bar struct{
5 | }
6 |
7 | type FooBar {
8 | Foo int
9 | Bar bool
10 | Map map[string]int
11 | Map1 map[string]Bar
12 | Map2 map[string]*Bar
13 | Map3 map[string][]int
14 | Map4 map[string][]Bar
15 | Map5 map[string][]*Bar
16 | Map6 map[string]map[string]int
17 | Array []int
18 | Array1 []*Bar
19 | Array2 []Bar
20 | Pointer *Bar
21 | Bar
22 | }
23 |
24 |
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/testdata/test.api:
--------------------------------------------------------------------------------
1 | // syntax doc
2 | syntax = "v1" // syntax comment
3 |
4 | // type doc
5 | type Request {
6 | Name string `path:"name,options=you|me"`
7 | }
8 |
9 | type Response {
10 | Message string `json:"message"`
11 | }
12 |
13 | // service doc
14 | service greet-api {
15 | // handler doc
16 | @handler GreetHandler // handler comment
17 | get /from/:name(Request) returns (Response);
18 | }
--------------------------------------------------------------------------------
/common/xcache/global/err.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | var (
8 | ErrTablerNotImplement = fmt.Errorf("Tabler接口未实现")
9 | ErrIGetIDNotImplement = fmt.Errorf("IGetID接口未实现")
10 | ErrInputListNotPtr = fmt.Errorf("传入的list字段并非指针")
11 | ErrInputListNotSlice = fmt.Errorf("传入的list字段并非切片")
12 | ErrInputModelNotPtr = fmt.Errorf("传入的model字段并非指针")
13 | ErrInputModelNotStruct = fmt.Errorf("传入的model字段并非结构体")
14 | ErrInputMpNotMap = fmt.Errorf("参数mp的类型不是Map")
15 | )
16 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/middleware.tpl:
--------------------------------------------------------------------------------
1 | package middleware
2 |
3 | import "net/http"
4 |
5 | type {{.name}} struct {
6 | }
7 |
8 | func New{{.name}}() *{{.name}} {
9 | return &{{.name}}{}
10 | }
11 |
12 | func (m *{{.name}})Handle(next http.HandlerFunc) http.HandlerFunc {
13 | return func(w http.ResponseWriter, r *http.Request) {
14 | // TODO generate middleware implement function, delete after code implementation
15 |
16 | // Passthrough to next handler if need
17 | next(w, r)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/g4/test/grammar_test.go:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/assert"
7 | )
8 |
9 | var files = []string{
10 | "example",
11 | "empty",
12 | "syntax",
13 | "info",
14 | "types",
15 | "service",
16 | }
17 |
18 | func TestGrammar(t *testing.T) {
19 | for _, file := range files {
20 | t.Run(file, func(t *testing.T) {
21 | _, err := parser.Parse("./apis/" + file + ".api")
22 | assert.Nil(t, err)
23 | })
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/middleware.tpl:
--------------------------------------------------------------------------------
1 | package middleware
2 |
3 | import "net/http"
4 |
5 | type {{.name}} struct {
6 | }
7 |
8 | func New{{.name}}() *{{.name}} {
9 | return &{{.name}}{}
10 | }
11 |
12 | func (m *{{.name}})Handle(next http.HandlerFunc) http.HandlerFunc {
13 | return func(w http.ResponseWriter, r *http.Request) {
14 | // TODO generate middleware implement function, delete after code implementation
15 |
16 | // Passthrough to next handler if need
17 | next(w, r)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/goctl/goctl/util/ctx/context_test.go:
--------------------------------------------------------------------------------
1 | package ctx
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/assert"
7 | )
8 |
9 | func TestBackground(t *testing.T) {
10 | workDir := "."
11 | ctx, err := Prepare(workDir)
12 | assert.Nil(t, err)
13 | assert.True(t, true, func() bool {
14 | return len(ctx.Dir) != 0 && len(ctx.Path) != 0
15 | }())
16 | }
17 |
18 | func TestBackgroundNilWorkDir(t *testing.T) {
19 | workDir := ""
20 | _, err := Prepare(workDir)
21 | assert.NotNil(t, err)
22 | }
23 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/generator/prototmpl_test.go:
--------------------------------------------------------------------------------
1 | package generator
2 |
3 | import (
4 | "path/filepath"
5 | "testing"
6 |
7 | "github.com/stretchr/testify/assert"
8 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
9 | )
10 |
11 | func TestProtoTmpl(t *testing.T) {
12 | _ = Clean()
13 | // exists dir
14 | err := ProtoTmpl(pathx.MustTempDir())
15 | assert.Nil(t, err)
16 |
17 | // not exist dir
18 | dir := filepath.Join(pathx.MustTempDir(), "test")
19 | err = ProtoTmpl(dir)
20 | assert.Nil(t, err)
21 | }
22 |
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/etc/msggateway-rpc.yaml:
--------------------------------------------------------------------------------
1 | Name: msggateway-rpc
2 | ListenOn: 192.168.2.77:10400
3 |
4 | Etcd:
5 | Hosts:
6 | - 127.0.0.1:2379
7 | Key: msggateway-rpc
8 |
9 | Log:
10 | ServiceName: msggateway-rpc
11 | Level: info
12 |
13 |
14 | Prometheus:
15 | Host: 0.0.0.0
16 | Port: 10401
17 | Path: /metrics
18 |
19 | Telemetry:
20 | Name: msggateway-rpc
21 | #Endpoint: http://jaeger:14268/api/traces
22 | Endpoint: http://127.0.0.1:14268/api/traces
23 | Sampler: 1.0
24 | Batcher: jaeger
25 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/generator/logic.tpl:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 |
6 | {{.imports}}
7 |
8 | "github.com/zeromicro/go-zero/core/logx"
9 | )
10 |
11 | type {{.logicName}} struct {
12 | ctx context.Context
13 | svcCtx *svc.ServiceContext
14 | logx.Logger
15 | }
16 |
17 | func New{{.logicName}}(ctx context.Context,svcCtx *svc.ServiceContext) *{{.logicName}} {
18 | return &{{.logicName}}{
19 | ctx: ctx,
20 | svcCtx: svcCtx,
21 | Logger: logx.WithContext(ctx),
22 | }
23 | }
24 | {{.functions}}
25 |
--------------------------------------------------------------------------------
/goctl/goctl/vars/settings.go:
--------------------------------------------------------------------------------
1 | package vars
2 |
3 | const (
4 | // ProjectName the const value of zero
5 | ProjectName = "zero"
6 | // ProjectOpenSourceURL the github url of go-zero
7 | ProjectOpenSourceURL = "github.com/zeromicro/go-zero"
8 | // OsWindows represents os windows
9 | OsWindows = "windows"
10 | // OsMac represents os mac
11 | OsMac = "darwin"
12 | // OsLinux represents os linux
13 | OsLinux = "linux"
14 | // OsJs represents os js
15 | OsJs = "js"
16 | // OsIOS represents os ios
17 | OsIOS = "ios"
18 | )
19 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/logic.tpl:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 |
6 | {{.imports}}
7 |
8 | "github.com/zeromicro/go-zero/core/logx"
9 | )
10 |
11 | type {{.logicName}} struct {
12 | ctx context.Context
13 | svcCtx *svc.ServiceContext
14 | logx.Logger
15 | }
16 |
17 | func New{{.logicName}}(ctx context.Context,svcCtx *svc.ServiceContext) *{{.logicName}} {
18 | return &{{.logicName}}{
19 | ctx: ctx,
20 | svcCtx: svcCtx,
21 | Logger: logx.WithContext(ctx),
22 | }
23 | }
24 | {{.functions}}
25 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/server-func.tpl:
--------------------------------------------------------------------------------
1 |
2 | {{if .hasComment}}{{.comment}}{{end}}
3 | func (s *{{.server}}Server) {{.method}} ({{if .notStream}}ctx context.Context,{{if .hasReq}} in {{.request}}{{end}}{{else}}{{if .hasReq}} in {{.request}},{{end}}stream {{.streamBody}}{{end}}) ({{if .notStream}}{{.response}},{{end}}error) {
4 | l := logic.New{{.logicName}}({{if .notStream}}ctx,{{else}}stream.Context(),{{end}}s.svcCtx)
5 | return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}})
6 | }
7 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/api_route_test.api:
--------------------------------------------------------------------------------
1 | type Request struct {
2 | Name string `path:"name,options=you|me"`
3 | }
4 | type Response struct {
5 | Message string `json:"message"`
6 | }
7 | service A-api {
8 | @handler NormalHandler
9 | get /greet/from/:name(Request) returns (Response)
10 | @handler NoResponseHandler
11 | get /greet/from/:sex(Request)
12 | @handler NoRequestHandler
13 | get /greet/from/request returns (Response)
14 | @handler NoRequestNoResponseHandler
15 | get /greet/from
16 | }
--------------------------------------------------------------------------------
/goctl/goctl/api/javagen/component.tpl:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT.
2 | package com.xhb.logic.http.packet.{{.packet}}.model;
3 |
4 | import org.jetbrains.annotations.NotNull;
5 | import org.jetbrains.annotations.Nullable;
6 | {{.imports}}
7 |
8 | public class {{.className}} extends {{.superClassName}} {
9 |
10 | {{.properties}}
11 | {{if .HasProperty}}
12 |
13 | public {{.className}}() {
14 | }
15 |
16 | public {{.className}}({{.params}}) {
17 | {{.constructorSetter}}
18 | }
19 | {{end}}
20 |
21 | {{.getSet}}
22 | }
23 |
--------------------------------------------------------------------------------
/goctl/goctl/util/head.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | const (
4 | // DoNotEditHead added to the beginning of a file to prompt the user not to edit
5 | DoNotEditHead = "// Code generated by goctl. DO NOT EDIT!"
6 |
7 | headTemplate = DoNotEditHead + `
8 | // Source: {{.source}}`
9 | )
10 |
11 | // GetHead returns a code head string with source filename
12 | func GetHead(source string) string {
13 | buffer, _ := With("head").Parse(headTemplate).Execute(map[string]interface{}{
14 | "source": source,
15 | })
16 | return buffer.String()
17 | }
18 |
--------------------------------------------------------------------------------
/app/msg/cmd/rpc/internal/server/exampleServer.go:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT!
2 | // Source: ws.proto
3 |
4 | package server
5 |
6 | import (
7 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/internal/svc"
8 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/pb"
9 | )
10 |
11 | type ExampleServer struct {
12 | svcCtx *svc.ServiceContext
13 | pb.UnimplementedExampleServer
14 | }
15 |
16 | func NewExampleServer(svcCtx *svc.ServiceContext) *ExampleServer {
17 | return &ExampleServer{
18 | svcCtx: svcCtx,
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/common/xmgo/client.go:
--------------------------------------------------------------------------------
1 | package xmgo
2 |
3 | import (
4 | "context"
5 | "github.com/showurl/Zero-IM-Server/common/xmgo/global"
6 | "go.mongodb.org/mongo-driver/mongo"
7 | "go.mongodb.org/mongo-driver/mongo/options"
8 | )
9 |
10 | func GetClient(
11 | cfg global.MongoConfig,
12 | ) *mongo.Client {
13 | mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(cfg.Uri))
14 | if err != nil {
15 | panic(err)
16 | }
17 | err = mongoClient.Ping(context.TODO(), nil)
18 | if err != nil {
19 | panic(err)
20 | }
21 | return mongoClient
22 | }
23 |
--------------------------------------------------------------------------------
/goctl/goctl/api/apigen/util.go:
--------------------------------------------------------------------------------
1 | package apigen
2 |
3 | import (
4 | "os/exec"
5 | "strings"
6 | )
7 |
8 | func getGitName() string {
9 | cmd := exec.Command("git", "config", "user.name")
10 | out, err := cmd.CombinedOutput()
11 | if err != nil {
12 | return ""
13 | }
14 |
15 | return strings.TrimSpace(string(out))
16 | }
17 |
18 | func getGitEmail() string {
19 | cmd := exec.Command("git", "config", "user.email")
20 | out, err := cmd.CombinedOutput()
21 | if err != nil {
22 | return ""
23 | }
24 |
25 | return strings.TrimSpace(string(out))
26 | }
27 |
--------------------------------------------------------------------------------
/common/xcache/rc/options.go:
--------------------------------------------------------------------------------
1 | package rc
2 |
3 | type Option func(*relationOption)
4 |
5 | type relationOption struct {
6 | order string // 排序字段
7 | size int // 存储大小 <=0 则会全部存储
8 | }
9 |
10 | func defaultRelationOption() *relationOption {
11 | return &relationOption{
12 | order: "created_at desc",
13 | size: 0,
14 | }
15 | }
16 |
17 | func Order(field string) Option {
18 | return func(r *relationOption) {
19 | r.order = field
20 | }
21 | }
22 |
23 | func Size(limit int) Option {
24 | return func(r *relationOption) {
25 | r.size = limit
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/goctl/goctl/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/zeromicro/go-zero/tools/goctl
2 |
3 | go 1.16
4 |
5 | require (
6 | github.com/DATA-DOG/go-sqlmock v1.5.0
7 | github.com/emicklei/proto v1.9.1
8 | github.com/fatih/structtag v1.2.0
9 | github.com/go-sql-driver/mysql v1.6.0
10 | github.com/iancoleman/strcase v0.2.0
11 | github.com/logrusorgru/aurora v2.0.3+incompatible
12 | github.com/spf13/cobra v1.4.0
13 | github.com/stretchr/testify v1.7.0
14 | github.com/zeromicro/antlr v0.0.1
15 | github.com/zeromicro/ddl-parser v1.0.3
16 | github.com/zeromicro/go-zero v1.3.2
17 | )
18 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/main.tpl:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 |
7 | {{.importPackages}}
8 | )
9 |
10 | var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
11 |
12 | func main() {
13 | flag.Parse()
14 |
15 | var c config.Config
16 | conf.MustLoad(*configFile, &c)
17 |
18 | ctx := svc.NewServiceContext(c)
19 | server := rest.MustNewServer(c.RestConf)
20 | defer server.Stop()
21 |
22 | handler.RegisterHandlers(server, ctx)
23 |
24 | fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
25 | server.Start()
26 | }
27 |
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/g4/ast/importstack.go:
--------------------------------------------------------------------------------
1 | package ast
2 |
3 | import "errors"
4 |
5 | // ErrImportCycleNotAllowed defines an error for circular importing
6 | var ErrImportCycleNotAllowed = errors.New("import cycle not allowed")
7 |
8 | // importStack a stack of import paths
9 | type importStack []string
10 |
11 | func (s *importStack) push(p string) error {
12 | for _, x := range *s {
13 | if x == p {
14 | return ErrImportCycleNotAllowed
15 | }
16 | }
17 | *s = append(*s, p)
18 | return nil
19 | }
20 |
21 | func (s *importStack) pop() {
22 | *s = (*s)[0 : len(*s)-1]
23 | }
24 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/main.tpl:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 |
7 | {{.importPackages}}
8 | )
9 |
10 | var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
11 |
12 | func main() {
13 | flag.Parse()
14 |
15 | var c config.Config
16 | conf.MustLoad(*configFile, &c)
17 |
18 | ctx := svc.NewServiceContext(c)
19 | server := rest.MustNewServer(c.RestConf)
20 | defer server.Stop()
21 |
22 | handler.RegisterHandlers(server, ctx)
23 |
24 | fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
25 | server.Start()
26 | }
27 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/find-one-by-field-extra-method.tpl:
--------------------------------------------------------------------------------
1 |
2 | func (m *default{{.upperStartCamelObject}}Model) formatPrimary(primary interface{}) string {
3 | return fmt.Sprintf("%s%v", {{.primaryKeyLeft}}, primary)
4 | }
5 |
6 | func (m *default{{.upperStartCamelObject}}Model) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error {
7 | query := fmt.Sprintf("select %s from %s where {{.originalPrimaryField}} = {{if .postgreSql}}$1{{else}}?{{end}} limit 1", {{.lowerStartCamelObject}}Rows, m.table )
8 | return conn.QueryRowCtx(ctx, v, query, primary)
9 | }
10 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/logic.tpl:
--------------------------------------------------------------------------------
1 | package {{.pkgName}}
2 |
3 | import (
4 | {{.imports}}
5 | )
6 |
7 | type {{.logic}} struct {
8 | logx.Logger
9 | ctx context.Context
10 | svcCtx *svc.ServiceContext
11 | }
12 |
13 | func New{{.logic}}(ctx context.Context, svcCtx *svc.ServiceContext) *{{.logic}} {
14 | return &{{.logic}}{
15 | Logger: logx.WithContext(ctx),
16 | ctx: ctx,
17 | svcCtx: svcCtx,
18 | }
19 | }
20 |
21 | func (l *{{.logic}}) {{.function}}({{.request}}) {{.responseType}} {
22 | // todo: add your logic here and delete this line
23 |
24 | {{.returnString}}
25 | }
26 |
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/g4/test/apis/service.api:
--------------------------------------------------------------------------------
1 | type Foo {}
2 |
3 | @server(
4 | foo: foo
5 | bar: "bar"
6 | fooBar: "foo
7 | bar"
8 | )
9 | service foo-api {
10 | @doc("foo")
11 | @handler foo
12 | get /foo (Foo) returns (Foo)
13 | @handler bar
14 | post /foo (Foo)
15 | @handler fooBar
16 | post /foo/bar
17 | @server(
18 | handler: getFoo
19 | )
20 | post /foo/:id returns(Foo)
21 | }
22 |
23 | service foo-api {
24 | @doc(
25 | summary:"post foo"
26 | )
27 | @handler postFoo
28 | post /foo/bar/post (Foo)
29 | }
30 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/test_multi_service_template.api:
--------------------------------------------------------------------------------
1 | info(
2 | title: doc title
3 | desc: doc description first part
4 | version: 1.0
5 | )
6 |
7 | type Request struct {
8 | Name string `path:"name,options=you|me"`
9 | }
10 |
11 | type Response struct {
12 | Message string `json:"message"`
13 | }
14 |
15 | service A-api {
16 | @server(
17 | handler: GreetHandler
18 | )
19 | get /greet/from/:name(Request) returns (Response)
20 | }
21 |
22 | service A-api {
23 | @server(
24 | handler: NoResponseHandler
25 | )
26 | get /greet/get(Request)
27 | }
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/logic.tpl:
--------------------------------------------------------------------------------
1 | package {{.pkgName}}
2 |
3 | import (
4 | {{.imports}}
5 | )
6 |
7 | type {{.logic}} struct {
8 | logx.Logger
9 | ctx context.Context
10 | svcCtx *svc.ServiceContext
11 | }
12 |
13 | func New{{.logic}}(ctx context.Context, svcCtx *svc.ServiceContext) *{{.logic}} {
14 | return &{{.logic}}{
15 | Logger: logx.WithContext(ctx),
16 | ctx: ctx,
17 | svcCtx: svcCtx,
18 | }
19 | }
20 |
21 | func (l *{{.logic}}) {{.function}}({{.request}}) {{.responseType}} {
22 | // todo: add your logic here and delete this line
23 |
24 | {{.returnString}}
25 | }
26 |
--------------------------------------------------------------------------------
/app/msg-transfer/cmd/history/internal/repository/seq.go:
--------------------------------------------------------------------------------
1 | package repository
2 |
3 | import (
4 | "context"
5 | "github.com/showurl/Zero-IM-Server/common/types"
6 | )
7 |
8 | func (r *Rep) IncrUserSeq(uid string) (uint64, error) {
9 | key := types.RedisKeyUserIncrSeq + uid
10 | count, err := r.Cache.Incr(context.Background(), key).Result()
11 | return uint64(count), err
12 | }
13 |
14 | func (r *Rep) IncrSuperGroupSeq(groupId string) (uint64, error) {
15 | key := types.RedisKeySuperGroupIncrSeq + groupId
16 | count, err := r.Cache.Incr(context.Background(), key).Result()
17 | return uint64(count), err
18 | }
19 |
--------------------------------------------------------------------------------
/common/utils/encrypt/hash.go:
--------------------------------------------------------------------------------
1 | package encrypt
2 |
3 | import "github.com/speps/go-hashids"
4 |
5 | func EnCodeInt64(id int64, salt string) (string, error) {
6 | hd := hashids.NewData()
7 | hd.Salt = salt //盐值
8 | hd.MinLength = 10
9 | h, _ := hashids.NewWithData(hd)
10 | return h.EncodeInt64([]int64{id})
11 | }
12 |
13 | func DeCodeInt64(code string, salt string) (int64, error) {
14 | hd := hashids.NewData()
15 | hd.Salt = salt
16 | hd.MinLength = 10
17 | h, _ := hashids.NewWithData(hd)
18 | d, err := h.DecodeInt64WithError(code)
19 | if err == nil {
20 | return d[0], nil
21 | }
22 | return 0, err
23 | }
24 |
--------------------------------------------------------------------------------
/common/xtrace/span.go:
--------------------------------------------------------------------------------
1 | package xtrace
2 |
3 | import (
4 | "context"
5 | "github.com/zeromicro/go-zero/core/trace"
6 | "go.opentelemetry.io/otel"
7 | "go.opentelemetry.io/otel/attribute"
8 | oteltrace "go.opentelemetry.io/otel/trace"
9 | )
10 |
11 | func StartFuncSpan(ctx context.Context, name string, f func(context.Context), kv ...attribute.KeyValue) {
12 | tracer := otel.GetTracerProvider().Tracer(trace.TraceName)
13 | spanCtx, span := tracer.Start(ctx, name,
14 | oteltrace.WithSpanKind(oteltrace.SpanKindInternal),
15 | oteltrace.WithAttributes(kv...),
16 | )
17 | defer span.End()
18 | f(spanCtx)
19 | }
20 |
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/internal/handler/routes.go:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT.
2 | package handler
3 |
4 | import (
5 | "net/http"
6 |
7 | "github.com/showurl/Zero-IM-Server/app/msg-gateway/cmd/wsrpc/internal/wssvc"
8 |
9 | "github.com/zeromicro/go-zero/rest"
10 | )
11 |
12 | func RegisterHandlers(server *rest.Server, serverCtx *wssvc.ServiceContext) {
13 | //http.HandleFunc("/", MsggatewayHandler(serverCtx))
14 | server.AddRoutes(
15 | []rest.Route{
16 | {
17 | Method: http.MethodGet,
18 | Path: "/",
19 | Handler: MsggatewayHandler(serverCtx),
20 | },
21 | },
22 | )
23 | }
24 |
--------------------------------------------------------------------------------
/common/utils/time/format.go:
--------------------------------------------------------------------------------
1 | package timeUtils
2 |
3 | import "time"
4 |
5 | const (
6 | TimeFormat = "2006-01-02 15:04:05"
7 | TimeMSFormat = "2006-01-02 15:04:05.000"
8 | DateFormat = "2006-01-02"
9 | TimeTZFormat = `2006-01-02T15:04:05Z`
10 | )
11 |
12 | func StrDatetime(t time.Time) string {
13 | return t.Format(TimeFormat)
14 | }
15 |
16 | func StrDatetimeMs(t time.Time) string {
17 | return t.Format(TimeMSFormat)
18 | }
19 |
20 | func StrDate(t time.Time) string {
21 | return t.Format(DateFormat)
22 | }
23 |
24 | func ParseTime(str string) time.Time {
25 | t, _ := time.Parse(TimeFormat, str)
26 | return t
27 | }
28 |
--------------------------------------------------------------------------------
/common/xcache/rc/knownMap.go:
--------------------------------------------------------------------------------
1 | package rc
2 |
3 | const MagicKey = "$"
4 |
5 | var (
6 | gtKey = MagicKey + "gt"
7 | gteKey = MagicKey + "gte"
8 | ltKey = MagicKey + "lt"
9 | lteKey = MagicKey + "lte"
10 | whereKey = MagicKey + "where"
11 | )
12 |
13 | func KeyGt(key string) string {
14 | return key + gtKey
15 | }
16 |
17 | func KeyGte(key string) string {
18 | return key + gteKey
19 | }
20 |
21 | func KeyLt(key string) string {
22 | return key + ltKey
23 | }
24 |
25 | func KeyLte(key string) string {
26 | return key + lteKey
27 | }
28 |
29 | func KeyWhere(key string) string {
30 | return key + whereKey
31 | }
32 |
--------------------------------------------------------------------------------
/goctl/goctl/rpc/generator/call.tpl:
--------------------------------------------------------------------------------
1 | {{.head}}
2 |
3 | package {{.filePackage}}
4 |
5 | import (
6 | "context"
7 |
8 | {{.pbPackage}}
9 | {{if ne .pbPackage .protoGoPackage}}{{.protoGoPackage}}{{end}}
10 |
11 | "github.com/zeromicro/go-zero/zrpc"
12 | "google.golang.org/grpc"
13 | )
14 |
15 | type (
16 | {{.alias}}
17 |
18 | {{.serviceName}} interface {
19 | {{.interface}}
20 | }
21 |
22 | default{{.serviceName}} struct {
23 | cli zrpc.Client
24 | }
25 | )
26 |
27 | func New{{.serviceName}}(cli zrpc.Client) {{.serviceName}} {
28 | return &default{{.serviceName}}{
29 | cli: cli,
30 | }
31 | }
32 |
33 | {{.functions}}
34 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/rpc/call.tpl:
--------------------------------------------------------------------------------
1 | {{.head}}
2 |
3 | package {{.filePackage}}
4 |
5 | import (
6 | "context"
7 |
8 | {{.pbPackage}}
9 | {{if ne .pbPackage .protoGoPackage}}{{.protoGoPackage}}{{end}}
10 |
11 | "github.com/zeromicro/go-zero/zrpc"
12 | "google.golang.org/grpc"
13 | )
14 |
15 | type (
16 | {{.alias}}
17 |
18 | {{.serviceName}} interface {
19 | {{.interface}}
20 | }
21 |
22 | default{{.serviceName}} struct {
23 | cli zrpc.Client
24 | }
25 | )
26 |
27 | func New{{.serviceName}}(cli zrpc.Client) {{.serviceName}} {
28 | return &default{{.serviceName}}{
29 | cli: cli,
30 | }
31 | }
32 |
33 | {{.functions}}
34 |
--------------------------------------------------------------------------------
/goctl/goctl/compare/cmd/cmd.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "github.com/spf13/cobra"
5 | "github.com/zeromicro/go-zero/tools/goctl/compare/testdata"
6 | "github.com/zeromicro/go-zero/tools/goctl/util/console"
7 | )
8 |
9 | var rootCmd = &cobra.Command{
10 | Use: "compare",
11 | Short: "Compare the goctl commands generated results between urfave and cobra",
12 | Args: cobra.ExactValidArgs(1),
13 | Run: func(cmd *cobra.Command, args []string) {
14 | dir := args[0]
15 | testdata.MustRun(dir)
16 | },
17 | }
18 |
19 | func Execute() {
20 | if err := rootCmd.Execute(); err != nil {
21 | console.Error("%+v", err)
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/goctl/goctl/api/apigen/api.tpl:
--------------------------------------------------------------------------------
1 | syntax = "v1"
2 |
3 | info (
4 | title: // TODO: add title
5 | desc: // TODO: add description
6 | author: "{{.gitUser}}"
7 | email: "{{.gitEmail}}"
8 | )
9 |
10 | type request {
11 | // TODO: add members here and delete this comment
12 | }
13 |
14 | type response {
15 | // TODO: add members here and delete this comment
16 | }
17 |
18 | service {{.serviceName}} {
19 | @handler GetUser // TODO: set handler name and delete this comment
20 | get /users/id/:userId(request) returns(response)
21 |
22 | @handler CreateUser // TODO: set handler name and delete this comment
23 | post /users/create(request)
24 | }
25 |
--------------------------------------------------------------------------------
/goctl/goctl/pkg/golang/bin.go:
--------------------------------------------------------------------------------
1 | package golang
2 |
3 | import (
4 | "go/build"
5 | "os"
6 | "path/filepath"
7 |
8 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
9 | )
10 |
11 | // GoBin returns a path of GOBIN.
12 | func GoBin() string {
13 | def := build.Default
14 | goroot := os.Getenv("GOPATH")
15 | bin := filepath.Join(goroot, "bin")
16 | if !pathx.FileExists(bin) {
17 | gopath := os.Getenv("GOROOT")
18 | bin = filepath.Join(gopath, "bin")
19 | }
20 | if !pathx.FileExists(bin) {
21 | bin = os.Getenv("GOBIN")
22 | }
23 | if !pathx.FileExists(bin) {
24 | bin = filepath.Join(def.GOPATH, "bin")
25 | }
26 | return bin
27 | }
28 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/template.tpl:
--------------------------------------------------------------------------------
1 | syntax = "v1"
2 |
3 | info (
4 | title: // TODO: add title
5 | desc: // TODO: add description
6 | author: "{{.gitUser}}"
7 | email: "{{.gitEmail}}"
8 | )
9 |
10 | type request {
11 | // TODO: add members here and delete this comment
12 | }
13 |
14 | type response {
15 | // TODO: add members here and delete this comment
16 | }
17 |
18 | service {{.serviceName}} {
19 | @handler GetUser // TODO: set handler name and delete this comment
20 | get /users/id/:userId(request) returns(response)
21 |
22 | @handler CreateUser // TODO: set handler name and delete this comment
23 | post /users/create(request)
24 | }
25 |
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/etc/msggateway-ws.yaml:
--------------------------------------------------------------------------------
1 | Name: msggateway-ws
2 | Host: 0.0.0.0
3 | Port: 17778
4 |
5 | Websocket:
6 | MaxConnNum: 10000
7 | TimeOut: 10
8 | MaxMsgLen: 4096
9 |
10 | Log:
11 | ServiceName: msggateway-ws
12 | Level: info
13 |
14 |
15 | Prometheus:
16 | Host: 0.0.0.0
17 | Port: 17779
18 | Path: /metrics
19 |
20 | Telemetry:
21 | Name: msggateway-ws
22 | #Endpoint: http://jaeger:14268/api/traces
23 | Endpoint: http://127.0.0.1:14268/api/traces
24 | Sampler: 1.0
25 | Batcher: jaeger
26 |
27 | #rpc service
28 | AuthRpc:
29 | Endpoints:
30 | - 192.168.2.77:10160
31 |
32 | MsgRpc:
33 | Endpoints:
34 | - 192.168.2.77:10130
--------------------------------------------------------------------------------
/goctl/goctl/util/ctx/modcheck.go:
--------------------------------------------------------------------------------
1 | package ctx
2 |
3 | import (
4 | "errors"
5 | "os"
6 |
7 | "github.com/zeromicro/go-zero/tools/goctl/rpc/execx"
8 | )
9 |
10 | // IsGoMod is used to determine whether workDir is a go module project through command `go list -json -m`
11 | func IsGoMod(workDir string) (bool, error) {
12 | if len(workDir) == 0 {
13 | return false, errors.New("the work directory is not found")
14 | }
15 | if _, err := os.Stat(workDir); err != nil {
16 | return false, err
17 | }
18 |
19 | data, err := execx.Run("go list -m -f '{{.GoMod}}'", workDir)
20 | if err != nil || len(data) == 0 {
21 | return false, nil
22 | }
23 |
24 | return true, nil
25 | }
26 |
--------------------------------------------------------------------------------
/goctl/goctl/bug/env.go:
--------------------------------------------------------------------------------
1 | package bug
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "runtime"
7 | "strings"
8 |
9 | "github.com/zeromicro/go-zero/tools/goctl/internal/version"
10 | )
11 |
12 | type env map[string]string
13 |
14 | func (e env) string() string {
15 | if e == nil {
16 | return ""
17 | }
18 |
19 | w := bytes.NewBuffer(nil)
20 | for k, v := range e {
21 | w.WriteString(fmt.Sprintf("%s = %q\n", k, v))
22 | }
23 |
24 | return strings.TrimSuffix(w.String(), "\n")
25 | }
26 |
27 | func getEnv() env {
28 | e := make(env)
29 | e[os] = runtime.GOOS
30 | e[arch] = runtime.GOARCH
31 | e[goctlVersion] = version.BuildVersion
32 | e[goVersion] = runtime.Version()
33 | return e
34 | }
35 |
--------------------------------------------------------------------------------
/common/utils/rand/str.go:
--------------------------------------------------------------------------------
1 | package randUtils
2 |
3 | import (
4 | "math/rand"
5 | "strconv"
6 | "time"
7 | )
8 |
9 | // RandPhone 随机手机号
10 | func RandPhone() string {
11 | return "13" + RandNum(8)
12 | }
13 |
14 | // RandNum 随机数字
15 | func RandNum(i int) string {
16 | var str string
17 | for j := 0; j < i; j++ {
18 | str += strconv.Itoa(RandInt(0, 9))
19 | }
20 | return str
21 | }
22 |
23 | // RandString 随机字符串
24 | func RandString(n int) string {
25 | var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
26 | b := make([]rune, n)
27 | for i := range b {
28 | rand.Seed(time.Now().UnixNano())
29 | b[i] = letters[rand.Intn(len(letters))]
30 | }
31 | return string(b)
32 | }
33 |
--------------------------------------------------------------------------------
/common/xetcd/gozero.go:
--------------------------------------------------------------------------------
1 | package xetcd
2 |
3 | import (
4 | "context"
5 | "github.com/zeromicro/go-zero/zrpc"
6 | clientv3 "go.etcd.io/etcd/client/v3"
7 | )
8 |
9 | func GetGoZeroZrpcConns(ctx context.Context, etcdClient *clientv3.Client, key string) (zrpcConns []zrpc.Client, err error) {
10 | response, err := etcdClient.Get(ctx, key, clientv3.WithPrefix())
11 | if err != nil {
12 | return
13 | }
14 | for _, kv := range response.Kvs {
15 | zrpcConns = append(zrpcConns, zrpc.MustNewClient(zrpc.RpcClientConf{
16 | Endpoints: []string{string(kv.Value)},
17 | Target: "",
18 | App: "",
19 | Token: "",
20 | NonBlock: false,
21 | Timeout: 0,
22 | }))
23 | }
24 | return
25 | }
26 |
--------------------------------------------------------------------------------
/common/utils/rand/time.go:
--------------------------------------------------------------------------------
1 | package randUtils
2 |
3 | import "time"
4 |
5 | func RandTime(min string, max string) string {
6 | minTime, _ := time.Parse("2006-01-02 15:04:05", min)
7 | maxTime, _ := time.Parse("2006-01-02 15:04:05", max)
8 | randTime := minTime.Add(time.Duration(RandInt64(int64(minTime.Unix()), int64(maxTime.Unix()))) * time.Second)
9 | return randTime.Format("2006-01-02 15:04:05")
10 | }
11 |
12 | func RandDate(min string, max string) string {
13 | minTime, _ := time.Parse("2006-01-02", min)
14 | maxTime, _ := time.Parse("2006-01-02", max)
15 | randTime := minTime.Add(time.Duration(RandInt64(int64(minTime.Unix()), int64(maxTime.Unix()))) * time.Second)
16 | return randTime.Format("2006-01-02")
17 | }
18 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/gen/tag.go:
--------------------------------------------------------------------------------
1 | package gen
2 |
3 | import (
4 | "github.com/zeromicro/go-zero/tools/goctl/model/sql/template"
5 | "github.com/zeromicro/go-zero/tools/goctl/util"
6 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
7 | )
8 |
9 | func genTag(table Table, in string) (string, error) {
10 | if in == "" {
11 | return in, nil
12 | }
13 |
14 | text, err := pathx.LoadTemplate(category, tagTemplateFile, template.Tag)
15 | if err != nil {
16 | return "", err
17 | }
18 |
19 | output, err := util.With("tag").Parse(text).Execute(map[string]interface{}{
20 | "field": in,
21 | "data": table,
22 | })
23 | if err != nil {
24 | return "", err
25 | }
26 |
27 | return output.String(), nil
28 | }
29 |
--------------------------------------------------------------------------------
/common/xhttp/responsebean.go:
--------------------------------------------------------------------------------
1 | package xhttp
2 |
3 | type (
4 | NullJson struct{}
5 |
6 | ResponseSuccessBean struct {
7 | Code int `json:"code"`
8 | Msg string `json:"msg"`
9 | Data interface{} `json:"data"`
10 | }
11 | )
12 |
13 | func Success(data interface{}) *ResponseSuccessBean {
14 | return &ResponseSuccessBean{200, "OK", data}
15 | }
16 |
17 | type ResponseErrorBean struct {
18 | Code int `json:"code"`
19 | Msg string `json:"msg"`
20 | }
21 |
22 | func Error(errCode int, errMsg string) *ResponseErrorBean {
23 | return &ResponseErrorBean{errCode, errMsg}
24 | }
25 |
26 | func NewResp(resp interface{}) *ResponseSuccessBean {
27 | return &ResponseSuccessBean{
28 | Data: resp,
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/app/msg-transfer/cmd/history/internal/server/types.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "github.com/showurl/Zero-IM-Server/app/msg-transfer/cmd/history/internal/svc"
5 | "github.com/showurl/Zero-IM-Server/common/xkafka"
6 | "sync"
7 | )
8 |
9 | const OnlineTopicBusy = 1
10 | const OnlineTopicVacancy = 0
11 |
12 | type fcb func(msg []byte, msgKey string)
13 | type Cmd2Value struct {
14 | Cmd int
15 | Value interface{}
16 | }
17 |
18 | type MsgTransferHistoryServer struct {
19 | svcCtx *svc.ServiceContext
20 | msgHandle map[string]fcb
21 | historyConsumerGroup *xkafka.MConsumerGroup
22 | cmdCh chan Cmd2Value
23 | w *sync.Mutex
24 | OnlineTopicStatus int
25 | }
26 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/converter/types_test.go:
--------------------------------------------------------------------------------
1 | package converter
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/assert"
7 | "github.com/zeromicro/ddl-parser/parser"
8 | )
9 |
10 | func TestConvertDataType(t *testing.T) {
11 | v, err := ConvertDataType(parser.TinyInt, false)
12 | assert.Nil(t, err)
13 | assert.Equal(t, "int64", v)
14 |
15 | v, err = ConvertDataType(parser.TinyInt, true)
16 | assert.Nil(t, err)
17 | assert.Equal(t, "sql.NullInt64", v)
18 |
19 | v, err = ConvertDataType(parser.Timestamp, false)
20 | assert.Nil(t, err)
21 | assert.Equal(t, "time.Time", v)
22 |
23 | v, err = ConvertDataType(parser.Timestamp, true)
24 | assert.Nil(t, err)
25 | assert.Equal(t, "sql.NullTime", v)
26 | }
27 |
--------------------------------------------------------------------------------
/app/msg-transfer/cmd/history/history.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "github.com/showurl/Zero-IM-Server/app/msg-transfer/cmd/history/internal/config"
6 | "github.com/showurl/Zero-IM-Server/app/msg-transfer/cmd/history/internal/server"
7 | "github.com/showurl/Zero-IM-Server/app/msg-transfer/cmd/history/internal/svc"
8 | "github.com/zeromicro/go-zero/core/conf"
9 | )
10 |
11 | var configFile = flag.String("f", "etc/history.yaml", "the config file")
12 |
13 | func main() {
14 | flag.Parse()
15 |
16 | var c config.Config
17 | conf.MustLoad(*configFile, &c)
18 | err := c.ServiceConf.SetUp()
19 | if err != nil {
20 | panic(err)
21 | }
22 | s := server.NewMsgTransferHistoryServer(svc.NewServiceContext(c))
23 | s.Start()
24 | }
25 |
--------------------------------------------------------------------------------
/goctl/goctl/migrate/cmd.go:
--------------------------------------------------------------------------------
1 | package migrate
2 |
3 | import "github.com/spf13/cobra"
4 |
5 | var (
6 | boolVarVerbose bool
7 | stringVarVersion string
8 | // Cmd describes a migrate command.
9 | Cmd = &cobra.Command{
10 | Use: "migrate",
11 | Short: "Migrate from tal-tech to zeromicro",
12 | Long: "Migrate is a transition command to help users migrate their " +
13 | "projects from tal-tech to zeromicro version",
14 | RunE: migrate,
15 | }
16 | )
17 |
18 | func init() {
19 | Cmd.Flags().BoolVarP(&boolVarVerbose, "verbose", "v",
20 | false, "Verbose enables extra logging")
21 | Cmd.Flags().StringVar(&stringVarVersion, "version", defaultMigrateVersion,
22 | "The target release version of github.com/zeromicro/go-zero to migrate")
23 | }
24 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/insert.tpl:
--------------------------------------------------------------------------------
1 |
2 | func (m *default{{.upperStartCamelObject}}Model) Insert(ctx context.Context, data *{{.upperStartCamelObject}}) (sql.Result,error) {
3 | {{if .withCache}}{{.keys}}
4 | ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
5 | query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet)
6 | return conn.ExecCtx(ctx, query, {{.expressionValues}})
7 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet)
8 | ret,err:=m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}}
9 | return ret,err
10 | }
11 |
--------------------------------------------------------------------------------
/common/types/contenttype.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | const ( ///消息类型
4 | Text = 101
5 | Picture = 102
6 | Voice = 103
7 | Video = 104
8 | File = 105
9 | AtText = 106
10 | Merger = 107
11 | Card = 108
12 | Location = 109
13 | Custom = 110
14 | Revoke = 111
15 | HasReadReceipt = 112
16 | Typing = 113
17 | Quote = 114
18 | Common = 200
19 | GroupMsg = 201
20 | )
21 |
22 | var ContentType2PushContent = map[int64]string{
23 | Picture: "[图片]",
24 | Voice: "[语音]",
25 | Video: "[视频]",
26 | File: "[文件]",
27 | Text: "你收到了一条文本消息",
28 | AtText: "[有人@你]",
29 | GroupMsg: "你收到一条群聊消息",
30 | Common: "你收到一条新消息",
31 | }
32 |
--------------------------------------------------------------------------------
/goctl/goctl/migrate/cancel.go:
--------------------------------------------------------------------------------
1 | //go:build linux || darwin
2 | // +build linux darwin
3 |
4 | package migrate
5 |
6 | import (
7 | "os"
8 | "os/signal"
9 | "syscall"
10 |
11 | "github.com/zeromicro/go-zero/core/syncx"
12 | "github.com/zeromicro/go-zero/tools/goctl/util/console"
13 | )
14 |
15 | func cancelOnSignals() {
16 | doneChan := syncx.NewDoneChan()
17 | defer doneChan.Close()
18 |
19 | go func(dc *syncx.DoneChan) {
20 | c := make(chan os.Signal)
21 | signal.Notify(c, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGINT, syscall.SIGTSTP, syscall.SIGQUIT)
22 | select {
23 | case <-c:
24 | console.Error(`
25 | migrate failed, reason: "User Canceled"`)
26 | os.Exit(0)
27 | case <-dc.Done():
28 | return
29 | }
30 | }(doneChan)
31 | }
32 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/builderx/builder.go:
--------------------------------------------------------------------------------
1 | package builderx
2 |
3 | import (
4 | "github.com/zeromicro/go-zero/core/stores/builder"
5 | )
6 |
7 | // Deprecated: Use github.com/zeromicro/go-zero/core/stores/builder.RawFieldNames instead.
8 | func FieldNames(in interface{}) []string {
9 | return builder.RawFieldNames(in)
10 | }
11 |
12 | // Deprecated: Use github.com/zeromicro/go-zero/core/stores/builder.RawFieldNames instead.
13 | func RawFieldNames(in interface{}, postgresSql ...bool) []string {
14 | return builder.RawFieldNames(in, postgresSql...)
15 | }
16 |
17 | // Deprecated: Use github.com/zeromicro/go-zero/core/stores/builderx.PostgreSqlJoin instead.
18 | func PostgreSqlJoin(elems []string) string {
19 | return builder.PostgreSqlJoin(elems)
20 | }
21 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/gen/tablename.go:
--------------------------------------------------------------------------------
1 | package gen
2 |
3 | import (
4 | "github.com/zeromicro/go-zero/tools/goctl/model/sql/template"
5 | "github.com/zeromicro/go-zero/tools/goctl/util"
6 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
7 | )
8 |
9 | func genTableName(table Table) (string, error) {
10 | text, err := pathx.LoadTemplate(category, tableNameTemplateFile, template.TableName)
11 | if err != nil {
12 | return "", err
13 | }
14 |
15 | output, err := util.With("tableName").
16 | Parse(text).
17 | Execute(map[string]interface{}{
18 | "tableName": table.Name.Source(),
19 | "upperStartCamelObject": table.Name.ToCamel(),
20 | })
21 | if err != nil {
22 | return "", nil
23 | }
24 |
25 | return output.String(), nil
26 | }
27 |
--------------------------------------------------------------------------------
/goctl/goctl/upgrade/upgrade.go:
--------------------------------------------------------------------------------
1 | package upgrade
2 |
3 | import (
4 | "fmt"
5 | "runtime"
6 |
7 | "github.com/spf13/cobra"
8 | "github.com/zeromicro/go-zero/tools/goctl/rpc/execx"
9 | )
10 |
11 | // Upgrade gets the latest goctl by
12 | // go install github.com/zeromicro/go-zero/tools/goctl@latest
13 | func upgrade(_ *cobra.Command, _ []string) error {
14 | cmd := `GO111MODULE=on GOPROXY=https://goproxy.cn/,direct go install github.com/zeromicro/go-zero/tools/goctl@latest`
15 | if runtime.GOOS == "windows" {
16 | cmd = `set GOPROXY=https://goproxy.cn,direct && go install github.com/zeromicro/go-zero/tools/goctl@latest`
17 | }
18 | info, err := execx.Run(cmd, "")
19 | if err != nil {
20 | return err
21 | }
22 |
23 | fmt.Print(info)
24 | return nil
25 | }
26 |
--------------------------------------------------------------------------------
/app/msg-gateway/cmd/wsrpc/internal/wssvc/servicecontext.go:
--------------------------------------------------------------------------------
1 | package wssvc
2 |
3 | import (
4 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/authservice"
5 | "github.com/showurl/Zero-IM-Server/app/msg-gateway/cmd/wsrpc/internal/wsconfig"
6 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/chat"
7 | "github.com/zeromicro/go-zero/zrpc"
8 | )
9 |
10 | type ServiceContext struct {
11 | Config wsconfig.Config
12 | AuthService authservice.AuthService
13 | MsgRpc chat.Chat
14 | }
15 |
16 | func NewServiceContext(c wsconfig.Config) *ServiceContext {
17 | return &ServiceContext{
18 | Config: c,
19 | AuthService: authservice.NewAuthService(zrpc.MustNewClient(c.AuthRpc)),
20 | MsgRpc: chat.NewChat(zrpc.MustNewClient(c.MsgRpc)),
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/goctl/goctl/api/validate/validate.go:
--------------------------------------------------------------------------------
1 | package validate
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 |
7 | "github.com/logrusorgru/aurora"
8 | "github.com/spf13/cobra"
9 | "github.com/zeromicro/go-zero/tools/goctl/api/parser"
10 | )
11 |
12 | // VarStringAPI describes an API.
13 | var VarStringAPI string
14 |
15 | // GoValidateApi verifies whether the api has a syntax error
16 | func GoValidateApi(_ *cobra.Command, _ []string) error {
17 | apiFile := VarStringAPI
18 |
19 | if len(apiFile) == 0 {
20 | return errors.New("missing -api")
21 | }
22 |
23 | spec, err := parser.Parse(apiFile)
24 | if err != nil {
25 | return err
26 | }
27 |
28 | err = spec.Validate()
29 | if err == nil {
30 | fmt.Println(aurora.Green("api format ok"))
31 | }
32 | return err
33 | }
34 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/handler.tpl:
--------------------------------------------------------------------------------
1 | package {{.PkgName}}
2 |
3 | import (
4 | "net/http"
5 |
6 | "github.com/zeromicro/go-zero/rest/httpx"
7 | {{.ImportPackages}}
8 | )
9 |
10 | func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc {
11 | return func(w http.ResponseWriter, r *http.Request) {
12 | {{if .HasRequest}}var req types.{{.RequestType}}
13 | if err := httpx.Parse(r, &req); err != nil {
14 | httpx.Error(w, err)
15 | return
16 | }
17 |
18 | {{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
19 | {{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}&req{{end}})
20 | if err != nil {
21 | httpx.Error(w, err)
22 | } else {
23 | {{if .HasResp}}httpx.OkJson(w, resp){{else}}httpx.Ok(w){{end}}
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/command/migrationnotes/migrationnotes.go:
--------------------------------------------------------------------------------
1 | package migrationnotes
2 |
3 | import (
4 | "github.com/zeromicro/go-zero/tools/goctl/config"
5 | "github.com/zeromicro/go-zero/tools/goctl/util/format"
6 | )
7 |
8 | // BeforeCommands run before comamnd run to show some migration notes
9 | func BeforeCommands(dir, style string) error {
10 | if err := migrateBefore1_3_4(dir, style); err != nil {
11 | return err
12 | }
13 | return nil
14 | }
15 |
16 | func getModelSuffix(style string) (string, error) {
17 | cfg, err := config.NewConfig(style)
18 | if err != nil {
19 | return "", err
20 | }
21 | baseSuffix, err := format.FileNamingFormat(cfg.NamingFormat, "_model")
22 | if err != nil {
23 | return "", err
24 | }
25 | return baseSuffix + ".go", nil
26 | }
27 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/api/handler.tpl:
--------------------------------------------------------------------------------
1 | package {{.PkgName}}
2 |
3 | import (
4 | "net/http"
5 |
6 | "github.com/zeromicro/go-zero/rest/httpx"
7 | {{.ImportPackages}}
8 | )
9 |
10 | func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc {
11 | return func(w http.ResponseWriter, r *http.Request) {
12 | {{if .HasRequest}}var req types.{{.RequestType}}
13 | if err := httpx.Parse(r, &req); err != nil {
14 | httpx.Error(w, err)
15 | return
16 | }
17 |
18 | {{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
19 | {{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}&req{{end}})
20 | if err != nil {
21 | httpx.Error(w, err)
22 | } else {
23 | {{if .HasResp}}httpx.OkJson(w, resp){{else}}httpx.Ok(w){{end}}
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/goctl/goctl/api/parser/g4/gen/api/baseparser_test.go:
--------------------------------------------------------------------------------
1 | package api
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/assert"
7 | )
8 |
9 | func TestMatch(t *testing.T) {
10 | assert.False(t, matchRegex("v1ddd", versionRegex))
11 | }
12 |
13 | func TestImportRegex(t *testing.T) {
14 | tests := []struct {
15 | value string
16 | matched bool
17 | }{
18 | {`"bar.api"`, true},
19 | {`"foo/bar.api"`, true},
20 | {`"/foo/bar.api"`, true},
21 | {`"../foo/bar.api"`, true},
22 | {`"../../foo/bar.api"`, true},
23 |
24 | {`"//bar.api"`, false},
25 | {`"/foo/foo_bar.api"`, true},
26 | }
27 | for _, tt := range tests {
28 | t.Run(tt.value, func(t *testing.T) {
29 | assert.Equal(t, tt.matched, matchRegex(tt.value, importValueRegex))
30 | })
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/common/xerr/err.go:
--------------------------------------------------------------------------------
1 | package xerr
2 |
3 | import "fmt"
4 |
5 | type CodeError struct {
6 | errCode int
7 | errMsg string
8 | }
9 |
10 | // 属性
11 | func (e *CodeError) GetErrCode() int {
12 | return e.errCode
13 | }
14 |
15 | func (e *CodeError) GetErrMsg() string {
16 | return e.errMsg
17 | }
18 |
19 | func (e *CodeError) Error() string {
20 | return fmt.Sprintf("ErrCode:%d,ErrMsg:%s", e.errCode, e.errMsg)
21 | }
22 |
23 | func New(errCode int, errMsg string) *CodeError {
24 | return &CodeError{errCode: errCode, errMsg: errMsg}
25 | }
26 |
27 | func NewErrCode(errCode int) *CodeError {
28 | return &CodeError{errCode: errCode, errMsg: MapErrMsg(errCode)}
29 | }
30 |
31 | func NewErrMsg(errMsg string) *CodeError {
32 | return &CodeError{errCode: BAD_REUQEST_ERROR, errMsg: errMsg}
33 | }
34 |
--------------------------------------------------------------------------------
/app/msg-push/cmd/rpc/internal/sdk/jpush/requestBody/message.go:
--------------------------------------------------------------------------------
1 | package requestBody
2 |
3 | type Message struct {
4 | MsgContent string `json:"msg_content"`
5 | Title string `json:"title,omitempty"`
6 | ContentType string `json:"content_type,omitempty"`
7 | Extras map[string]interface{} `json:"extras,omitempty"`
8 | }
9 |
10 | func (m *Message) SetMsgContent(c string) {
11 | m.MsgContent = c
12 | }
13 |
14 | func (m *Message) SetTitle(t string) {
15 | m.Title = t
16 | }
17 |
18 | func (m *Message) SetContentType(c string) {
19 | m.ContentType = c
20 | }
21 |
22 | func (m *Message) SetExtras(key string, value interface{}) {
23 | if m.Extras == nil {
24 | m.Extras = make(map[string]interface{})
25 | }
26 | m.Extras[key] = value
27 | }
28 |
--------------------------------------------------------------------------------
/common/xcache/global/expire.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | import (
4 | "math/rand"
5 | "time"
6 | )
7 |
8 | func ExpireDuration(second int) time.Duration {
9 | return time.Second * time.Duration(expire(second))
10 | }
11 |
12 | func expire(second int) int {
13 | return second + rand.Intn(second/10)
14 | }
15 |
16 | func Expire5Min() int {
17 | expireTime := 5 * 60
18 | return expire(expireTime)
19 | }
20 |
21 | func Expire10Min() int {
22 | expireTime := 10 * 60
23 | return expire(expireTime)
24 | }
25 |
26 | func Expire30Min() int {
27 | expireTime := 30 * 60
28 | return expire(expireTime)
29 | }
30 |
31 | func ExpireHour() int {
32 | expireTime := 60 * 60
33 | return expire(expireTime)
34 | }
35 |
36 | func ExpireDay() int {
37 | expireTime := 24 * 60 * 60
38 | return expire(expireTime)
39 | }
40 |
--------------------------------------------------------------------------------
/app/msg-push/cmd/rpc/internal/sdk/jpush/requestBody/pushObj.go:
--------------------------------------------------------------------------------
1 | package requestBody
2 |
3 | type PushObj struct {
4 | Platform interface{} `json:"platform"`
5 | Audience interface{} `json:"audience"`
6 | Notification interface{} `json:"notification,omitempty"`
7 | Message interface{} `json:"message,omitempty"`
8 | Options interface{} `json:"options,omitempty"`
9 | }
10 |
11 | func (p *PushObj) SetPlatform(pf *Platform) {
12 | p.Platform = pf.Os
13 | }
14 |
15 | func (p *PushObj) SetAudience(ad *Audience) {
16 | p.Audience = ad.Object
17 | }
18 |
19 | func (p *PushObj) SetNotification(no *Notification) {
20 | p.Notification = no
21 | }
22 |
23 | func (p *PushObj) SetMessage(m *Message) {
24 | p.Message = m
25 | }
26 | func (p *PushObj) SetOptions(o *Options) {
27 | p.Options = o
28 | }
29 |
--------------------------------------------------------------------------------
/common/utils/callerfunc.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "fmt"
5 | "runtime"
6 | "strings"
7 | )
8 |
9 | func CallerFuncName() string {
10 | pc := make([]uintptr, 1)
11 | runtime.Callers(3, pc)
12 | f := runtime.FuncForPC(pc[0])
13 | return f.Name()
14 | }
15 |
16 | func CallerFuncLine() string {
17 | pc := make([]uintptr, 1)
18 | runtime.Callers(2, pc)
19 | f := runtime.FuncForPC(pc[0])
20 | file, line := f.FileLine(pc[0])
21 | return fmt.Sprintf("%s@%d", file, line)
22 | }
23 |
24 | func cleanUpFuncName(funcName string) string {
25 | end := strings.LastIndex(funcName, ".")
26 | if end == -1 {
27 | return ""
28 | }
29 | return funcName[end+1:]
30 | }
31 | func GetSelfFuncName() string {
32 | pc, _, _, _ := runtime.Caller(1)
33 | return cleanUpFuncName(runtime.FuncForPC(pc).Name())
34 | }
35 |
--------------------------------------------------------------------------------
/goctl/goctl/api/gogen/testdata/test_api_template.api:
--------------------------------------------------------------------------------
1 | info(
2 | title: doc title
3 | desc: ">
4 | doc description first part,
5 | doc description second part<"
6 | version: 1.0
7 | )
8 |
9 | // TODO: test
10 | // {
11 | type Request struct { // TODO: test
12 | // TODO
13 | Name string `path:"name,options=you|me"` // }
14 | } // TODO: test
15 |
16 | // TODO: test
17 | type Response struct {
18 | Message string `json:"message"`
19 | }
20 |
21 | @server(
22 | // C0
23 | group: greet/s1
24 | )
25 | // C1
26 | service A-api {
27 | // C2
28 | @server( // C3
29 | handler: GreetHandler
30 | )
31 | get /greet/from/:name(Request) returns (Response) // hello
32 |
33 | // C4
34 | @handler NoResponseHandler // C5
35 | get /greet/get(Request)
36 | }
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/update.tpl:
--------------------------------------------------------------------------------
1 |
2 | func (m *default{{.upperStartCamelObject}}Model) Update(ctx context.Context, data *{{.upperStartCamelObject}}) error {
3 | {{if .withCache}}{{.keys}}
4 | _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
5 | query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder)
6 | return conn.ExecCtx(ctx, query, {{.expressionValues}})
7 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder)
8 | _,err:=m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}}
9 | return err
10 | }
11 |
--------------------------------------------------------------------------------
/goctl/goctl/api/dartgen/format.go:
--------------------------------------------------------------------------------
1 | package dartgen
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "os/exec"
7 | )
8 |
9 | const dartExec = "dart"
10 |
11 | func formatDir(dir string) error {
12 | ok, err := dirctoryExists(dir)
13 | if err != nil {
14 | return err
15 | }
16 | if !ok {
17 | return fmt.Errorf("format failed, directory %q does not exist", dir)
18 | }
19 |
20 | _, err = exec.LookPath(dartExec)
21 | if err != nil {
22 | return err
23 | }
24 | cmd := exec.Command(dartExec, "format", dir)
25 | cmd.Env = os.Environ()
26 | cmd.Stderr = os.Stderr
27 |
28 | return cmd.Run()
29 | }
30 |
31 | func dirctoryExists(dir string) (bool, error) {
32 | _, err := os.Stat(dir)
33 | if err == nil {
34 | return true, nil
35 | }
36 | if os.IsNotExist(err) {
37 | return false, nil
38 | }
39 | return false, err
40 | }
41 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/util/matcher.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import (
4 | "io/ioutil"
5 | "path/filepath"
6 | )
7 |
8 | // MatchFiles returns the match values by globbing patterns
9 | func MatchFiles(in string) ([]string, error) {
10 | dir, pattern := filepath.Split(in)
11 | abs, err := filepath.Abs(dir)
12 | if err != nil {
13 | return nil, err
14 | }
15 |
16 | files, err := ioutil.ReadDir(abs)
17 | if err != nil {
18 | return nil, err
19 | }
20 | var res []string
21 | for _, file := range files {
22 | if file.IsDir() {
23 | continue
24 | }
25 | name := file.Name()
26 | match, err := filepath.Match(pattern, name)
27 | if err != nil {
28 | return nil, err
29 | }
30 |
31 | if !match {
32 | continue
33 | }
34 |
35 | res = append(res, filepath.Join(abs, name))
36 | }
37 | return res, nil
38 | }
39 |
--------------------------------------------------------------------------------
/goctl/goctl/api/javagen/packet.tpl:
--------------------------------------------------------------------------------
1 | package com.xhb.logic.http.packet.{{.packet}};
2 |
3 | import com.xhb.core.packet.HttpPacket;
4 | import com.xhb.core.network.HttpRequestClient;
5 | {{.imports}}
6 |
7 | {{.doc}}
8 | public class {{.packetName}} extends HttpPacket<{{.responseType}}> {
9 | {{.paramsDeclaration}}
10 |
11 | public {{.packetName}}({{.params}}{{if .HasRequestBody}}{{.requestType}} request{{end}}) {
12 | {{if .HasRequestBody}}super(request);{{else}}super(EmptyRequest.instance);{{end}}
13 | {{if .HasRequestBody}}this.request = request;{{end}}{{.paramsSetter}}
14 | }
15 |
16 | @Override
17 | public HttpRequestClient.Method requestMethod() {
18 | return HttpRequestClient.Method.{{.method}};
19 | }
20 |
21 | @Override
22 | public String requestUri() {
23 | return {{.uri}};
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/common/xcache/client.go:
--------------------------------------------------------------------------------
1 | package xcache
2 |
3 | import (
4 | "context"
5 | "github.com/go-redis/redis/v8"
6 | "github.com/showurl/Zero-IM-Server/common/xcache/global"
7 | zeroredis "github.com/zeromicro/go-zero/core/stores/redis"
8 | "log"
9 | )
10 |
11 | func GetClient(
12 | cfg zeroredis.RedisConf,
13 | db global.DB,
14 | ) redis.UniversalClient {
15 | // 打印配置
16 | log.Printf("redis config: %+v", cfg)
17 | opts := &redis.UniversalOptions{
18 | Addrs: []string{cfg.Host},
19 | DB: db.Int(),
20 | //PoolSize: 15,
21 | //MinIdleConns: 5, // redis连接池最小空闲连接数.
22 | Password: cfg.Pass,
23 | //ReadTimeout: 5,
24 | }
25 | rc := redis.NewUniversalClient(opts)
26 | err := rc.Ping(context.Background()).Err()
27 | if err != nil {
28 | log.Printf("redis ping error: %+v", err)
29 | panic(err)
30 | }
31 | return rc
32 | }
33 |
--------------------------------------------------------------------------------
/app/msg/cmd/rpc/internal/logic/sendMsgStruct.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | type MsgCallBackReq struct {
4 | SendID string `json:"sendID"`
5 | RecvID string `json:"recvID"`
6 | Content string `json:"content"`
7 | SendTime int64 `json:"sendTime"`
8 | MsgFrom int32 `json:"msgFrom"`
9 | ContentType int32 `json:"contentType"`
10 | SessionType int32 `json:"sessionType"`
11 | PlatformID int32 `json:"senderPlatformID"`
12 | MsgID string `json:"msgID"`
13 | IsOnlineOnly bool `json:"isOnlineOnly"`
14 | }
15 | type MsgCallBackResp struct {
16 | ErrCode int32 `json:"errCode"`
17 | ErrMsg string `json:"errMsg"`
18 | ResponseErrCode int32 `json:"responseErrCode"`
19 | ResponseResult struct {
20 | ModifiedMsg string `json:"modifiedMsg"`
21 | Ext string `json:"ext"`
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/example/makefile:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # generate model with cache from ddl
4 | fromDDLWithCache:
5 | goctl template clean
6 | goctl model mysql ddl -src="./sql/*.sql" -dir="./sql/model/cache" -cache
7 |
8 | fromDDLWithCacheAndDb:
9 | goctl template clean
10 | goctl model mysql ddl -src="./sql/*.sql" -dir="./sql/model/cache_db" -database="1gozero" -cache
11 |
12 | fromDDLWithoutCache:
13 | goctl template clean;
14 | goctl model mysql ddl -src="./sql/*.sql" -dir="./sql/model/nocache"
15 |
16 |
17 | # generate model with cache from data source
18 | user=root
19 | password=password
20 | datasource=127.0.0.1:3306
21 | database=gozero
22 |
23 | fromDataSource:
24 | goctl template clean
25 | goctl model mysql datasource -url="$(user):$(password)@tcp($(datasource))/$(database)" -table="*" -dir ./model/cache -c -style gozero
26 |
--------------------------------------------------------------------------------
/app/msg/cmd/rpc/internal/logic/delMsgListLogic.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 |
6 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/internal/svc"
7 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/pb"
8 |
9 | "github.com/zeromicro/go-zero/core/logx"
10 | )
11 |
12 | type DelMsgListLogic struct {
13 | ctx context.Context
14 | svcCtx *svc.ServiceContext
15 | logx.Logger
16 | }
17 |
18 | func NewDelMsgListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelMsgListLogic {
19 | return &DelMsgListLogic{
20 | ctx: ctx,
21 | svcCtx: svcCtx,
22 | Logger: logx.WithContext(ctx),
23 | }
24 | }
25 |
26 | func (l *DelMsgListLogic) DelMsgList(in *pb.WrapDelMsgListReq) (*pb.WrapDelMsgListResp, error) {
27 | // todo: add your logic here and delete this line
28 |
29 | return &pb.WrapDelMsgListResp{}, nil
30 | }
31 |
--------------------------------------------------------------------------------
/goctl/goctl/model/mongo/generate/generate_test.go:
--------------------------------------------------------------------------------
1 | package generate
2 |
3 | import (
4 | "io/ioutil"
5 | "path/filepath"
6 | "testing"
7 |
8 | "github.com/stretchr/testify/assert"
9 | "github.com/zeromicro/go-zero/tools/goctl/config"
10 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
11 | )
12 |
13 | var testTypes = `
14 | type User struct{}
15 | type Class struct{}
16 | `
17 |
18 | func TestDo(t *testing.T) {
19 | cfg, err := config.NewConfig(config.DefaultFormat)
20 | assert.Nil(t, err)
21 |
22 | tempDir := pathx.MustTempDir()
23 | typesfile := filepath.Join(tempDir, "types.go")
24 | err = ioutil.WriteFile(typesfile, []byte(testTypes), 0o666)
25 | assert.Nil(t, err)
26 |
27 | err = Do(&Context{
28 | Types: []string{"User", "Class"},
29 | Cache: false,
30 | Output: tempDir,
31 | Cfg: cfg,
32 | })
33 |
34 | assert.Nil(t, err)
35 | }
36 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/gen/testdata/user.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE `test_user`
2 | (
3 | `id` bigint NOT NULL AUTO_INCREMENT,
4 | `mobile` varchar(255) COLLATE utf8mb4_bin NOT NULL,
5 | `class` bigint NOT NULL,
6 | `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
7 | `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
8 | `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
9 | PRIMARY KEY (`id`),
10 | UNIQUE KEY `mobile_unique` (`mobile`),
11 | UNIQUE KEY `class_name_unique` (`class`,`name`),
12 | KEY `create_index` (`create_time`),
13 | KEY `name_index` (`name`)
14 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
--------------------------------------------------------------------------------
/app/auth/cmd/rpc/internal/server/authServiceServer.go:
--------------------------------------------------------------------------------
1 | // Code generated by goctl. DO NOT EDIT!
2 | // Source: auth.proto
3 |
4 | package server
5 |
6 | import (
7 | "context"
8 |
9 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/internal/logic"
10 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/internal/svc"
11 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/pb"
12 | )
13 |
14 | type AuthServiceServer struct {
15 | svcCtx *svc.ServiceContext
16 | pb.UnimplementedAuthServiceServer
17 | }
18 |
19 | func NewAuthServiceServer(svcCtx *svc.ServiceContext) *AuthServiceServer {
20 | return &AuthServiceServer{
21 | svcCtx: svcCtx,
22 | }
23 | }
24 |
25 | func (s *AuthServiceServer) VerifyToken(ctx context.Context, in *pb.VerifyTokenReq) (*pb.VerifyTokenResp, error) {
26 | l := logic.NewVerifyTokenLogic(ctx, s.svcCtx)
27 | return l.VerifyToken(in)
28 | }
29 |
--------------------------------------------------------------------------------
/common/utils/str/difference.go:
--------------------------------------------------------------------------------
1 | package strUtils
2 |
3 | //Get the intersection of two slices
4 | func IntersectString(slice1, slice2 []string) []string {
5 | m := make(map[string]bool)
6 | n := make([]string, 0)
7 | for _, v := range slice1 {
8 | m[v] = true
9 | }
10 | for _, v := range slice2 {
11 | flag, _ := m[v]
12 | if flag {
13 | n = append(n, v)
14 | }
15 | }
16 | return n
17 | }
18 |
19 | //Get the diff of two slices
20 | func DifferenceString(slice1, slice2 []string) []string {
21 | m := make(map[string]bool)
22 | n := make([]string, 0)
23 | inter := IntersectString(slice1, slice2)
24 | for _, v := range inter {
25 | m[v] = true
26 | }
27 | for _, v := range slice1 {
28 | if !m[v] {
29 | n = append(n, v)
30 | }
31 | }
32 |
33 | for _, v := range slice2 {
34 | if !m[v] {
35 | n = append(n, v)
36 | }
37 | }
38 | return n
39 | }
40 |
--------------------------------------------------------------------------------
/goctl/goctl/util/pathx/path_test.go:
--------------------------------------------------------------------------------
1 | package pathx
2 |
3 | import (
4 | "io/ioutil"
5 | "os"
6 | "path/filepath"
7 | "testing"
8 |
9 | "github.com/stretchr/testify/assert"
10 | )
11 |
12 | func TestReadLink(t *testing.T) {
13 | dir, err := ioutil.TempDir("", "go-zero")
14 | assert.Nil(t, err)
15 | symLink := filepath.Join(dir, "test")
16 | pwd, err := os.Getwd()
17 | assertError(err, t)
18 |
19 | err = os.Symlink(pwd, symLink)
20 | assertError(err, t)
21 |
22 | t.Run("linked", func(t *testing.T) {
23 | ret, err := ReadLink(symLink)
24 | assert.Nil(t, err)
25 | assert.Equal(t, pwd, ret)
26 | })
27 |
28 | t.Run("unlink", func(t *testing.T) {
29 | ret, err := ReadLink(pwd)
30 | assert.Nil(t, err)
31 | assert.Equal(t, pwd, ret)
32 | })
33 | }
34 |
35 | func assertError(err error, t *testing.T) {
36 | if err != nil {
37 | t.Fatal(err)
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/common/xorm/global/generateId.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | import (
4 | "github.com/bwmarrin/snowflake"
5 | "github.com/showurl/Zero-IM-Server/common/utils/encrypt"
6 | "math/rand"
7 | "time"
8 | )
9 |
10 | var (
11 | c = make(chan string)
12 | nd *snowflake.Node
13 | NodId int64
14 | uniquePodId string
15 | )
16 |
17 | func init() {
18 | rand.Seed(time.Now().UnixNano())
19 | NodId = int64(rand.Intn(128))
20 | nd, _ = snowflake.NewNode(NodId)
21 | uniquePodId = nd.Generate().String()
22 | go loop()
23 | }
24 |
25 | func loop() {
26 | for {
27 | c <- nd.Generate().String()
28 | }
29 | }
30 |
31 | // GetID 获取ID
32 | // 参数: podId 当前机器标识 这里使用 pod ip
33 | func GetID() string {
34 | md5 := encrypt.Md5(uniquePodId + <-c)
35 | //fmt.Println("md5:", md5)
36 | return md5
37 | }
38 |
39 | func ReplacePodID(podId string) {
40 | uniquePodId = podId
41 | }
42 |
--------------------------------------------------------------------------------
/app/msg/cmd/rpc/internal/logic/getMaxAndMinSeqLogic.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 |
6 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/internal/svc"
7 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/pb"
8 |
9 | "github.com/zeromicro/go-zero/core/logx"
10 | )
11 |
12 | type GetMaxAndMinSeqLogic struct {
13 | ctx context.Context
14 | svcCtx *svc.ServiceContext
15 | logx.Logger
16 | }
17 |
18 | func NewGetMaxAndMinSeqLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMaxAndMinSeqLogic {
19 | return &GetMaxAndMinSeqLogic{
20 | ctx: ctx,
21 | svcCtx: svcCtx,
22 | Logger: logx.WithContext(ctx),
23 | }
24 | }
25 |
26 | func (l *GetMaxAndMinSeqLogic) GetMaxAndMinSeq(in *pb.GetMaxAndMinSeqReq) (*pb.GetMaxAndMinSeqResp, error) {
27 | // todo: add your logic here and delete this line
28 |
29 | return &pb.GetMaxAndMinSeqResp{}, nil
30 | }
31 |
--------------------------------------------------------------------------------
/app/auth/cmd/rpc/internal/logic/verifyTokenLogic.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 |
6 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/internal/svc"
7 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/pb"
8 |
9 | "github.com/zeromicro/go-zero/core/logx"
10 | )
11 |
12 | type VerifyTokenLogic struct {
13 | ctx context.Context
14 | svcCtx *svc.ServiceContext
15 | logx.Logger
16 | }
17 |
18 | func NewVerifyTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VerifyTokenLogic {
19 | return &VerifyTokenLogic{
20 | ctx: ctx,
21 | svcCtx: svcCtx,
22 | Logger: logx.WithContext(ctx),
23 | }
24 | }
25 |
26 | func (l *VerifyTokenLogic) VerifyToken(in *pb.VerifyTokenReq) (*pb.VerifyTokenResp, error) {
27 | // todo: add your logic here and delete this line
28 |
29 | return &pb.VerifyTokenResp{
30 | Uid: in.SendID,
31 | Success: true,
32 | ErrMsg: "",
33 | }, nil
34 | }
35 |
--------------------------------------------------------------------------------
/goctl/home/1.3.6-beta/model/delete.tpl:
--------------------------------------------------------------------------------
1 |
2 | func (m *default{{.upperStartCamelObject}}Model) Delete(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) error {
3 | {{if .withCache}}{{if .containsIndexCache}}data, err:=m.FindOne(ctx, {{.lowerStartCamelPrimaryKey}})
4 | if err!=nil{
5 | return err
6 | }
7 |
8 | {{end}} {{.keys}}
9 | _, err {{if .containsIndexCache}}={{else}}:={{end}} m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
10 | query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table)
11 | return conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}})
12 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table)
13 | _,err:=m.conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}}){{end}}
14 | return err
15 | }
16 |
--------------------------------------------------------------------------------
/common/types/rediskey.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | const (
4 | RedisKeyAccountTempCode = "ACCOUNT_TEMP_CODE"
5 | RedisKeyResetPwdTempCode = "RESET_PWD_TEMP_CODE"
6 | RedisKeyUserIncrSeq = "REDIS_USER_INCR_SEQ:" // user incr seq
7 | RedisKeySuperGroupIncrSeq = "REDIS_SUPER_GROUP_INCR_SEQ:" // user incr seq
8 | RedisKeyAppleDeviceToken = "DEVICE_TOKEN"
9 | RedisKeyUserMinSeq = "REDIS_USER_MIN_SEQ:"
10 | RedisKeyUidPidToken = "UID_PID_TOKEN_STATUS:"
11 | RedisKeyConversationReceiveMessageOpt = "CON_RECV_MSG_OPT:"
12 | RedisKeyGetuiToken = "GETUI"
13 | RedisKeyUserInfoCache = "USER_INFO_CACHE:"
14 | RedisKeyFriendRelationCache = "FRIEND_RELATION_CACHE:"
15 | RedisKeyBlackListCache = "BLACK_LIST_CACHE:"
16 | RedisKeyGroupCache = "GROUP_CACHE:"
17 | )
18 |
--------------------------------------------------------------------------------
/goctl/goctl/model/sql/parser/testdata/user.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE `test_user`
2 | (
3 | `id` bigint NOT NULL AUTO_INCREMENT,
4 | `mobile` varchar(255) COLLATE utf8mb4_bin NOT NULL comment '手\t机 号',
5 | `class` bigint NOT NULL comment '班级',
6 | `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL comment '姓
7 | 名',
8 | `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP comment '创建\r时间',
9 | `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
10 | PRIMARY KEY (`id`),
11 | UNIQUE KEY `mobile_unique` (`mobile`),
12 | UNIQUE KEY `class_name_unique` (`class`,`name`),
13 | KEY `create_index` (`create_time`),
14 | KEY `name_index` (`name`)
15 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
--------------------------------------------------------------------------------
/app/msg-callback/cmd/rpc/internal/logic/callbackWordFilterLogic.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 |
6 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/internal/svc"
7 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/pb"
8 |
9 | "github.com/zeromicro/go-zero/core/logx"
10 | )
11 |
12 | type CallbackWordFilterLogic struct {
13 | ctx context.Context
14 | svcCtx *svc.ServiceContext
15 | logx.Logger
16 | }
17 |
18 | func NewCallbackWordFilterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackWordFilterLogic {
19 | return &CallbackWordFilterLogic{
20 | ctx: ctx,
21 | svcCtx: svcCtx,
22 | Logger: logx.WithContext(ctx),
23 | }
24 | }
25 |
26 | func (l *CallbackWordFilterLogic) CallbackWordFilter(in *pb.CallbackWordFilterReq) (*pb.CallbackWordFilterResp, error) {
27 | // todo: add your logic here and delete this line
28 |
29 | return &pb.CallbackWordFilterResp{}, nil
30 | }
31 |
--------------------------------------------------------------------------------
/app/msg/cmd/rpc/internal/logic/pullMessageBySeqListLogic.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 |
6 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/internal/svc"
7 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/pb"
8 |
9 | "github.com/zeromicro/go-zero/core/logx"
10 | )
11 |
12 | type PullMessageBySeqListLogic struct {
13 | ctx context.Context
14 | svcCtx *svc.ServiceContext
15 | logx.Logger
16 | }
17 |
18 | func NewPullMessageBySeqListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PullMessageBySeqListLogic {
19 | return &PullMessageBySeqListLogic{
20 | ctx: ctx,
21 | svcCtx: svcCtx,
22 | Logger: logx.WithContext(ctx),
23 | }
24 | }
25 |
26 | func (l *PullMessageBySeqListLogic) PullMessageBySeqList(in *pb.WrapPullMessageBySeqListReq) (*pb.WrapPullMessageBySeqListResp, error) {
27 | // todo: add your logic here and delete this line
28 |
29 | return &pb.WrapPullMessageBySeqListResp{}, nil
30 | }
31 |
--------------------------------------------------------------------------------
/common/xetcd/gozero_test.go:
--------------------------------------------------------------------------------
1 | package xetcd
2 |
3 | import (
4 | "context"
5 | "github.com/showurl/Zero-IM-Server/app/msg-gateway/cmd/wsrpc/onlineMessageRelayService"
6 | "github.com/showurl/Zero-IM-Server/app/msg-gateway/cmd/wsrpc/pb"
7 | "github.com/zeromicro/go-zero/core/discov"
8 | "testing"
9 | )
10 |
11 | func TestGetGoZeroZrpcConns(t *testing.T) {
12 | zrpcConns, err := GetGoZeroZrpcConns(context.TODO(), NewClient(discov.EtcdConf{
13 | Hosts: []string{"127.0.0.1:2379"},
14 | }), "msggateway-rpc")
15 | if err != nil {
16 | t.Error(err)
17 | }
18 | for _, conn := range zrpcConns {
19 | onlineStatus, err := onlinemessagerelayservice.NewOnlineMessageRelayService(conn).GetUsersOnlineStatus(context.TODO(), &pb.GetUsersOnlineStatusReq{
20 | UserIDList: []string{"1", "2"},
21 | OperationID: "",
22 | OpUserID: "",
23 | })
24 | if err != nil {
25 | t.Error(err)
26 | }
27 | t.Log(onlineStatus.ErrCode)
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/app/msg-push/cmd/rpc/internal/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "github.com/showurl/Zero-IM-Server/common/xkafka"
5 | "github.com/zeromicro/go-zero/zrpc"
6 | )
7 |
8 | type Config struct {
9 | zrpc.RpcServerConf
10 | PushType string `json:",default=jpns,options=jpns|mobpush"`
11 | //MsgGatewayEtcd discov.EtcdConf
12 | Jpns JpnsConf
13 | MsgGatewayRpc zrpc.RpcClientConf
14 | ImUserRpc zrpc.RpcClientConf
15 | SinglePushConsumer SinglePushConsumerConfig
16 | SuperGroupPushConsumer SuperGroupPushConsumerConfig
17 | }
18 | type JpnsConf struct {
19 | PushIntent string
20 | PushUrl string
21 | AppKey string
22 | MasterSecret string
23 | }
24 |
25 | type SinglePushConsumerConfig struct {
26 | xkafka.ProducerConfig
27 | SinglePushGroupID string
28 | }
29 |
30 | type SuperGroupPushConsumerConfig struct {
31 | xkafka.ProducerConfig
32 | SuperGroupPushGroupID string
33 | }
34 |
--------------------------------------------------------------------------------
/common/utils/env/env.go:
--------------------------------------------------------------------------------
1 | package envUtils
2 |
3 | import "os"
4 |
5 | const (
6 | EnvKey = "ENV"
7 | )
8 |
9 | type TypEnv string
10 |
11 | var (
12 | env TypEnv
13 | )
14 |
15 | const (
16 | envDev TypEnv = "dev"
17 | envTest TypEnv = "test"
18 | envPre TypEnv = "pre"
19 | envProd TypEnv = "prod"
20 | )
21 |
22 | func init() {
23 | getEnv := TypEnv(os.Getenv(EnvKey))
24 | if getEnv == "" {
25 | env = "local"
26 | } else {
27 | env = getEnv
28 | }
29 | }
30 |
31 | func IsDev() bool {
32 | return env == envDev
33 | }
34 |
35 | func IsTest() bool {
36 | return env == envTest
37 | }
38 |
39 | func IsPre() bool {
40 | return env == envPre
41 | }
42 |
43 | func IsProd() bool {
44 | return env == envProd
45 | }
46 |
47 | func IsCustom() bool {
48 | return !IsDev() && !IsTest() && !IsPre() && !IsProd()
49 | }
50 |
51 | func Env() TypEnv {
52 | return env
53 | }
54 |
55 | func (t TypEnv) String() string {
56 | return string(t)
57 | }
58 |
--------------------------------------------------------------------------------
/app/msg-push/cmd/rpc/internal/sdk/jpush/requestBody/notification.go:
--------------------------------------------------------------------------------
1 | package requestBody
2 |
3 | type Notification struct {
4 | Alert string `json:"alert,omitempty"`
5 | Android Android `json:"android,omitempty"`
6 | IOS Ios `json:"ios,omitempty"`
7 | }
8 |
9 | type Android struct {
10 | Alert string `json:"alert,omitempty"`
11 | Intent struct {
12 | URL string `json:"url,omitempty"`
13 | } `json:"intent,omitempty"`
14 | }
15 | type Ios struct {
16 | Alert string `json:"alert,omitempty"`
17 | Sound string `json:"sound,omitempty"`
18 | Badge string `json:"badge,omitempty"`
19 | }
20 |
21 | func (n *Notification) SetAlert(alert, pushIntent string) {
22 | n.Alert = alert
23 | n.Android.Alert = alert
24 | n.SetAndroidIntent(pushIntent)
25 | n.IOS.Alert = alert
26 | n.IOS.Sound = "default"
27 | n.IOS.Badge = "+1"
28 |
29 | }
30 | func (n *Notification) SetAndroidIntent(pushIntent string) {
31 | n.Android.Intent.URL = pushIntent
32 | }
33 |
--------------------------------------------------------------------------------
/goctl/goctl/bug/issue.go:
--------------------------------------------------------------------------------
1 | package bug
2 |
3 | const issueTemplate = `
4 |
5 |
6 | ### What category of issue (goctl or sdk)?
7 |
8 | ### What type of issue (feature|bug|suggestion)?
9 |
10 | ### What version of Goctl are you using (goctl --version)?
11 |
12 |
13 | $ goctl --version 14 | %s 15 |16 | 17 | ### Does this issue reproduce with the latest release? 18 | 19 | 20 | ### What operating system and processor architecture are you using ? 21 |
22 | %s 23 |24 | 25 | ### What did you do? 26 | 27 | 32 | 33 | 34 | 35 | ### What did you expect to see? 36 | 37 | 38 | 39 | ### What did you see instead? 40 | 41 | 42 | ` 43 | -------------------------------------------------------------------------------- /goctl/goctl/model/sql/command/testdata/user.sql: -------------------------------------------------------------------------------- 1 | -- 用户表 -- 2 | CREATE TABLE `user` 3 | ( 4 | `id` bigint(10) NOT NULL AUTO_INCREMENT, 5 | `name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户名称', 6 | `password` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户密码', 7 | `mobile` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手机号', 8 | `gender` char(5) COLLATE utf8mb4_general_ci NOT NULL COMMENT '男|女|未公开', 9 | `nickname` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '用户昵称', 10 | `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 11 | `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 12 | PRIMARY KEY (`id`), 13 | UNIQUE KEY `name_index` (`name`), 14 | UNIQUE KEY `mobile_index` (`mobile`) 15 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; 16 | 17 | -------------------------------------------------------------------------------- /goctl/goctl/api/parser/g4/gen/api/apiparser_parser9.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/zeromicro/antlr" 7 | ) 8 | 9 | // Part 9 10 | // The apiparser_parser.go file was split into multiple files because it 11 | // was too large and caused a possible memory overflow during goctl installation. 12 | 13 | func (p *ApiParserParser) Sempred(localctx antlr.RuleContext, ruleIndex, predIndex int) bool { 14 | switch ruleIndex { 15 | case 18: 16 | var t *FieldContext = nil 17 | if localctx != nil { 18 | t = localctx.(*FieldContext) 19 | } 20 | return p.Field_Sempred(t, predIndex) 21 | 22 | default: 23 | panic("No predicate with index: " + fmt.Sprint(ruleIndex)) 24 | } 25 | } 26 | 27 | func (p *ApiParserParser) Field_Sempred(localctx antlr.RuleContext, predIndex int) bool { 28 | switch predIndex { 29 | case 0: 30 | return isNormal(p) 31 | 32 | default: 33 | panic("No predicate with index: " + fmt.Sprint(predIndex)) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /app/msg-transfer/cmd/history/internal/svc/serviceContext.go: -------------------------------------------------------------------------------- 1 | package svc 2 | 3 | import ( 4 | "github.com/showurl/Zero-IM-Server/app/msg-push/cmd/rpc/msgpushservice" 5 | "github.com/showurl/Zero-IM-Server/app/msg-transfer/cmd/history/internal/config" 6 | "github.com/showurl/Zero-IM-Server/common/xkafka" 7 | "github.com/zeromicro/go-zero/zrpc" 8 | ) 9 | 10 | type ServiceContext struct { 11 | Config config.Config 12 | SinglePushProducer *xkafka.Producer 13 | SuperGroupPushProducer *xkafka.Producer 14 | MsgPush msgpushservice.MsgPushService 15 | } 16 | 17 | func NewServiceContext(c config.Config) *ServiceContext { 18 | return &ServiceContext{ 19 | Config: c, 20 | SinglePushProducer: xkafka.MustNewProducer(c.Kafka.SinglePush), 21 | SuperGroupPushProducer: xkafka.MustNewProducer(c.Kafka.SuperGroupPush), 22 | MsgPush: msgpushservice.NewMsgPushService(zrpc.MustNewClient(c.MsgPushRpc)), 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /goctl/goctl/model/sql/template/import.go: -------------------------------------------------------------------------------- 1 | package template 2 | 3 | const ( 4 | // Imports defines a import template for model in cache case 5 | Imports = `import ( 6 | "context" 7 | "database/sql" 8 | "fmt" 9 | "strings" 10 | {{if .time}}"time"{{end}} 11 | 12 | "github.com/zeromicro/go-zero/core/stores/builder" 13 | "github.com/zeromicro/go-zero/core/stores/cache" 14 | "github.com/zeromicro/go-zero/core/stores/sqlc" 15 | "github.com/zeromicro/go-zero/core/stores/sqlx" 16 | "github.com/zeromicro/go-zero/core/stringx" 17 | ) 18 | ` 19 | // ImportsNoCache defines a import template for model in normal case 20 | ImportsNoCache = `import ( 21 | "context" 22 | "database/sql" 23 | "fmt" 24 | "strings" 25 | {{if .time}}"time"{{end}} 26 | 27 | "github.com/zeromicro/go-zero/core/stores/builder" 28 | "github.com/zeromicro/go-zero/core/stores/sqlc" 29 | "github.com/zeromicro/go-zero/core/stores/sqlx" 30 | "github.com/zeromicro/go-zero/core/stringx" 31 | ) 32 | ` 33 | ) 34 | -------------------------------------------------------------------------------- /app/msg-callback/cmd/rpc/internal/logic/callbackAfterSendGroupMsgLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type CallbackAfterSendGroupMsgLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewCallbackAfterSendGroupMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackAfterSendGroupMsgLogic { 19 | return &CallbackAfterSendGroupMsgLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | func (l *CallbackAfterSendGroupMsgLogic) CallbackAfterSendGroupMsg(in *pb.CallbackSendGroupMsgReq) (*pb.CommonCallbackResp, error) { 27 | // todo: add your logic here and delete this line 28 | 29 | return &pb.CommonCallbackResp{}, nil 30 | } 31 | -------------------------------------------------------------------------------- /goctl/goctl/internal/errorx/errorx.go: -------------------------------------------------------------------------------- 1 | package errorx 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "github.com/zeromicro/go-zero/tools/goctl/pkg/env" 8 | ) 9 | 10 | var errorFormat = `goctl error: %+v 11 | goctl env: 12 | %s 13 | %s` 14 | 15 | // GoctlError represents a goctl error. 16 | type GoctlError struct { 17 | message []string 18 | err error 19 | } 20 | 21 | func (e *GoctlError) Error() string { 22 | detail := wrapMessage(e.message...) 23 | return fmt.Sprintf(errorFormat, e.err, env.Print(), detail) 24 | } 25 | 26 | // Wrap wraps an error with goctl version and message. 27 | func Wrap(err error, message ...string) error { 28 | e, ok := err.(*GoctlError) 29 | if ok { 30 | return e 31 | } 32 | 33 | return &GoctlError{ 34 | message: message, 35 | err: err, 36 | } 37 | } 38 | 39 | func wrapMessage(message ...string) string { 40 | if len(message) == 0 { 41 | return "" 42 | } 43 | return fmt.Sprintf(`message: %s`, strings.Join(message, "\n")) 44 | } 45 | -------------------------------------------------------------------------------- /app/conversation/cmd/rpc/internal/logic/modifyConversationFieldLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/conversation/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/conversation/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type ModifyConversationFieldLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewModifyConversationFieldLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ModifyConversationFieldLogic { 19 | return &ModifyConversationFieldLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | func (l *ModifyConversationFieldLogic) ModifyConversationField(in *pb.ModifyConversationFieldReq) (*pb.ModifyConversationFieldResp, error) { 27 | // todo: add your logic here and delete this line 28 | 29 | return &pb.ModifyConversationFieldResp{}, nil 30 | } 31 | -------------------------------------------------------------------------------- /app/msg-callback/cmd/rpc/internal/logic/callbackBeforeSendGroupMsgLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type CallbackBeforeSendGroupMsgLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewCallbackBeforeSendGroupMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackBeforeSendGroupMsgLogic { 19 | return &CallbackBeforeSendGroupMsgLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | func (l *CallbackBeforeSendGroupMsgLogic) CallbackBeforeSendGroupMsg(in *pb.CallbackSendGroupMsgReq) (*pb.CommonCallbackResp, error) { 27 | // todo: add your logic here and delete this line 28 | 29 | return &pb.CommonCallbackResp{}, nil 30 | } 31 | -------------------------------------------------------------------------------- /goctl/goctl/rpc/generator/main.tpl: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | {{.imports}} 8 | 9 | "github.com/zeromicro/go-zero/core/conf" 10 | "github.com/zeromicro/go-zero/core/service" 11 | "github.com/zeromicro/go-zero/zrpc" 12 | "google.golang.org/grpc" 13 | "google.golang.org/grpc/reflection" 14 | ) 15 | 16 | var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file") 17 | 18 | func main() { 19 | flag.Parse() 20 | 21 | var c config.Config 22 | conf.MustLoad(*configFile, &c) 23 | ctx := svc.NewServiceContext(c) 24 | svr := server.New{{.serviceNew}}Server(ctx) 25 | 26 | s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { 27 | {{.pkg}}.Register{{.service}}Server(grpcServer, svr) 28 | 29 | if c.Mode == service.DevMode || c.Mode == service.TestMode { 30 | reflection.Register(grpcServer) 31 | } 32 | }) 33 | defer s.Stop() 34 | 35 | fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) 36 | s.Start() 37 | } 38 | -------------------------------------------------------------------------------- /goctl/home/1.3.6-beta/rpc/main.tpl: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | {{.imports}} 8 | 9 | "github.com/zeromicro/go-zero/core/conf" 10 | "github.com/zeromicro/go-zero/core/service" 11 | "github.com/zeromicro/go-zero/zrpc" 12 | "google.golang.org/grpc" 13 | "google.golang.org/grpc/reflection" 14 | ) 15 | 16 | var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file") 17 | 18 | func main() { 19 | flag.Parse() 20 | 21 | var c config.Config 22 | conf.MustLoad(*configFile, &c) 23 | ctx := svc.NewServiceContext(c) 24 | svr := server.New{{.serviceNew}}Server(ctx) 25 | 26 | s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { 27 | {{.pkg}}.Register{{.service}}Server(grpcServer, svr) 28 | 29 | if c.Mode == service.DevMode || c.Mode == service.TestMode { 30 | reflection.Register(grpcServer) 31 | } 32 | }) 33 | defer s.Stop() 34 | 35 | fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) 36 | s.Start() 37 | } 38 | -------------------------------------------------------------------------------- /goctl/goctl/Makefile: -------------------------------------------------------------------------------- 1 | build: 2 | go build -ldflags="-s -w" goctl.go 3 | $(if $(shell command -v upx), upx goctl) 4 | 5 | mac: 6 | GOOS=darwin go build -ldflags="-s -w" -o goctl-darwin goctl.go 7 | $(if $(shell command -v upx), upx goctl-darwin) 8 | 9 | win: 10 | GOOS=windows go build -ldflags="-s -w" -o goctl.exe goctl.go 11 | $(if $(shell command -v upx), upx goctl.exe) 12 | 13 | linux: 14 | GOOS=linux go build -ldflags="-s -w" -o goctl-linux goctl.go 15 | $(if $(shell command -v upx), upx goctl-linux) 16 | 17 | image: 18 | docker build --rm --platform linux/amd64 -t kevinwan/goctl:$(version) . 19 | docker tag kevinwan/goctl:$(version) kevinwan/goctl:latest 20 | docker push kevinwan/goctl:$(version) 21 | docker push kevinwan/goctl:latest 22 | docker build --rm --platform linux/arm64 -t kevinwan/goctl:$(version)-arm64 . 23 | docker tag kevinwan/goctl:$(version)-arm64 kevinwan/goctl:latest-arm64 24 | docker push kevinwan/goctl:$(version)-arm64 25 | docker push kevinwan/goctl:latest-arm64 26 | -------------------------------------------------------------------------------- /goctl/goctl/model/sql/util/match_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "path/filepath" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestMatchFiles(t *testing.T) { 11 | dir, err := filepath.Abs("./") 12 | assert.Nil(t, err) 13 | 14 | files, err := MatchFiles("./*.sql") 15 | assert.Nil(t, err) 16 | assert.Equal(t, []string{filepath.Join(dir, "studeat.sql"), filepath.Join(dir, "student.sql"), filepath.Join(dir, "xx.sql")}, files) 17 | 18 | files, err = MatchFiles("./??.sql") 19 | assert.Nil(t, err) 20 | assert.Equal(t, []string{filepath.Join(dir, "xx.sql")}, files) 21 | 22 | files, err = MatchFiles("./*.sq*") 23 | assert.Nil(t, err) 24 | assert.Equal(t, []string{filepath.Join(dir, "studeat.sql"), filepath.Join(dir, "student.sql"), filepath.Join(dir, "xx.sql"), filepath.Join(dir, "xx.sql1")}, files) 25 | 26 | files, err = MatchFiles("./student.sql") 27 | assert.Nil(t, err) 28 | assert.Equal(t, []string{filepath.Join(dir, "student.sql")}, files) 29 | } 30 | -------------------------------------------------------------------------------- /app/msg-push/cmd/rpc/msgpushservice/msgPushService.go: -------------------------------------------------------------------------------- 1 | // Code generated by goctl. DO NOT EDIT! 2 | // Source: msgpush.proto 3 | 4 | package msgpushservice 5 | 6 | import ( 7 | "context" 8 | 9 | "github.com/showurl/Zero-IM-Server/app/msg-push/cmd/rpc/pb" 10 | 11 | "github.com/zeromicro/go-zero/zrpc" 12 | "google.golang.org/grpc" 13 | ) 14 | 15 | type ( 16 | PushMsgReq = pb.PushMsgReq 17 | PushMsgResp = pb.PushMsgResp 18 | 19 | MsgPushService interface { 20 | PushMsg(ctx context.Context, in *PushMsgReq, opts ...grpc.CallOption) (*PushMsgResp, error) 21 | } 22 | 23 | defaultMsgPushService struct { 24 | cli zrpc.Client 25 | } 26 | ) 27 | 28 | func NewMsgPushService(cli zrpc.Client) MsgPushService { 29 | return &defaultMsgPushService{ 30 | cli: cli, 31 | } 32 | } 33 | 34 | func (m *defaultMsgPushService) PushMsg(ctx context.Context, in *PushMsgReq, opts ...grpc.CallOption) (*PushMsgResp, error) { 35 | client := pb.NewMsgPushServiceClient(m.cli.Conn()) 36 | return client.PushMsg(ctx, in, opts...) 37 | } 38 | -------------------------------------------------------------------------------- /app/auth/cmd/rpc/authservice/authService.go: -------------------------------------------------------------------------------- 1 | // Code generated by goctl. DO NOT EDIT! 2 | // Source: auth.proto 3 | 4 | package authservice 5 | 6 | import ( 7 | "context" 8 | 9 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/pb" 10 | 11 | "github.com/zeromicro/go-zero/zrpc" 12 | "google.golang.org/grpc" 13 | ) 14 | 15 | type ( 16 | VerifyTokenReq = pb.VerifyTokenReq 17 | VerifyTokenResp = pb.VerifyTokenResp 18 | 19 | AuthService interface { 20 | VerifyToken(ctx context.Context, in *VerifyTokenReq, opts ...grpc.CallOption) (*VerifyTokenResp, error) 21 | } 22 | 23 | defaultAuthService struct { 24 | cli zrpc.Client 25 | } 26 | ) 27 | 28 | func NewAuthService(cli zrpc.Client) AuthService { 29 | return &defaultAuthService{ 30 | cli: cli, 31 | } 32 | } 33 | 34 | func (m *defaultAuthService) VerifyToken(ctx context.Context, in *VerifyTokenReq, opts ...grpc.CallOption) (*VerifyTokenResp, error) { 35 | client := pb.NewAuthServiceClient(m.cli.Conn()) 36 | return client.VerifyToken(ctx, in, opts...) 37 | } 38 | -------------------------------------------------------------------------------- /app/conversation/cmd/rpc/internal/server/conversationServiceServer.go: -------------------------------------------------------------------------------- 1 | // Code generated by goctl. DO NOT EDIT! 2 | // Source: conversation.proto 3 | 4 | package server 5 | 6 | import ( 7 | "context" 8 | 9 | "github.com/showurl/Zero-IM-Server/app/conversation/cmd/rpc/internal/logic" 10 | "github.com/showurl/Zero-IM-Server/app/conversation/cmd/rpc/internal/svc" 11 | "github.com/showurl/Zero-IM-Server/app/conversation/cmd/rpc/pb" 12 | ) 13 | 14 | type ConversationServiceServer struct { 15 | svcCtx *svc.ServiceContext 16 | pb.UnimplementedConversationServiceServer 17 | } 18 | 19 | func NewConversationServiceServer(svcCtx *svc.ServiceContext) *ConversationServiceServer { 20 | return &ConversationServiceServer{ 21 | svcCtx: svcCtx, 22 | } 23 | } 24 | 25 | func (s *ConversationServiceServer) ModifyConversationField(ctx context.Context, in *pb.ModifyConversationFieldReq) (*pb.ModifyConversationFieldResp, error) { 26 | l := logic.NewModifyConversationFieldLogic(ctx, s.svcCtx) 27 | return l.ModifyConversationField(in) 28 | } 29 | -------------------------------------------------------------------------------- /goctl/goctl/migrate/proxy.go: -------------------------------------------------------------------------------- 1 | package migrate 2 | 3 | import ( 4 | "net/url" 5 | "os" 6 | "strings" 7 | 8 | "github.com/zeromicro/go-zero/core/stringx" 9 | "github.com/zeromicro/go-zero/tools/goctl/rpc/execx" 10 | ) 11 | 12 | var ( 13 | defaultProxy = "https://goproxy.cn" 14 | defaultProxies = []string{defaultProxy} 15 | ) 16 | 17 | func goProxy() []string { 18 | wd, err := os.Getwd() 19 | if err != nil { 20 | return defaultProxies 21 | } 22 | 23 | proxy, err := execx.Run("go env GOPROXY", wd) 24 | if err != nil { 25 | return defaultProxies 26 | } 27 | list := strings.FieldsFunc(proxy, func(r rune) bool { 28 | return r == '|' || r == ',' 29 | }) 30 | var ret []string 31 | for _, item := range list { 32 | if len(item) == 0 { 33 | continue 34 | } 35 | _, err = url.Parse(item) 36 | if err == nil && !stringx.Contains(ret, item) { 37 | ret = append(ret, item) 38 | } 39 | } 40 | if !stringx.Contains(ret, defaultProxy) { 41 | ret = append(ret, defaultProxy) 42 | } 43 | return ret 44 | } 45 | -------------------------------------------------------------------------------- /app/im-user/cmd/rpc/internal/logic/ifAInBBlacklistLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/im-user/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/im-user/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type IfAInBBlacklistLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewIfAInBBlacklistLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IfAInBBlacklistLogic { 19 | return &IfAInBBlacklistLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | // 判断用户A是否在B黑名单中 27 | func (l *IfAInBBlacklistLogic) IfAInBBlacklist(in *pb.IfAInBBlacklistReq) (*pb.IfAInBBlacklistResp, error) { 28 | // todo: add your logic here and delete this line 29 | 30 | return &pb.IfAInBBlacklistResp{ 31 | CommonResp: &pb.CommonResp{ 32 | ErrCode: 0, 33 | ErrMsg: "", 34 | }, 35 | IsInBlacklist: false, 36 | }, nil 37 | } 38 | -------------------------------------------------------------------------------- /common/utils/statistics/statistics.go: -------------------------------------------------------------------------------- 1 | package statistics 2 | 3 | import ( 4 | "github.com/zeromicro/go-zero/core/logx" 5 | "time" 6 | ) 7 | 8 | type Statistics struct { 9 | AllCount *uint64 10 | ModuleName string 11 | PrintArgs string 12 | SleepTime int 13 | } 14 | 15 | func (s *Statistics) output() { 16 | var intervalCount uint64 17 | t := time.NewTicker(time.Duration(s.SleepTime) * time.Second) 18 | defer t.Stop() 19 | var sum uint64 20 | for { 21 | sum = *s.AllCount 22 | select { 23 | case <-t.C: 24 | } 25 | if *s.AllCount-sum <= 0 { 26 | intervalCount = 0 27 | } else { 28 | intervalCount = *s.AllCount - sum 29 | } 30 | logx.Infof("%v %v %v %v %v %v ", " system stat ", s.ModuleName, s.PrintArgs, intervalCount, "total:", *s.AllCount) 31 | } 32 | } 33 | 34 | func NewStatistics(allCount *uint64, moduleName, printArgs string, sleepTime int) *Statistics { 35 | p := &Statistics{AllCount: allCount, ModuleName: moduleName, SleepTime: sleepTime, PrintArgs: printArgs} 36 | go p.output() 37 | return p 38 | } 39 | -------------------------------------------------------------------------------- /goctl/goctl/docker/docker.tpl: -------------------------------------------------------------------------------- 1 | FROM golang:{{.Version}}alpine AS builder 2 | 3 | LABEL stage=gobuilder 4 | 5 | ENV CGO_ENABLED 0 6 | {{if .Chinese}}ENV GOPROXY https://goproxy.cn,direct 7 | {{end}}{{if .HasTimezone}} 8 | RUN apk update --no-cache && apk add --no-cache tzdata 9 | {{end}} 10 | WORKDIR /build 11 | 12 | ADD go.mod . 13 | ADD go.sum . 14 | RUN go mod download 15 | COPY . . 16 | {{if .Argument}}COPY {{.GoRelPath}}/etc /app/etc 17 | {{end}}RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoRelPath}}/{{.GoFile}} 18 | 19 | 20 | FROM {{.BaseImage}} 21 | 22 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt 23 | {{if .HasTimezone}}COPY --from=builder /usr/share/zoneinfo/{{.Timezone}} /usr/share/zoneinfo/{{.Timezone}} 24 | ENV TZ {{.Timezone}} 25 | {{end}} 26 | WORKDIR /app 27 | COPY --from=builder /app/{{.ExeFile}} /app/{{.ExeFile}}{{if .Argument}} 28 | COPY --from=builder /app/etc /app/etc{{end}} 29 | {{if .HasPort}} 30 | EXPOSE {{.Port}} 31 | {{end}} 32 | CMD ["./{{.ExeFile}}"{{.Argument}}] 33 | -------------------------------------------------------------------------------- /goctl/goctl/internal/version/version_test.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_convertVersion(t *testing.T) { 10 | number, tag := convertVersion("1.1.10") 11 | assert.Equal(t, 1.110, number) 12 | assert.Equal(t, "", tag) 13 | 14 | number, tag = convertVersion("0.1.11") 15 | assert.Equal(t, 0.111, number) 16 | assert.Equal(t, "", tag) 17 | 18 | number, tag = convertVersion("1.11-pre") 19 | assert.Equal(t, 1.11, number) 20 | assert.Equal(t, "pre", tag) 21 | 22 | number, tag = convertVersion("1.11-beta-v1") 23 | assert.Equal(t, 1.11, number) 24 | assert.Equal(t, "betav1", tag) 25 | } 26 | 27 | func Test_IsVersionGatherThan(t *testing.T) { 28 | assert.False(t, IsVersionGreaterThan("0.11", "1.1")) 29 | assert.True(t, IsVersionGreaterThan("0.112", "0.1")) 30 | assert.True(t, IsVersionGreaterThan("1.1.10", "1.0.111")) 31 | assert.True(t, IsVersionGreaterThan("1.1.10", "1.1.10-pre")) 32 | assert.True(t, IsVersionGreaterThan("1.1.11-pre", "1.1.10")) 33 | } 34 | -------------------------------------------------------------------------------- /goctl/goctl/rpc/generator/prototmpl.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | _ "embed" 5 | "path/filepath" 6 | "strings" 7 | 8 | "github.com/zeromicro/go-zero/tools/goctl/util" 9 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx" 10 | "github.com/zeromicro/go-zero/tools/goctl/util/stringx" 11 | ) 12 | 13 | //go:embed rpc.tpl 14 | var rpcTemplateText string 15 | 16 | // ProtoTmpl returns a sample of a proto file 17 | func ProtoTmpl(out string) error { 18 | protoFilename := filepath.Base(out) 19 | serviceName := stringx.From(strings.TrimSuffix(protoFilename, filepath.Ext(protoFilename))) 20 | text, err := pathx.LoadTemplate(category, rpcTemplateFile, rpcTemplateText) 21 | if err != nil { 22 | return err 23 | } 24 | 25 | dir := filepath.Dir(out) 26 | err = pathx.MkdirIfNotExist(dir) 27 | if err != nil { 28 | return err 29 | } 30 | 31 | err = util.With("t").Parse(text).SaveTo(map[string]string{ 32 | "package": serviceName.Untitle(), 33 | "serviceName": serviceName.Title(), 34 | }, out, false) 35 | return err 36 | } 37 | -------------------------------------------------------------------------------- /app/im-user/cmd/rpc/internal/logic/ifAInBFriendListLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/im-user/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/im-user/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type IfAInBFriendListLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewIfAInBFriendListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IfAInBFriendListLogic { 19 | return &IfAInBFriendListLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | // 判断用户A是否在B好友列表中 27 | func (l *IfAInBFriendListLogic) IfAInBFriendList(in *pb.IfAInBFriendListReq) (*pb.IfAInBFriendListResp, error) { 28 | // todo: add your logic here and delete this line 29 | 30 | return &pb.IfAInBFriendListResp{ 31 | CommonResp: &pb.CommonResp{ 32 | ErrCode: 0, 33 | ErrMsg: "", 34 | }, 35 | IsInFriendList: true, 36 | }, nil 37 | } 38 | -------------------------------------------------------------------------------- /goctl/home/1.3.6-beta/docker/docker.tpl: -------------------------------------------------------------------------------- 1 | FROM golang:{{.Version}}alpine AS builder 2 | 3 | LABEL stage=gobuilder 4 | 5 | ENV CGO_ENABLED 0 6 | {{if .Chinese}}ENV GOPROXY https://goproxy.cn,direct 7 | {{end}}{{if .HasTimezone}} 8 | RUN apk update --no-cache && apk add --no-cache tzdata 9 | {{end}} 10 | WORKDIR /build 11 | 12 | ADD go.mod . 13 | ADD go.sum . 14 | RUN go mod download 15 | COPY . . 16 | {{if .Argument}}COPY {{.GoRelPath}}/etc /app/etc 17 | {{end}}RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoRelPath}}/{{.GoFile}} 18 | 19 | 20 | FROM {{.BaseImage}} 21 | 22 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt 23 | {{if .HasTimezone}}COPY --from=builder /usr/share/zoneinfo/{{.Timezone}} /usr/share/zoneinfo/{{.Timezone}} 24 | ENV TZ {{.Timezone}} 25 | {{end}} 26 | WORKDIR /app 27 | COPY --from=builder /app/{{.ExeFile}} /app/{{.ExeFile}}{{if .Argument}} 28 | COPY --from=builder /app/etc /app/etc{{end}} 29 | {{if .HasPort}} 30 | EXPOSE {{.Port}} 31 | {{end}} 32 | CMD ["./{{.ExeFile}}"{{.Argument}}] 33 | -------------------------------------------------------------------------------- /common/xcache/dc/first_option.go: -------------------------------------------------------------------------------- 1 | package dc 2 | 3 | type FuncFirstOption func(*FirstOption) 4 | 5 | type FirstOption struct { 6 | where string // 缓存查不到 去数据库查询的时候 用 where语句 查询 7 | args []interface{} // 缓存查不到 去数据库查询的时候 用 where语句+args 查询 8 | keySuffix string // redis key的后缀 9 | fieldId string // 替换id的字段 10 | } 11 | 12 | func WithWhere( 13 | where string, 14 | args ...interface{}, 15 | ) FuncFirstOption { 16 | return func(option *FirstOption) { 17 | option.where = where 18 | option.args = args 19 | } 20 | } 21 | 22 | func WithKeySuffix( 23 | suffix string, 24 | ) FuncFirstOption { 25 | return func(option *FirstOption) { 26 | option.keySuffix = suffix 27 | } 28 | } 29 | 30 | func WithFieldId( 31 | fieldId string, 32 | ) FuncFirstOption { 33 | return func(option *FirstOption) { 34 | option.fieldId = fieldId 35 | option.where = fieldId + " = ?" 36 | } 37 | } 38 | 39 | func defaultOption(id string) *FirstOption { 40 | return &FirstOption{ 41 | where: "id = ?", 42 | args: []interface{}{id}, 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /goctl/goctl/model/sql/gen/new.go: -------------------------------------------------------------------------------- 1 | package gen 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/zeromicro/go-zero/tools/goctl/model/sql/template" 7 | "github.com/zeromicro/go-zero/tools/goctl/util" 8 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx" 9 | ) 10 | 11 | func genNew(table Table, withCache, postgreSql bool) (string, error) { 12 | text, err := pathx.LoadTemplate(category, modelNewTemplateFile, template.New) 13 | if err != nil { 14 | return "", err 15 | } 16 | 17 | t := fmt.Sprintf(`"%s"`, wrapWithRawString(table.Name.Source(), postgreSql)) 18 | if postgreSql { 19 | t = "`" + fmt.Sprintf(`"%s"."%s"`, table.Db.Source(), table.Name.Source()) + "`" 20 | } 21 | 22 | output, err := util.With("new"). 23 | Parse(text). 24 | Execute(map[string]interface{}{ 25 | "table": t, 26 | "withCache": withCache, 27 | "upperStartCamelObject": table.Name.ToCamel(), 28 | "data": table, 29 | }) 30 | if err != nil { 31 | return "", err 32 | } 33 | 34 | return output.String(), nil 35 | } 36 | -------------------------------------------------------------------------------- /goctl/goctl/util/name/naming_test.go: -------------------------------------------------------------------------------- 1 | package name 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestIsNamingValid(t *testing.T) { 10 | style, valid := IsNamingValid("") 11 | assert.True(t, valid) 12 | assert.Equal(t, NamingLower, style) 13 | 14 | _, valid = IsNamingValid("lower1") 15 | assert.False(t, valid) 16 | 17 | _, valid = IsNamingValid("lower") 18 | assert.True(t, valid) 19 | 20 | _, valid = IsNamingValid("snake") 21 | assert.True(t, valid) 22 | 23 | _, valid = IsNamingValid("camel") 24 | assert.True(t, valid) 25 | } 26 | 27 | func TestFormatFilename(t *testing.T) { 28 | assert.Equal(t, "abc", FormatFilename("a_b_c", NamingLower)) 29 | assert.Equal(t, "ABC", FormatFilename("a_b_c", NamingCamel)) 30 | assert.Equal(t, "a_b_c", FormatFilename("a_b_c", NamingSnake)) 31 | assert.Equal(t, "a", FormatFilename("a", NamingSnake)) 32 | assert.Equal(t, "A", FormatFilename("a", NamingCamel)) 33 | // no flag to convert to snake 34 | assert.Equal(t, "abc", FormatFilename("abc", NamingSnake)) 35 | } 36 | -------------------------------------------------------------------------------- /goctl/goctl/model/sql/template/insert.go: -------------------------------------------------------------------------------- 1 | package template 2 | 3 | const ( 4 | // Insert defines a template for insert code in model 5 | Insert = ` 6 | func (m *default{{.upperStartCamelObject}}Model) Insert(ctx context.Context, data *{{.upperStartCamelObject}}) (sql.Result,error) { 7 | {{if .withCache}}{{.keys}} 8 | ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 9 | query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet) 10 | return conn.ExecCtx(ctx, query, {{.expressionValues}}) 11 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet) 12 | ret,err:=m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}} 13 | return ret,err 14 | } 15 | ` 16 | 17 | // InsertMethod defines an interface method template for insert code in model 18 | InsertMethod = `Insert(ctx context.Context, data *{{.upperStartCamelObject}}) (sql.Result,error)` 19 | ) 20 | -------------------------------------------------------------------------------- /goctl/goctl/plugin/plugin_test.go: -------------------------------------------------------------------------------- 1 | package plugin 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestGetPluginAndArgs(t *testing.T) { 10 | bin, args := getPluginAndArgs("android") 11 | assert.Equal(t, "android", bin) 12 | assert.Equal(t, "", args) 13 | 14 | bin, args = getPluginAndArgs("android=") 15 | assert.Equal(t, "android", bin) 16 | assert.Equal(t, "", args) 17 | 18 | bin, args = getPluginAndArgs("android=-javaPackage com.tal") 19 | assert.Equal(t, "android", bin) 20 | assert.Equal(t, "-javaPackage com.tal", args) 21 | 22 | bin, args = getPluginAndArgs("android=-javaPackage com.tal --lambda") 23 | assert.Equal(t, "android", bin) 24 | assert.Equal(t, "-javaPackage com.tal --lambda", args) 25 | 26 | bin, args = getPluginAndArgs(`https://test-xjy-file.obs.cn-east-2.myhuaweicloud.com/202012/8a7ab6e1-e639-49d1-89cf-2ae6127a1e90n=-v 1`) 27 | assert.Equal(t, "https://test-xjy-file.obs.cn-east-2.myhuaweicloud.com/202012/8a7ab6e1-e639-49d1-89cf-2ae6127a1e90n", bin) 28 | assert.Equal(t, "-v 1", args) 29 | } 30 | -------------------------------------------------------------------------------- /goctl/goctl/rpc/generator/generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "log" 5 | 6 | conf "github.com/zeromicro/go-zero/tools/goctl/config" 7 | "github.com/zeromicro/go-zero/tools/goctl/env" 8 | "github.com/zeromicro/go-zero/tools/goctl/util/console" 9 | ) 10 | 11 | // Generator defines the environment needs of rpc service generation 12 | type Generator struct { 13 | log console.Console 14 | cfg *conf.Config 15 | verbose bool 16 | } 17 | 18 | // NewGenerator returns an instance of Generator 19 | func NewGenerator(style string, verbose bool) *Generator { 20 | cfg, err := conf.NewConfig(style) 21 | if err != nil { 22 | log.Fatalln(err) 23 | } 24 | log := console.NewColorConsole(verbose) 25 | return &Generator{ 26 | log: log, 27 | cfg: cfg, 28 | verbose: verbose, 29 | } 30 | } 31 | 32 | // Prepare provides environment detection generated by rpc service, 33 | // including go environment, protoc, whether protoc-gen-go is installed or not 34 | func (g *Generator) Prepare() error { 35 | return env.Prepare(true, true, g.verbose) 36 | } 37 | -------------------------------------------------------------------------------- /app/msg-push/cmd/rpc/internal/svc/serviceContext.go: -------------------------------------------------------------------------------- 1 | package svc 2 | 3 | import ( 4 | "github.com/showurl/Zero-IM-Server/app/im-user/cmd/rpc/imuserservice" 5 | "github.com/showurl/Zero-IM-Server/app/msg-push/cmd/rpc/internal/config" 6 | "github.com/showurl/Zero-IM-Server/app/msg-push/cmd/rpc/internal/sdk" 7 | push "github.com/showurl/Zero-IM-Server/app/msg-push/cmd/rpc/internal/sdk/jpush" 8 | "github.com/zeromicro/go-zero/zrpc" 9 | ) 10 | 11 | type ServiceContext struct { 12 | Config config.Config 13 | offlinePusher sdk.OfflinePusher 14 | ImUserRpc imuserservice.ImUserService 15 | } 16 | 17 | func NewServiceContext(c config.Config) *ServiceContext { 18 | return &ServiceContext{ 19 | Config: c, 20 | ImUserRpc: imuserservice.NewImUserService(zrpc.MustNewClient(c.ImUserRpc)), 21 | } 22 | } 23 | func (s *ServiceContext) GetOfflinePusher() sdk.OfflinePusher { 24 | if s.offlinePusher != nil { 25 | return s.offlinePusher 26 | } 27 | if s.Config.PushType == "jpns" { 28 | s.offlinePusher = &push.JPush{s.Config} 29 | } 30 | return s.offlinePusher 31 | } 32 | -------------------------------------------------------------------------------- /goctl/goctl/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine AS builder 2 | 3 | LABEL stage=gobuilder 4 | 5 | ENV CGO_ENABLED 0 6 | ENV GOPROXY https://goproxy.cn,direct 7 | 8 | RUN apk update --no-cache && apk add --no-cache tzdata 9 | RUN go install google.golang.org/protobuf/cmd/protoc-gen-go@latest 10 | RUN go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest 11 | 12 | WORKDIR /build 13 | 14 | ADD go.mod . 15 | ADD go.sum . 16 | RUN go mod download 17 | COPY . . 18 | RUN go build -ldflags="-s -w" -o /app/goctl ./goctl.go 19 | 20 | 21 | FROM golang:alpine 22 | 23 | RUN apk update --no-cache && apk add --no-cache protoc 24 | 25 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt 26 | COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /usr/share/zoneinfo/Asia/Shanghai 27 | COPY --from=builder /go/bin/protoc-gen-go /usr/bin/protoc-gen-go 28 | COPY --from=builder /go/bin/protoc-gen-go-grpc /usr/bin/protoc-gen-go-grpc 29 | ENV TZ Asia/Shanghai 30 | 31 | WORKDIR /app 32 | COPY --from=builder /app/goctl /usr/bin/goctl 33 | 34 | CMD ["goctl"] 35 | -------------------------------------------------------------------------------- /goctl/goctl/api/ktgen/api.tpl: -------------------------------------------------------------------------------- 1 | package {{with .Info}}{{.Desc}}{{end}} 2 | 3 | import com.google.gson.Gson 4 | 5 | object {{with .Info}}{{.Title}}{{end}}{ 6 | {{range .Types}} 7 | data class {{.Name}}({{$length := (len .Members)}}{{range $i,$item := .Members}} 8 | val {{with $item}}{{lowCamelCase .Name}}: {{parseType .Type.Name}}{{end}}{{if ne $i (add $length -1)}},{{end}}{{end}} 9 | ){{end}} 10 | {{with .Service}} 11 | {{range .Routes}}suspend fun {{routeToFuncName .Method .Path}}({{with .RequestType}}{{if ne .Name ""}} 12 | req:{{.Name}},{{end}}{{end}} 13 | onOk: (({{with .ResponseType}}{{.Name}}{{end}}) -> Unit)? = null, 14 | onFail: ((String) -> Unit)? = null, 15 | eventually: (() -> Unit)? = null 16 | ){ 17 | apiRequest("{{upperCase .Method}}","{{.Path}}",{{with .RequestType}}{{if ne .Name ""}}body=req,{{end}}{{end}} onOk = { {{with .ResponseType}} 18 | onOk?.invoke({{if ne .Name ""}}Gson().fromJson(it,{{.Name}}::class.java){{end}}){{end}} 19 | }, onFail = onFail, eventually =eventually) 20 | } 21 | {{end}}{{end}} 22 | } 23 | -------------------------------------------------------------------------------- /app/msg-gateway/cmd/wsrpc/internal/rpclogic/getUsersOnlineStatusLogic.go: -------------------------------------------------------------------------------- 1 | package rpclogic 2 | 3 | import ( 4 | "context" 5 | "github.com/showurl/Zero-IM-Server/app/msg-gateway/cmd/wsrpc/internal/rpcsvc" 6 | 7 | "github.com/showurl/Zero-IM-Server/app/msg-gateway/cmd/wsrpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type GetUsersOnlineStatusLogic struct { 13 | ctx context.Context 14 | svcCtx *rpcsvc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewGetUsersOnlineStatusLogic(ctx context.Context, svcCtx *rpcsvc.ServiceContext) *GetUsersOnlineStatusLogic { 19 | return &GetUsersOnlineStatusLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | func (l *GetUsersOnlineStatusLogic) GetUsersOnlineStatus(in *pb.GetUsersOnlineStatusReq) (*pb.GetUsersOnlineStatusResp, error) { 27 | // todo: add your logic here and delete this line 28 | 29 | return &pb.GetUsersOnlineStatusResp{ 30 | ErrCode: 0, 31 | ErrMsg: "", 32 | SuccessResult: nil, 33 | FailedResult: nil, 34 | }, nil 35 | } 36 | -------------------------------------------------------------------------------- /goctl/home/1.3.6-beta/model/var.tpl: -------------------------------------------------------------------------------- 1 | 2 | var ( 3 | {{.lowerStartCamelObject}}FieldNames = builder.RawFieldNames(&{{.upperStartCamelObject}}{}{{if .postgreSql}},true{{end}}) 4 | {{.lowerStartCamelObject}}Rows = strings.Join({{.lowerStartCamelObject}}FieldNames, ",") 5 | {{.lowerStartCamelObject}}RowsExpectAutoSet = {{if .postgreSql}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}",{{end}} "create_time", "update_time"), ","){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}",{{end}} "`create_time`", "`update_time`"), ","){{end}} 6 | {{.lowerStartCamelObject}}RowsWithPlaceHolder = {{if .postgreSql}}builder.PostgreSqlJoin(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", "create_time", "update_time")){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", "`create_time`", "`update_time`"), "=?,") + "=?"{{end}} 7 | 8 | {{if .withCache}}{{.cacheKeys}}{{end}} 9 | ) 10 | -------------------------------------------------------------------------------- /app/msg-callback/cmd/rpc/internal/logic/callbackAfterSendSuperGroupMsgLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type CallbackAfterSendSuperGroupMsgLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewCallbackAfterSendSuperGroupMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackAfterSendSuperGroupMsgLogic { 19 | return &CallbackAfterSendSuperGroupMsgLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | func (l *CallbackAfterSendSuperGroupMsgLogic) CallbackAfterSendSuperGroupMsg(in *pb.CallbackSendSuperGroupMsgReq) (*pb.CommonCallbackResp, error) { 27 | // todo: add your logic here and delete this line 28 | 29 | return &pb.CommonCallbackResp{ 30 | ActionCode: 0, 31 | ErrCode: 0, 32 | ErrMsg: "", 33 | }, nil 34 | } 35 | -------------------------------------------------------------------------------- /common/xorm/client.go: -------------------------------------------------------------------------------- 1 | package xorm 2 | 3 | import ( 4 | "github.com/showurl/Zero-IM-Server/common/xorm/global" 5 | "gorm.io/driver/mysql" 6 | "gorm.io/gorm" 7 | "gorm.io/gorm/logger" 8 | "strings" 9 | ) 10 | 11 | func GetClient( 12 | cfg global.MysqlConfig, 13 | ) *gorm.DB { 14 | var db *gorm.DB 15 | var err error 16 | var logLevel logger.LogLevel 17 | level := strings.ToUpper(cfg.LogLevel) 18 | if level == "" || level == "INFO" { 19 | logLevel = logger.Info 20 | } else { 21 | if level == "SILENT" { 22 | logLevel = logger.Silent 23 | } 24 | if level == "WARNING" { 25 | logLevel = logger.Warn 26 | } 27 | if level == "ERROR" { 28 | logLevel = logger.Error 29 | } 30 | } 31 | db, err = gorm.Open(mysql.New(mysql.Config{ 32 | DSN: cfg.Addr, 33 | SkipInitializeWithVersion: false, 34 | DefaultStringSize: 191, 35 | DontSupportRenameIndex: true, 36 | DontSupportRenameColumn: true, 37 | }), &gorm.Config{ 38 | Logger: logger.Default.LogMode(logLevel), 39 | }) 40 | if err != nil { 41 | panic(err) 42 | } 43 | return db 44 | } 45 | -------------------------------------------------------------------------------- /goctl/goctl/api/parser/parser_test.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | _ "embed" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | "github.com/zeromicro/go-zero/tools/goctl/api/spec" 9 | ) 10 | 11 | //go:embed testdata/test.api 12 | var testApi string 13 | 14 | func TestParseContent(t *testing.T) { 15 | sp, err := ParseContent(testApi) 16 | assert.Nil(t, err) 17 | assert.Equal(t, spec.Doc{`// syntax doc`}, sp.Syntax.Doc) 18 | assert.Equal(t, spec.Doc{`// syntax comment`}, sp.Syntax.Comment) 19 | for _, tp := range sp.Types { 20 | if tp.Name() == "Request" { 21 | assert.Equal(t, []string{`// type doc`}, tp.Documents()) 22 | } 23 | } 24 | for _, e := range sp.Service.Routes() { 25 | if e.Handler == "GreetHandler" { 26 | assert.Equal(t, spec.Doc{"// handler doc"}, e.HandlerDoc) 27 | assert.Equal(t, spec.Doc{"// handler comment"}, e.HandlerComment) 28 | } 29 | } 30 | } 31 | 32 | func TestMissingService(t *testing.T) { 33 | sp, err := ParseContent("") 34 | assert.Nil(t, err) 35 | err = sp.Validate() 36 | assert.Equal(t, spec.ErrMissingService, err) 37 | } 38 | -------------------------------------------------------------------------------- /goctl/goctl/util/zipx/zipx.go: -------------------------------------------------------------------------------- 1 | package zipx 2 | 3 | import ( 4 | "archive/zip" 5 | "io" 6 | "os" 7 | "path/filepath" 8 | 9 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx" 10 | ) 11 | 12 | func Unpacking(name, destPath string, mapper func(f *zip.File) bool) error { 13 | r, err := zip.OpenReader(name) 14 | if err != nil { 15 | return err 16 | } 17 | defer r.Close() 18 | 19 | for _, file := range r.File { 20 | ok := mapper(file) 21 | if ok { 22 | err = fileCopy(file, destPath) 23 | if err != nil { 24 | return err 25 | } 26 | } 27 | } 28 | return nil 29 | } 30 | 31 | func fileCopy(file *zip.File, destPath string) error { 32 | rc, err := file.Open() 33 | if err != nil { 34 | return err 35 | } 36 | defer rc.Close() 37 | filename := filepath.Join(destPath, filepath.Base(file.Name)) 38 | dir := filepath.Dir(filename) 39 | err = pathx.MkdirIfNotExist(dir) 40 | if err != nil { 41 | return err 42 | } 43 | 44 | w, err := os.Create(filename) 45 | if err != nil { 46 | return err 47 | } 48 | defer w.Close() 49 | _, err = io.Copy(w, rc) 50 | return err 51 | } 52 | -------------------------------------------------------------------------------- /app/msg-callback/cmd/rpc/internal/logic/callbackAfterSendSingleMsgLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type CallbackAfterSendSingleMsgLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewCallbackAfterSendSingleMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackAfterSendSingleMsgLogic { 19 | return &CallbackAfterSendSingleMsgLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | func (l *CallbackAfterSendSingleMsgLogic) CallbackAfterSendSingleMsg(in *pb.CallbackSendSingleMsgReq) (*pb.CommonCallbackResp, error) { 27 | // todo: add your logic here and delete this line 28 | 29 | return &pb.CommonCallbackResp{ 30 | ActionCode: pb.ActionCode_Forbidden, 31 | ErrCode: pb.ErrCode_HandleFailed, 32 | ErrMsg: "", 33 | }, nil 34 | } 35 | -------------------------------------------------------------------------------- /app/msg-callback/cmd/rpc/internal/logic/callbackBeforeSendSingleMsgLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type CallbackBeforeSendSingleMsgLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewCallbackBeforeSendSingleMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackBeforeSendSingleMsgLogic { 19 | return &CallbackBeforeSendSingleMsgLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | func (l *CallbackBeforeSendSingleMsgLogic) CallbackBeforeSendSingleMsg(in *pb.CallbackSendSingleMsgReq) (*pb.CommonCallbackResp, error) { 27 | // todo: add your logic here and delete this line 28 | 29 | return &pb.CommonCallbackResp{ 30 | ActionCode: pb.ActionCode_Forbidden, 31 | ErrCode: pb.ErrCode_HandleFailed, 32 | ErrMsg: "", 33 | }, nil 34 | } 35 | -------------------------------------------------------------------------------- /common/xorm/err/duplicate.go: -------------------------------------------------------------------------------- 1 | package xormerr 2 | 3 | import ( 4 | "errors" 5 | m "github.com/go-sql-driver/mysql" 6 | "github.com/pingcap/parser/mysql" 7 | "github.com/zeromicro/go-zero/core/logx" 8 | "gorm.io/gorm" 9 | "strings" 10 | ) 11 | 12 | func DuplicateError(err error) bool { 13 | if err != nil { 14 | return strings.HasPrefix(err.Error(), "Error 1062") 15 | } 16 | return false 17 | } 18 | func TableNotFound(err error) bool { 19 | if err == nil { 20 | return false 21 | } 22 | if errMysql, ok := err.(*mysql.SQLError); ok { 23 | if errMysql.Code == mysql.ErrNoSuchTable { 24 | return true 25 | } else { 26 | logx.Error("errMysql.Code:", errMysql.Code) 27 | } 28 | } 29 | if errMysql, ok := err.(*m.MySQLError); ok { 30 | if errMysql.Number == mysql.ErrNoSuchTable { 31 | return true 32 | } else { 33 | logx.Error("errMysql.Code:", errMysql.Number) 34 | } 35 | } 36 | return false 37 | } 38 | func RecordNotFound(err error) bool { 39 | if err == nil { 40 | return false 41 | } 42 | if errors.Is(err, gorm.ErrRecordNotFound) { 43 | return true 44 | } 45 | return false 46 | } 47 | -------------------------------------------------------------------------------- /goctl/goctl/model/sql/template/update.go: -------------------------------------------------------------------------------- 1 | package template 2 | 3 | const ( 4 | // Update defines a template for generating update codes 5 | Update = ` 6 | func (m *default{{.upperStartCamelObject}}Model) Update(ctx context.Context, data *{{.upperStartCamelObject}}) error { 7 | {{if .withCache}}{{.keys}} 8 | _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 9 | query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) 10 | return conn.ExecCtx(ctx, query, {{.expressionValues}}) 11 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) 12 | _,err:=m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}} 13 | return err 14 | } 15 | ` 16 | 17 | // UpdateMethod defines an interface method template for generating update codes 18 | UpdateMethod = `Update(ctx context.Context, data *{{.upperStartCamelObject}}) error` 19 | ) 20 | -------------------------------------------------------------------------------- /app/msg-transfer/cmd/history/internal/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "github.com/showurl/Zero-IM-Server/common/xkafka" 5 | "github.com/showurl/Zero-IM-Server/common/xmgo/global" 6 | "github.com/zeromicro/go-zero/core/service" 7 | "github.com/zeromicro/go-zero/core/stores/redis" 8 | "github.com/zeromicro/go-zero/zrpc" 9 | ) 10 | 11 | type Config struct { 12 | service.ServiceConf 13 | Kafka KafkaConfig 14 | Redis RedisConfig 15 | Mongo MongoConfig 16 | MsgPushRpc zrpc.RpcClientConf 17 | } 18 | type KafkaConfigOnline struct { 19 | xkafka.ProducerConfig 20 | MsgToMongoGroupID string 21 | } 22 | type KafkaConfig struct { 23 | Online KafkaConfigOnline 24 | Offline xkafka.ProducerConfig 25 | SinglePush xkafka.ProducerConfig 26 | SuperGroupPush xkafka.ProducerConfig 27 | } 28 | type RedisConfig struct { 29 | Conf redis.RedisConf 30 | DB int 31 | } 32 | type MongoConfig struct { 33 | global.MongoConfig 34 | DBDatabase string 35 | DBTimeout int 36 | SingleChatMsgCollectionName string 37 | SuperGroupChatMsgCollectionName string 38 | } 39 | -------------------------------------------------------------------------------- /goctl/goctl/model/sql/gen/imports.go: -------------------------------------------------------------------------------- 1 | package gen 2 | 3 | import ( 4 | "github.com/zeromicro/go-zero/tools/goctl/model/sql/template" 5 | "github.com/zeromicro/go-zero/tools/goctl/util" 6 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx" 7 | ) 8 | 9 | func genImports(table Table, withCache, timeImport bool) (string, error) { 10 | if withCache { 11 | text, err := pathx.LoadTemplate(category, importsTemplateFile, template.Imports) 12 | if err != nil { 13 | return "", err 14 | } 15 | 16 | buffer, err := util.With("import").Parse(text).Execute(map[string]interface{}{ 17 | "time": timeImport, 18 | "data": table, 19 | }) 20 | if err != nil { 21 | return "", err 22 | } 23 | 24 | return buffer.String(), nil 25 | } 26 | 27 | text, err := pathx.LoadTemplate(category, importsWithNoCacheTemplateFile, template.ImportsNoCache) 28 | if err != nil { 29 | return "", err 30 | } 31 | 32 | buffer, err := util.With("import").Parse(text).Execute(map[string]interface{}{ 33 | "time": timeImport, 34 | "data": table, 35 | }) 36 | if err != nil { 37 | return "", err 38 | } 39 | 40 | return buffer.String(), nil 41 | } 42 | -------------------------------------------------------------------------------- /app/msg-callback/cmd/rpc/internal/logic/callbackBeforeSendSuperGroupMsgLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type CallbackBeforeSendSuperGroupMsgLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewCallbackBeforeSendSuperGroupMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackBeforeSendSuperGroupMsgLogic { 19 | return &CallbackBeforeSendSuperGroupMsgLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | func (l *CallbackBeforeSendSuperGroupMsgLogic) CallbackBeforeSendSuperGroupMsg(in *pb.CallbackSendSuperGroupMsgReq) (*pb.CommonCallbackResp, error) { 27 | // todo: add your logic here and delete this line 28 | 29 | return &pb.CommonCallbackResp{ 30 | ActionCode: pb.ActionCode_Forbidden, 31 | ErrCode: pb.ErrCode_HandleFailed, 32 | ErrMsg: "", 33 | }, nil 34 | } 35 | -------------------------------------------------------------------------------- /goctl/goctl/pkg/goctl/goctl.go: -------------------------------------------------------------------------------- 1 | package goctl 2 | 3 | import ( 4 | "path/filepath" 5 | "runtime" 6 | 7 | "github.com/zeromicro/go-zero/tools/goctl/pkg/golang" 8 | "github.com/zeromicro/go-zero/tools/goctl/util/console" 9 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx" 10 | "github.com/zeromicro/go-zero/tools/goctl/vars" 11 | ) 12 | 13 | func Install(cacheDir, name string, installFn func(dest string) (string, error)) (string, error) { 14 | goBin := golang.GoBin() 15 | cacheFile := filepath.Join(cacheDir, name) 16 | binFile := filepath.Join(goBin, name) 17 | 18 | goos := runtime.GOOS 19 | if goos == vars.OsWindows { 20 | cacheFile = cacheFile + ".exe" 21 | binFile = binFile + ".exe" 22 | } 23 | // read cache. 24 | err := pathx.Copy(cacheFile, binFile) 25 | if err == nil { 26 | console.Info("%q installed from cache", name) 27 | return binFile, nil 28 | } 29 | 30 | binFile, err = installFn(binFile) 31 | if err != nil { 32 | return "", err 33 | } 34 | 35 | // write cache. 36 | err = pathx.Copy(binFile, cacheFile) 37 | if err != nil { 38 | console.Warning("write cache error: %+v", err) 39 | } 40 | return binFile, nil 41 | } 42 | -------------------------------------------------------------------------------- /goctl/goctl/migrate/version.go: -------------------------------------------------------------------------------- 1 | package migrate 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net/http" 7 | "strings" 8 | "time" 9 | 10 | "github.com/zeromicro/go-zero/tools/goctl/util/console" 11 | ) 12 | 13 | var client = http.Client{ 14 | Timeout: 5 * time.Second, 15 | } 16 | 17 | func getLatest(repo string, verbose bool) ([]string, error) { 18 | proxies := goProxy() 19 | for _, proxy := range proxies { 20 | if verbose { 21 | console.Info("use go proxy %q", proxy) 22 | } 23 | log := func(err error) { 24 | console.Warning("get latest versions failed from proxy %q, error: %+v", proxy, err) 25 | } 26 | resp, err := client.Get(fmt.Sprintf("%s/%s/@v/list", proxy, repo)) 27 | if err != nil { 28 | log(err) 29 | continue 30 | } 31 | 32 | if resp.StatusCode != http.StatusOK { 33 | log(fmt.Errorf("%s", resp.Status)) 34 | continue 35 | } 36 | defer resp.Body.Close() 37 | data, err := ioutil.ReadAll(resp.Body) 38 | if err != nil { 39 | log(err) 40 | continue 41 | } 42 | versionStr := string(data) 43 | versions := strings.Fields(versionStr) 44 | return versions, nil 45 | } 46 | return []string{}, nil 47 | } 48 | -------------------------------------------------------------------------------- /goctl/goctl/util/git.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "os/exec" 7 | "path/filepath" 8 | "runtime" 9 | "strings" 10 | 11 | "github.com/zeromicro/go-zero/tools/goctl/util/env" 12 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx" 13 | ) 14 | 15 | func CloneIntoGitHome(url, branch string) (dir string, err error) { 16 | gitHome, err := pathx.GetGitHome() 17 | if err != nil { 18 | return "", err 19 | } 20 | os.RemoveAll(gitHome) 21 | ext := filepath.Ext(url) 22 | repo := strings.TrimSuffix(filepath.Base(url), ext) 23 | dir = filepath.Join(gitHome, repo) 24 | if pathx.FileExists(dir) { 25 | os.RemoveAll(dir) 26 | } 27 | path, err := env.LookPath("git") 28 | if err != nil { 29 | return "", err 30 | } 31 | if !env.CanExec() { 32 | return "", fmt.Errorf("os %q can not call 'exec' command", runtime.GOOS) 33 | } 34 | args := []string{"clone"} 35 | if len(branch) > 0 { 36 | args = append(args, "-b", branch) 37 | } 38 | args = append(args, url, dir) 39 | cmd := exec.Command(path, args...) 40 | cmd.Env = os.Environ() 41 | cmd.Stdout = os.Stdout 42 | cmd.Stderr = os.Stderr 43 | err = cmd.Run() 44 | return 45 | } 46 | -------------------------------------------------------------------------------- /app/msg-callback/cmd/rpc/internal/logic/callbackAtAllInSuperGroupLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/msg-callback/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type CallbackAtAllInSuperGroupLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewCallbackAtAllInSuperGroupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackAtAllInSuperGroupLogic { 19 | return &CallbackAtAllInSuperGroupLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | func (l *CallbackAtAllInSuperGroupLogic) CallbackAtAllInSuperGroup(in *pb.CallbackAtAllInSuperGroupReq) (*pb.CallbackAtAllInSuperGroupResp, error) { 27 | // todo: add your logic here and delete this line 28 | 29 | return &pb.CallbackAtAllInSuperGroupResp{CommonCallbackResp: &pb.CommonCallbackResp{ 30 | ActionCode: pb.ActionCode_Forbidden, 31 | ErrCode: pb.ErrCode_HandleFailed, 32 | ErrMsg: "", 33 | }}, nil 34 | } 35 | -------------------------------------------------------------------------------- /deploy/local/prometheus/prometheus.yml: -------------------------------------------------------------------------------- 1 | global: 2 | scrape_interval: 3 | external_labels: 4 | monitor: 'zero-im-server-monitor' 5 | 6 | scrape_configs: 7 | - job_name: 'prometheus' 8 | scrape_interval: 5s #global catch time 9 | static_configs: 10 | - targets: ['127.0.0.1:9090'] 11 | 12 | - job_name: 'msggateway-rpc' 13 | static_configs: 14 | - targets: ['192.168.2.77:10401'] 15 | labels: 16 | job: msggateway-rpc 17 | app: msggateway-rpc 18 | env: dev 19 | 20 | - job_name: 'auth-rpc' 21 | static_configs: 22 | - targets: ['192.168.2.77:10161'] 23 | labels: 24 | job: msggateway-rpc 25 | app: msggateway-rpc 26 | env: dev 27 | 28 | - job_name: 'imuser-rpc' 29 | static_configs: 30 | - targets: ['192.168.2.77:10241'] 31 | labels: 32 | job: msggateway-rpc 33 | app: msggateway-rpc 34 | env: dev 35 | 36 | - job_name: 'msg-rpc' 37 | static_configs: 38 | - targets: ['192.168.2.77:10131'] 39 | labels: 40 | job: msggateway-rpc 41 | app: msggateway-rpc 42 | env: dev 43 | -------------------------------------------------------------------------------- /goctl/goctl/model/sql/gen/types.go: -------------------------------------------------------------------------------- 1 | package gen 2 | 3 | import ( 4 | "github.com/zeromicro/go-zero/tools/goctl/model/sql/template" 5 | "github.com/zeromicro/go-zero/tools/goctl/util" 6 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx" 7 | "github.com/zeromicro/go-zero/tools/goctl/util/stringx" 8 | ) 9 | 10 | func genTypes(table Table, methods string, withCache bool) (string, error) { 11 | fields := table.Fields 12 | fieldsString, err := genFields(table, fields) 13 | if err != nil { 14 | return "", err 15 | } 16 | 17 | text, err := pathx.LoadTemplate(category, typesTemplateFile, template.Types) 18 | if err != nil { 19 | return "", err 20 | } 21 | 22 | output, err := util.With("types"). 23 | Parse(text). 24 | Execute(map[string]interface{}{ 25 | "withCache": withCache, 26 | "method": methods, 27 | "upperStartCamelObject": table.Name.ToCamel(), 28 | "lowerStartCamelObject": stringx.From(table.Name.ToCamel()).Untitle(), 29 | "fields": fieldsString, 30 | "data": table, 31 | }) 32 | if err != nil { 33 | return "", err 34 | } 35 | 36 | return output.String(), nil 37 | } 38 | -------------------------------------------------------------------------------- /goctl/goctl/api/gogen/genetc.go: -------------------------------------------------------------------------------- 1 | package gogen 2 | 3 | import ( 4 | _ "embed" 5 | "fmt" 6 | "strconv" 7 | 8 | "github.com/zeromicro/go-zero/tools/goctl/api/spec" 9 | "github.com/zeromicro/go-zero/tools/goctl/config" 10 | "github.com/zeromicro/go-zero/tools/goctl/util/format" 11 | ) 12 | 13 | const ( 14 | defaultPort = 8888 15 | etcDir = "etc" 16 | ) 17 | 18 | //go:embed etc.tpl 19 | var etcTemplate string 20 | 21 | func genEtc(dir string, cfg *config.Config, api *spec.ApiSpec) error { 22 | filename, err := format.FileNamingFormat(cfg.NamingFormat, api.Service.Name) 23 | if err != nil { 24 | return err 25 | } 26 | 27 | service := api.Service 28 | host := "0.0.0.0" 29 | port := strconv.Itoa(defaultPort) 30 | 31 | return genFile(fileGenConfig{ 32 | dir: dir, 33 | subdir: etcDir, 34 | filename: fmt.Sprintf("%s.yaml", filename), 35 | templateName: "etcTemplate", 36 | category: category, 37 | templateFile: etcTemplateFile, 38 | builtinTemplate: etcTemplate, 39 | data: map[string]string{ 40 | "serviceName": service.Name, 41 | "host": host, 42 | "port": port, 43 | }, 44 | }) 45 | } 46 | -------------------------------------------------------------------------------- /goctl/home/1.3.6-beta/model/model.tpl: -------------------------------------------------------------------------------- 1 | package {{.pkg}} 2 | {{if .withCache}} 3 | import ( 4 | "github.com/zeromicro/go-zero/core/stores/cache" 5 | "github.com/zeromicro/go-zero/core/stores/sqlx" 6 | ) 7 | {{else}} 8 | import "github.com/zeromicro/go-zero/core/stores/sqlx" 9 | {{end}} 10 | var _ {{.upperStartCamelObject}}Model = (*custom{{.upperStartCamelObject}}Model)(nil) 11 | 12 | type ( 13 | // {{.upperStartCamelObject}}Model is an interface to be customized, add more methods here, 14 | // and implement the added methods in custom{{.upperStartCamelObject}}Model. 15 | {{.upperStartCamelObject}}Model interface { 16 | {{.lowerStartCamelObject}}Model 17 | } 18 | 19 | custom{{.upperStartCamelObject}}Model struct { 20 | *default{{.upperStartCamelObject}}Model 21 | } 22 | ) 23 | 24 | // New{{.upperStartCamelObject}}Model returns a model for the database table. 25 | func New{{.upperStartCamelObject}}Model(conn sqlx.SqlConn{{if .withCache}}, c cache.CacheConf{{end}}) {{.upperStartCamelObject}}Model { 26 | return &custom{{.upperStartCamelObject}}Model{ 27 | default{{.upperStartCamelObject}}Model: new{{.upperStartCamelObject}}Model(conn{{if .withCache}}, c{{end}}), 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /goctl/goctl/api/ktgen/cmd.go: -------------------------------------------------------------------------------- 1 | package ktgen 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/spf13/cobra" 7 | "github.com/zeromicro/go-zero/tools/goctl/api/parser" 8 | ) 9 | 10 | var ( 11 | // VarStringDir describes a directory. 12 | VarStringDir string 13 | // VarStringAPI describes an API. 14 | VarStringAPI string 15 | // VarStringPKG describes a package. 16 | VarStringPKG string 17 | ) 18 | 19 | // KtCommand generates kotlin code command entrance 20 | func KtCommand(_ *cobra.Command, _ []string) error { 21 | apiFile := VarStringAPI 22 | if apiFile == "" { 23 | return errors.New("missing -api") 24 | } 25 | dir := VarStringDir 26 | if dir == "" { 27 | return errors.New("missing -dir") 28 | } 29 | pkg := VarStringPKG 30 | if pkg == "" { 31 | return errors.New("missing -pkg") 32 | } 33 | 34 | api, e := parser.Parse(apiFile) 35 | if e != nil { 36 | return e 37 | } 38 | 39 | if err := api.Validate(); err != nil { 40 | return err 41 | } 42 | 43 | api.Service = api.Service.JoinPrefix() 44 | e = genBase(dir, pkg, api) 45 | if e != nil { 46 | return e 47 | } 48 | e = genApi(dir, pkg, api) 49 | if e != nil { 50 | return e 51 | } 52 | return nil 53 | } 54 | -------------------------------------------------------------------------------- /goctl/goctl/docker/template.go: -------------------------------------------------------------------------------- 1 | package docker 2 | 3 | import ( 4 | _ "embed" 5 | 6 | "github.com/zeromicro/go-zero/tools/goctl/util/pathx" 7 | ) 8 | 9 | const ( 10 | category = "docker" 11 | dockerTemplateFile = "docker.tpl" 12 | ) 13 | 14 | //go:embed docker.tpl 15 | var dockerTemplate string 16 | 17 | // Clean deletes all templates files 18 | func Clean() error { 19 | return pathx.Clean(category) 20 | } 21 | 22 | // GenTemplates creates docker template files 23 | func GenTemplates() error { 24 | return initTemplate() 25 | } 26 | 27 | // Category returns the const string of docker category 28 | func Category() string { 29 | return category 30 | } 31 | 32 | // RevertTemplate recovers the deleted template files 33 | func RevertTemplate(name string) error { 34 | return pathx.CreateTemplate(category, name, dockerTemplate) 35 | } 36 | 37 | // Update deletes and creates new template files 38 | func Update() error { 39 | err := Clean() 40 | if err != nil { 41 | return err 42 | } 43 | 44 | return initTemplate() 45 | } 46 | 47 | func initTemplate() error { 48 | return pathx.InitTemplates(category, map[string]string{ 49 | dockerTemplateFile: dockerTemplate, 50 | }) 51 | } 52 | -------------------------------------------------------------------------------- /goctl/goctl/util/stringx/string_test.go: -------------------------------------------------------------------------------- 1 | package stringx 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestString_IsEmptyOrSpace(t *testing.T) { 10 | ret := From(" ").IsEmptyOrSpace() 11 | assert.Equal(t, true, ret) 12 | ret2 := From("ll??").IsEmptyOrSpace() 13 | assert.Equal(t, false, ret2) 14 | ret3 := From(` 15 | `).IsEmptyOrSpace() 16 | assert.Equal(t, true, ret3) 17 | } 18 | 19 | func TestString_Snake2Camel(t *testing.T) { 20 | ret := From("____this_is_snake").ToCamel() 21 | assert.Equal(t, "ThisIsSnake", ret) 22 | 23 | ret2 := From("测试_test_Data").ToCamel() 24 | assert.Equal(t, "测试TestData", ret2) 25 | 26 | ret3 := From("___").ToCamel() 27 | assert.Equal(t, "", ret3) 28 | 29 | ret4 := From("testData_").ToCamel() 30 | assert.Equal(t, "TestData", ret4) 31 | 32 | ret5 := From("testDataTestData").ToCamel() 33 | assert.Equal(t, "TestDataTestData", ret5) 34 | } 35 | 36 | func TestString_Camel2Snake(t *testing.T) { 37 | ret := From("ThisIsCCCamel").ToSnake() 38 | assert.Equal(t, "this_is_c_c_camel", ret) 39 | 40 | ret2 := From("测试Test_Data_test_data").ToSnake() 41 | assert.Equal(t, "测试_test__data_test_data", ret2) 42 | } 43 | -------------------------------------------------------------------------------- /app/msg/cmd/rpc/chat.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/internal/config" 8 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/internal/server" 9 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/internal/svc" 10 | "github.com/showurl/Zero-IM-Server/app/msg/cmd/rpc/pb" 11 | 12 | "github.com/zeromicro/go-zero/core/conf" 13 | "github.com/zeromicro/go-zero/core/service" 14 | "github.com/zeromicro/go-zero/zrpc" 15 | "google.golang.org/grpc" 16 | "google.golang.org/grpc/reflection" 17 | ) 18 | 19 | var configFile = flag.String("f", "etc/chat.yaml", "the config file") 20 | 21 | func main() { 22 | flag.Parse() 23 | 24 | var c config.Config 25 | conf.MustLoad(*configFile, &c) 26 | ctx := svc.NewServiceContext(c) 27 | svr := server.NewChatServer(ctx) 28 | 29 | s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { 30 | pb.RegisterChatServer(grpcServer, svr) 31 | 32 | if c.Mode == service.DevMode || c.Mode == service.TestMode { 33 | reflection.Register(grpcServer) 34 | } 35 | }) 36 | defer s.Stop() 37 | 38 | fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) 39 | s.Start() 40 | } 41 | -------------------------------------------------------------------------------- /goctl/goctl/bug/bug.go: -------------------------------------------------------------------------------- 1 | package bug 2 | 3 | import ( 4 | "fmt" 5 | "net/url" 6 | "os/exec" 7 | "runtime" 8 | 9 | "github.com/spf13/cobra" 10 | "github.com/zeromicro/go-zero/tools/goctl/internal/version" 11 | ) 12 | 13 | const ( 14 | windows = "windows" 15 | darwin = "darwin" 16 | 17 | windowsOpen = "start" 18 | darwinOpen = "open" 19 | linuxOpen = "xdg-open" 20 | 21 | os = "OS" 22 | arch = "ARCH" 23 | goctlVersion = "GOCTL_VERSION" 24 | goVersion = "GO_VERSION" 25 | ) 26 | 27 | var openCmd = map[string]string{ 28 | windows: windowsOpen, 29 | darwin: darwinOpen, 30 | } 31 | 32 | func runE(_ *cobra.Command, _ []string) error { 33 | env := getEnv() 34 | content := fmt.Sprintf(issueTemplate, version.BuildVersion, env.string()) 35 | content = url.QueryEscape(content) 36 | url := fmt.Sprintf("https://github.com/zeromicro/go-zero/issues/new?body=%s", content) 37 | 38 | goos := runtime.GOOS 39 | var cmd string 40 | var args []string 41 | cmd, ok := openCmd[goos] 42 | if !ok { 43 | cmd = linuxOpen 44 | } 45 | if goos == windows { 46 | args = []string{"/c", "start"} 47 | } 48 | 49 | args = append(args, url) 50 | return exec.Command(cmd, args...).Start() 51 | } 52 | -------------------------------------------------------------------------------- /goctl/goctl/model/sql/template/delete.go: -------------------------------------------------------------------------------- 1 | package template 2 | 3 | const ( 4 | // Delete defines a delete template 5 | Delete = ` 6 | func (m *default{{.upperStartCamelObject}}Model) Delete(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) error { 7 | {{if .withCache}}{{if .containsIndexCache}}data, err:=m.FindOne(ctx, {{.lowerStartCamelPrimaryKey}}) 8 | if err!=nil{ 9 | return err 10 | } 11 | 12 | {{end}} {{.keys}} 13 | _, err {{if .containsIndexCache}}={{else}}:={{end}} m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 14 | query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table) 15 | return conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}}) 16 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table) 17 | _,err:=m.conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}}){{end}} 18 | return err 19 | } 20 | ` 21 | 22 | // DeleteMethod defines a delete template for interface method 23 | DeleteMethod = `Delete(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) error` 24 | ) 25 | -------------------------------------------------------------------------------- /app/im-user/cmd/rpc/internal/logic/getSingleConversationRecvMsgOptsLogic.go: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/showurl/Zero-IM-Server/app/im-user/cmd/rpc/internal/svc" 7 | "github.com/showurl/Zero-IM-Server/app/im-user/cmd/rpc/pb" 8 | 9 | "github.com/zeromicro/go-zero/core/logx" 10 | ) 11 | 12 | type GetSingleConversationRecvMsgOptsLogic struct { 13 | ctx context.Context 14 | svcCtx *svc.ServiceContext 15 | logx.Logger 16 | } 17 | 18 | func NewGetSingleConversationRecvMsgOptsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSingleConversationRecvMsgOptsLogic { 19 | return &GetSingleConversationRecvMsgOptsLogic{ 20 | ctx: ctx, 21 | svcCtx: svcCtx, 22 | Logger: logx.WithContext(ctx), 23 | } 24 | } 25 | 26 | // 获取单聊会话的消息接收选项 27 | func (l *GetSingleConversationRecvMsgOptsLogic) GetSingleConversationRecvMsgOpts(in *pb.GetSingleConversationRecvMsgOptsReq) (*pb.GetSingleConversationRecvMsgOptsResp, error) { 28 | // todo: add your logic here and delete this line 29 | 30 | return &pb.GetSingleConversationRecvMsgOptsResp{ 31 | CommonResp: &pb.CommonResp{ 32 | ErrCode: 0, 33 | ErrMsg: "", 34 | }, 35 | Opts: pb.RecvMsgOpt_ReceiveMessage, 36 | }, nil 37 | } 38 | -------------------------------------------------------------------------------- /app/auth/cmd/rpc/auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/internal/config" 8 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/internal/server" 9 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/internal/svc" 10 | "github.com/showurl/Zero-IM-Server/app/auth/cmd/rpc/pb" 11 | 12 | "github.com/zeromicro/go-zero/core/conf" 13 | "github.com/zeromicro/go-zero/core/service" 14 | "github.com/zeromicro/go-zero/zrpc" 15 | "google.golang.org/grpc" 16 | "google.golang.org/grpc/reflection" 17 | ) 18 | 19 | var configFile = flag.String("f", "etc/auth.yaml", "the config file") 20 | 21 | func main() { 22 | flag.Parse() 23 | 24 | var c config.Config 25 | conf.MustLoad(*configFile, &c) 26 | ctx := svc.NewServiceContext(c) 27 | svr := server.NewAuthServiceServer(ctx) 28 | 29 | s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { 30 | pb.RegisterAuthServiceServer(grpcServer, svr) 31 | 32 | if c.Mode == service.DevMode || c.Mode == service.TestMode { 33 | reflection.Register(grpcServer) 34 | } 35 | }) 36 | defer s.Stop() 37 | 38 | fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) 39 | s.Start() 40 | } 41 | -------------------------------------------------------------------------------- /common/xorm/global/basemodel.go: -------------------------------------------------------------------------------- 1 | package global 2 | 3 | import ( 4 | envUtils "github.com/showurl/Zero-IM-Server/common/utils/env" 5 | "gorm.io/gorm" 6 | ) 7 | 8 | type BaseModel struct { 9 | ID string `json:"id" gorm:"primarykey;type:bigint(20);comment:'主键'"` 10 | CreatedAt ModelTime `json:"created_at" gorm:"column:created_at;index;comment:'创建时间'"` 11 | UpdatedAt ModelTime `json:"-" gorm:"column:updated_at;index;comment:'更新时间'"` 12 | DeletedAt gorm.DeletedAt `json:"-" gorm:"index;comment:'删除时间'"` 13 | } 14 | 15 | // DetailExpiredSecond 缓存默认5分钟过期 16 | func (b *BaseModel) DetailExpiredSecond() int { 17 | if envUtils.IsDev() { 18 | return 60 * 60 * 24 * 30 19 | } 20 | return 60 * 5 21 | } 22 | 23 | // RelationExpiredSecond 缓存默认5分钟过期 24 | func (b *BaseModel) RelationExpiredSecond() int { 25 | if envUtils.IsDev() { 26 | return 60 * 60 * 24 * 30 27 | } 28 | return 60 * 5 29 | } 30 | 31 | func (b *BaseModel) GetIdString() string { 32 | return b.ID 33 | } 34 | 35 | func (b *BaseModel) BeforeCreate(tx *gorm.DB) error { 36 | if b.ID == "0" || b.ID == "" { 37 | b.ID = GetID() 38 | } 39 | return nil 40 | } 41 | 42 | func (b *BaseModel) AfterFind(tx *gorm.DB) error { 43 | return nil 44 | } 45 | -------------------------------------------------------------------------------- /goctl/goctl/pkg/protocgengogrpc/protocgengogrpc.go: -------------------------------------------------------------------------------- 1 | package protocgengogrpc 2 | 3 | import ( 4 | "strings" 5 | 6 | "github.com/zeromicro/go-zero/tools/goctl/pkg/goctl" 7 | "github.com/zeromicro/go-zero/tools/goctl/pkg/golang" 8 | "github.com/zeromicro/go-zero/tools/goctl/rpc/execx" 9 | "github.com/zeromicro/go-zero/tools/goctl/util/env" 10 | ) 11 | 12 | const ( 13 | Name = "protoc-gen-go-grpc" 14 | url = "google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest" 15 | ) 16 | 17 | func Install(cacheDir string) (string, error) { 18 | return goctl.Install(cacheDir, Name, func(dest string) (string, error) { 19 | err := golang.Install(url) 20 | return dest, err 21 | }) 22 | } 23 | 24 | func Exists() bool { 25 | _, err := env.LookUpProtocGenGoGrpc() 26 | return err == nil 27 | } 28 | 29 | // Version is used to get the version of the protoc-gen-go-grpc plugin. 30 | func Version() (string, error) { 31 | path, err := env.LookUpProtocGenGoGrpc() 32 | if err != nil { 33 | return "", err 34 | } 35 | version, err := execx.Run(path+" --version", "") 36 | if err != nil { 37 | return "", err 38 | } 39 | fields := strings.Fields(version) 40 | if len(fields) > 1 { 41 | return fields[1], nil 42 | } 43 | return "", nil 44 | } 45 | --------------------------------------------------------------------------------