Compare commits

..
Author SHA1 Message Date
zhangwenjian 39ea1f6aef fix🐛: normalize a NULL data scope too, not just an unrecognized one
`NULL NOT IN (...)` evaluates to NULL rather than true, so the previous
condition left a NULL data_scope exactly as it found it - and NULL is the one
value that most needs the repair: it scans into a Go string as "", which is
what the fail-closed default now refuses.

The column has no NOT NULL constraint, so the value is reachable from any
writer that is not the admin UI.

Claude-Session: https://claude.ai/code/session_01HPTAw8b8tAdFNFn8rKdPYx
2026-09-04 19:10:53 +08:00
zhangwenjian b2053f507a refactor🎨: drop the unused second data permission implementation
app/admin/models/datascope.go carried a second copy of the scope logic with no
callers. Its department-tree pattern was written as "%" + id + "%" instead of
"%/" + id + "/%", so dept_id 1 also matched /11/, /21/ and /100/ - visibility
into unrelated subtrees.

It sat where someone looking for a data permission example would find it. The
copy that is actually wired up stays in common/actions.

Claude-Session: https://claude.ai/code/session_01HPTAw8b8tAdFNFn8rKdPYx
2026-09-04 17:24:55 +08:00
zhangwenjian 9520117914 feat✨: normalize invalid data scopes on existing installs
The seed fix only reaches new installations. An install that imported the old
db.sql already has an administrator with an empty data_scope, and after the
fail-closed change that account sees nothing.

The migration rewrites any value outside "1".."5" to "1", which is the
behaviour those rows had before. Plain SQL rather than the frozen migration
models, per the rule that migrations after 1786700003000 must not use them.

Claude-Session: https://claude.ai/code/session_01HPTAw8b8tAdFNFn8rKdPYx
2026-09-04 17:24:55 +08:00
zhangwenjian 7a5fc7d440 fix🐛: give the seeded admin role an explicit data scope
The shipped seed data left data_scope empty for the built-in administrator.
That was harmless while an unrecognized scope meant "see everything"; with the
previous commits it means the opposite, so a fresh install with data permission
enabled would have blinded its own default account on every list endpoint.

The admin short-circuit does not help here: role_key == "admin" bypasses Casbin,
not the data permission scopes, which never look at role_key.

The value is "1" - all data - which is the behaviour the empty string used to
produce, so this restores the intent rather than tightening it. A test reads
both seed files back so the pair cannot drift apart again.

Claude-Session: https://claude.ai/code/session_01HPTAw8b8tAdFNFn8rKdPYx
2026-09-04 17:24:41 +08:00
zhangwenjian bd5e83d464 fix🐛: validate data scope on the role DTOs
Nothing checked what went into sys_role.data_scope, so creating a role without
a dataScope stored an empty string - the value that used to be indistinguishable
from "see everything".

All three DTOs that write the column are validated, not just the insert path:
they target the same column, and guarding one entrance while leaving two open
would not be a guard.

Claude-Session: https://claude.ai/code/session_01HPTAw8b8tAdFNFn8rKdPYx
2026-09-04 17:24:41 +08:00
zhangwenjian 63dd40a8d7 test✅: cover the data scope failure directions
A table over all five scopes plus the ones that are not scopes, asserting the
generated SQL rather than a boolean, because the defect was that two different
intentions produced the same query.

The rows that matter are the negative ones: an unrecognized value, a zero
value, and a department scope with a non-positive id. Each was verified to go
red with its own fix reverted and the others in place, so a regression names
the defect it belongs to.

Claude-Session: https://claude.ai/code/session_01HPTAw8b8tAdFNFn8rKdPYx
2026-09-04 17:24:41 +08:00
zhangwenjian 32bd88504d fix🐛: fail closed when the department id is not positive
dept_path is built as "/0/" + id + "/..." for every department, so a DeptId of
0 turns the department-tree pattern into '%/0/%' - which matches every row in
sys_dept. The scope meant to narrow visibility to one subtree returned the
whole organisation instead.

Both department scopes now refuse a non-positive id rather than building a
pattern from it. The admin DTO validates deptId, but seed scripts, SSO and
third-party registration paths do not, and after the contract move the caller
is no longer ours to control.

Claude-Session: https://claude.ai/code/session_01HPTAw8b8tAdFNFn8rKdPYx
2026-09-04 17:24:26 +08:00
zhangwenjian d70818a9db fix🐛: fail closed on an unrecognized data scope
The switch ended in `default: return db`, which is the same answer as "this
role may see everything". That made a legitimate scope indistinguishable from a
broken one: "1" (all data) had no case of its own and fell into default too, so
"1", "", "6" and a zero value all produced byte-identical SQL.

Three changes, in this order, because reversing them would break "1":

  - the five scope values become named constants, so a reader can tell which
    string means what without consulting the seed data
  - "1" gets an explicit case, which is what frees default to mean "not a
    scope I recognise"
  - default now matches nothing rather than everything

SysRole DTOs accept the scope unvalidated, so an empty string reaches this
switch from ordinary use, not just from a corrupted row.

Claude-Session: https://claude.ai/code/session_01HPTAw8b8tAdFNFn8rKdPYx
2026-09-04 17:24:26 +08:00
zhangwenjian 9d4a425fc0 fix🐛: abort the request when the ORM is unavailable
PermissionAction logged the error and returned. Gin treats a plain return as
"carry on", so the request reached the business handler with PermissionKey
never set - and a zero DataPermission means Permission() adds no WHERE clause
at all. A database hiccup turned into full visibility, silently.

The neighbouring newDataPermission branch already aborts. This one now does the
same.

Claude-Session: https://claude.ai/code/session_01HPTAw8b8tAdFNFn8rKdPYx
2026-09-04 17:24:12 +08:00
wenjianzhang 34773a0a81 Merge pull request #894 from go-admin-team/chore/core-v2.4.1
Bump go-admin-core to v2.4.1
2026-09-01 20:47:11 +08:00
zhangwenjian 36a018400b chore🔧(deps): bump go-admin-core to v2.4.1
Documentation wording only; no code change between the two.
2026-09-01 20:42:36 +08:00
wenjianzhang 7bb02c5f1d Merge pull request #893 from go-admin-team/docs/contract-wording
Describe the rules rather than who follows them
2026-09-01 20:38:34 +08:00
zhangwenjian 15fb128236 docs📝: describe the rules rather than who follows them
The warning on Authorizator matters to anyone keeping a copy of that file, not
to one particular consumer, and it reads better addressed to all of them: check
what reads those context keys before taking this change.
2026-09-01 19:56:27 +08:00
wenjianzhang 3581e060ec Merge pull request #891 from go-admin-team/feat/003-app-prep
Groundwork for installable applications
2026-09-01 19:38:23 +08:00
zhangwenjian 0604a29596 feat✨(server): run the startup hooks through core
The package-level AppRouters slice keeps working and keeps running first, so
a fork that only ever appended to it sees no change. What is new is that the
core registry runs too, and that before callbacks run at all - this server
never had a loop for them.

Both go through core RunAppRouters / RunBefore, which brings the panic guard
and the seal with them.
2026-09-01 18:18:38 +08:00
zhangwenjian d8a2958797 chore🔧(deps): bump go-admin-core to v2.4.0 2026-09-01 18:18:38 +08:00
zhangwenjian ab28fa7bed docs📝: write down what a third-party app may depend on 2026-09-01 17:45:41 +08:00
zhangwenjian e88d751039 chore🔧: run the silent-failure checks in CI 2026-09-01 17:45:41 +08:00
zhangwenjian b836945eea feat✨: add checksilent, for the failures that do not report themselves
Six checks, five at ERROR and one - the cross-repository menu-name comparison -
at WARN, because it can only match by regular expression across two modules and
a false positive that fails CI teaches people to silence the tool.

The summary names which contract roots were actually scanned: core/ is a
separate module with no directory here, and a check that quietly covers less
than it claims is worse than no check.
2026-09-01 17:45:41 +08:00
zhangwenjian d7a8e66753 feat✨: add migrate status, --dry-run and --app
--app rejects a code nothing was registered under, on all three paths. It used
to take a typo as "nothing matched" and report success: migrate said the app
was unknown and still exited 0, while --dry-run and status printed the same
words an up-to-date database produces.
2026-09-01 17:45:40 +08:00
zhangwenjian 68780a845c feat✨: register migrations under an app code with ForApp 2026-09-01 17:45:40 +08:00
zhangwenjian 487dc94a2e feat✨: record on sys_migration which app a migration belongs to 2026-09-01 17:45:40 +08:00
zhangwenjian 016e977776 refactor🎨: drop Authorizator assertions that never matched
The map Authorizator receives is built by IdentityHandler in the same file and
carries IdentityKey / UserName / RoleKey / UserId / RoleIds / DataScope - not
user and role. Both assertions failed on every request, and because the ok
result was discarded the five c.Set calls stored zero values and the function
returned true anyway. Nothing in this repository or in core reads those keys.

go-admin-pro has its own copy of this file and does read them; this change
must not be carried over there verbatim.
2026-09-01 17:45:40 +08:00
zhangwenjian dcfe512204 refactor🎨: move the operation log status constants out of app/admin
common/middleware imported app/admin/service/dto for two string constants,
which made a package apps are told to build on depend on one particular app.
2026-09-01 17:45:40 +08:00
zhangwenjian fe6ebfd47c chore🔧: ignore the Go workspace files and the checksilent binary
go.work points this module at a local checkout of go-admin-core while the
two are developed together. It is a local tool and must never be committed:
CI resolves core from go.mod.

checksilent is where `go build ./tools/checksilent` drops its binary - four
megabytes beside the server one, which was already ignored by name.
2026-09-01 17:45:40 +08:00
wenjianzhang eba5fba3da Merge pull request #889 from go-admin-team/fix/password-hook-and-body-buffering
fix: a password hook that could destroy credentials, and a body copy on every request
2026-09-01 14:22:13 +08:00
zhangwenjian b7e9a79225 fix🐛: refuse an out-of-scope API update with the permission message
The previous commit added a data-permission scope to SysApi.Update and
returned early on db.Error, which left the RowsAffected check below it
unreachable: First reports a row the scope excluded as ErrRecordNotFound,
so the caller got "record not found" where the code meant to say
"无权更新该数据".

Map that one error to the permission message and drop the check it made
dead. The two cases - the row does not exist, and the row exists but is
not yours - have to look the same from outside, and now do.

Found by Copilot's review of #889.
2026-09-01 14:17:20 +08:00
wenjianzhang deffb19fd8 Merge pull request #888 from go-admin-team/ci/run-tests
Run the test suite in CI
2026-09-01 11:38:10 +08:00
zhangwenjian c858b322bd fix🐛: apply the data permission when updating an API
SysApi.Update took a DataPermission and never used it, so with data
permission enabled the update reached rows the caller could not read
through GetPage, Get or Remove, which all scope the query. It also
reported "无权更新该数据" for a row that simply did not exist, a message
that only becomes true once the scope is applied.

Drops the Debug() left on the query, which logged the statement for
every call.
2026-09-01 11:35:51 +08:00
zhangwenjian 1b5b52f0f1 perf👌: only read the request body when the operation log will store it
LoggerToFile is registered on the engine, so every POST, PUT, GET and
DELETE had its body copied into memory - through a bytes.Buffer, a
ReadAll and a string conversion - before any handler ran. The only
consumer is operParam on the operation-log row, which is written when
logger.enableddb is on, and that is off in the shipped configuration.

There was no size limit either, and a file upload is a POST like any
other: a 1MB request allocated 4.3MB here and a 16MB upload allocated
about 67MB, to build a value nobody stored.

The body is now read only when the operation log will use it, and at
most 32KB of it. The handler still receives the whole request: it reads
the copied part from memory and the rest from the connection, so what
this holds is bounded however large the request is. 32KB also keeps the
value inside the TEXT column it is written to.

The bufio.Writer this replaces was never flushed. Nothing was truncated
only because bytes.Buffer implements io.ReaderFrom, so io.Copy bypassed
the buffer entirely - a different destination would have dropped the
tail of every request body.
2026-09-01 11:35:45 +08:00
zhangwenjian ecb31a158b fix🐛: stop re-hashing a password that is already hashed
BeforeCreate and BeforeUpdate run Encrypt on whatever is in the struct,
and a user read from the database carries the stored hash in Password.
Hashing it again produces a hash of a hash: the password that user knows
stops matching, they cannot log in, and nothing reports an error.

Only the Omit("password") on SysUser.Update stood between that and the
stored credential. Any other write to this model - a profile update
written the way every other model here is written - destroys the
password, permanently and silently.

Encrypt now returns early when Password already parses as a bcrypt hash.
That also removes the round SysUser.Update was paying and discarding:
306ns where it was 54.7ms, on a route reachable without the permission
check, since PUT /api/v1/sys-user is in CasbinExclude.

The cost of deciding from the value is that a password which is itself a
well-formed bcrypt hash would be stored unchanged. That is a
60-character string beginning "$2a$", and it grants whoever set it no
access they did not already have.
2026-09-01 11:35:33 +08:00
zhangwenjian 1aecc140dc ci🔧: run the test suite on every push and pull request
The repository has 19 test files and nothing was running any of them. Both
workflows build with go build, which does not compile _test.go, the Makefile's
test target was commented out, and there is no pre-commit hook. Every test in
the tree, including the schema guards that exist precisely to catch a silent
breakage, only ran when someone remembered to type go test.

Enables the commented-out target and calls it from go.yml, the one workflow
that fires on every push and pull request. build.yml is left alone: it skips
documentation-only changes and deploys on master, so it is the wrong place for
a gate that should never be skipped.

Runs with -race. common/actions reuses model instances across concurrent
requests, so a Generate() that returns in place rather than a copy leaks data
between them, which a single-threaded run cannot see.

Verified locally: the suite passes under CGO_ENABLED=0 and under -race, and
make test exits non-zero when a test fails, so the step actually gates.

Claude-Session: https://claude.ai/code/session_01DJhM6LvhkNPej35wy9F7Aq
2026-09-01 11:33:08 +08:00
wenjianzhang e464a4aedd Merge pull request #887 from go-admin-team/fix/migration-model-soft-delete-drift
Guard new migrations against the frozen seed models
2026-08-31 15:06:05 +08:00
wenjianzhang 595c4a6be5 Merge pull request #885 from go-admin-team/fix/casbin-tenant-and-pattern-cache
fix: key the casbin enforcer by tenant, and stop recompiling patterns in the exclusion scan
2026-08-31 15:01:42 +08:00
zhangwenjian d115c5299c docs📝: say which models package a new migration may seed through
The hazard had no signal at its point of contact. Someone adding a business
module is told to copy 1786700001000_demo_menu.go, which imports the frozen
seed models - correct for that file, wrong for anything ordered after the
soft-delete conversion. The frozen ModelTime carried no comment at all, so
opening it taught the reader nothing.

Documents the boundary in three places the author actually passes through:
the frozen type itself, the contributor guide, and the module-scaffolding
skill, which previously said to copy the reference file verbatim and now
says to copy its structure but not its imports.

Claude-Session: https://claude.ai/code/session_01DJhM6LvhkNPej35wy9F7Aq
2026-08-31 15:01:26 +08:00
zhangwenjian 9bd542bb59 test✅: guard post-conversion migrations against the frozen seed models
Migrations ordered after 1786700003000 must not seed through
cmd/migrate/migration/models. That package's ModelTime declares a nullable
gorm.DeletedAt, which is the shape the columns had until that migration
converted deleted_at to a NOT NULL millisecond marker.

Afterwards it breaks in both directions. Writes put NULL into a NOT NULL
column and fail on the first insert. Reads are scoped "WHERE deleted_at IS
NULL" while live rows hold 0, so they match nothing - and 1786700001000
looks the admin role up that way and treats ErrRecordNotFound as "roles are
not seeded yet, skip authorisation", which would leave a module seeded with
no permissions and the migration still recorded as applied.

A fresh database does not surface either one: every migration using that
package today is ordered before the conversion, so it runs while the column
is still nullable. Only a migration added afterwards hits it.

Also pulls the import scan out of importsRuntimeModels so both checks share
one implementation, and derives the version through migration.GetFilename
rather than a second filename-parsing rule.

Verified by adding a violating migration and confirming the test fails with
an actionable message, then removing it and confirming the suite passes.

Claude-Session: https://claude.ai/code/session_01DJhM6LvhkNPej35wy9F7Aq
2026-08-31 15:01:11 +08:00
zhangwenjian 0fa015b6d0 perf👌: stop recompiling patterns when scanning the casbin exclusion list
AuthCheckRole walks CasbinExclude for every non-admin request, and used
casbin's util.KeyMatch2 to test each entry. That delegates to
util.RegexMatch, which is regexp.MatchString - it compiles its pattern on
every call - so a 32-entry list cost about 2,566 allocations per request
before the request reached Enforce.

Test the method first, which rules out most entries with a string
compare, and take the path test from go-admin-core, whose KeyMatch2
answers the same thing without recompiling. The scan drops to 52ns and no
allocations.

The loop moves out of AuthCheckRole so the tests exercise the code a
request runs rather than a copy of it, and an allocation budget fails if
the uncached matcher comes back.
2026-08-31 14:01:32 +08:00
zhangwenjian ec7d838ebd fix🐛: key the casbin enforcer by tenant host
setupSimpleDatabase runs once per configured database - one per host in
the multi-tenant configuration - and passed the same empty key to
mycasbin.Setup every time. Setup caches per key, so every host after the
first was handed the enforcer built from the first host's database and
was authorized against a casbin_rule table that was not its own.

Takes effect with the go-admin-core release that keys the cache; before
it, Setup ignored the argument entirely.
2026-08-30 10:03:26 +08:00
wenjianzhang 26e116c16c Merge pull request #884 from go-admin-team/ci/skip-deploy-for-docs
ci🔧: skip the deploy workflow for documentation-only changes
2026-08-29 14:49:39 +08:00
zhangwenjian 90d98893f5 ci🔧: skip the deploy workflow for documentation-only changes
A push to master here does not just build: it pushes an image, runs the
migrations and restarts the demo container, so the site takes a short outage
each time. The last two merges were markdown only and both paid for it.

Beyond the waste, a deploy can fail for reasons unrelated to the change that
triggered it - a container that will not come up, a database that is briefly
unreachable - and a README edit should not be able to turn the demo red.

Only build.yml is filtered. go.yml still builds on every push and pull request,
so nothing loses its compile check, and the badge keeps reporting the same
workflow it reports today.
2026-08-29 14:29:05 +08:00
wenjianzhang 10f162bf5d Merge pull request #883 from go-admin-team/fix/readme-vitepress-syntax
docs📝: drop VitePress container syntax GitHub cannot render
2026-08-29 14:28:11 +08:00
zhangwenjian 19909746f5 docs📝: drop VitePress container syntax GitHub cannot render
`:::tip` and its closing `:::` are VitePress custom containers. GitHub has no
such syntax, so both markers rendered as literal text: a paragraph beginning
":::tip" and a stray ":::" sitting alone above the next heading.

The Chinese README carries the same warning as a plain paragraph, which GitHub
renders correctly, so the English one now matches it. Verified through GitHub's
own markdown API: the literal marker no longer appears in the output and the
warning survives as ordinary text.

Only README.md was affected; the other three never had it.
2026-08-28 20:36:24 +08:00
wenjianzhang 205febdb8a Merge pull request #882 from go-admin-team/docs/readme-links-and-languages
docs📝: fix the badges and links, add Traditional Chinese and Japanese READMEs
2026-08-28 20:32:13 +08:00
zhangwenjian 5aec4ba32b docs📝: add Traditional Chinese and Japanese READMEs
The project had English and Simplified Chinese. These two follow the same
structure - same sections, same code blocks, same contributor list - so a
reader in any of the four sees the same document.

The Traditional Chinese is a translation rather than a character conversion of
the Simplified: the terminology differs (設定檔, 資料庫, 選單, 程式碼產生,
排程任務, 相依套件), and a converted file would read as machine output to
anyone who actually uses it.

Language navigation across all four is unified in the same commit, since a link
to a file that does not exist yet would be worse than no link.
2026-08-28 20:19:50 +08:00
zhangwenjian 8f1ea50dfe docs📝: point the badges and documentation links at the right places
The build badge rendered "build - failing" on both READMEs while CI was green.
It referenced the workflow under the old personal repository path, where the
status has been stale for years - so the first thing anyone saw on opening the
project was a failed build. It now points at the current repository, names the
workflow file explicitly, and pins the branch, so it reports master rather than
whatever happens to be the default branch later.

The workflow it reports on is go.yml, which is what the old badge referenced
by workflow name and is the right one to show: build.yml also deploys the demo
site, so a server-side problem there would turn the badge red while the code
is fine.

The licence badge read from mashape/apistatus, the example repository from
shields.io's own documentation. It happened to show MIT, the same licence this
project uses, so nobody noticed - but it reports someone else's licence.

Documentation links were spread across three hosts: doc.go-admin.dev redirects
to www.go-admin.pro, www.go-admin.dev serves byte-identical content, and only
the Chinese README linked the canonical host at all. All of them now point at
www.go-admin.pro directly rather than relying on a redirect outliving the
domain that issues it.

Two smaller ones: the gorm link pointed at the archived v1 repository while the
project builds on gorm.io v2, and the English introduction listed two UI kits
where the Chinese listed three, with an Ant Design demo linked directly below.
2026-08-28 20:19:50 +08:00
wenjianzhang 1483ca401d Merge pull request #881 from go-admin-team/fix/production-defaults
fix🐛: the settings a deployment needs, and the ones that were leaking
2026-08-28 19:50:18 +08:00
zhangwenjian ed74623a73 test✅: add an end-to-end load test harness
Skipped unless GOADMIN_BENCH_ADDR points at a running server, so `go test
./...` is unaffected.

Reports latency percentiles rather than an average, which is what capacity
planning needs, and a status-code distribution - that last part is how the rate
limiter's 200-on-rejection was found, since throughput alone looked excellent
while nothing reached a handler.

Includes a routing-floor control case. When a business endpoint matches it, the
measurement has stopped describing the endpoint and started describing the
transport, or the load generator when both share a machine.
2026-08-28 19:42:38 +08:00
zhangwenjian 1bc2e22833 fix🐛: give the config templates the defaults a deployment actually needs
Two settings that decide whether a deployment survives load, neither of which
appeared in any template.

The connection pool. Left unset, Go's defaults apply, and MaxIdleConns is 2:
under load almost every request opens a TCP connection and closes it again,
local ports run out, and the process answers "can't assign requested address"
to everything. Not slower - unavailable. A sweep against MySQL collapsed to
zero successful responses at 64 concurrent requests without these, and served
13,846 req/s with no errors once they were set.

The queue buffer. poolSize is the point at which messages start being dropped,
not a tuning knob: a full queue discards the message and returns an error
rather than blocking, and each stream has one consumer goroutine writing to the
database. At the previous default of 100 a load test lost over 60% of them; at
1000, none. Login and operation logs travel this queue, so what gets lost is
audit data - though only when logger.enableddb is on.

Both carry the reasoning in the file, because the failure mode of each is
invisible until it happens in production.
2026-08-28 19:42:38 +08:00
zhangwenjian cd8edfa5d4 fix🐛: reject rate-limited requests with 429 and make the threshold configurable
A rejected request answered 200 with the failure only in the body, so every
layer that reads the status line counted it as served: load balancers, metrics,
client-side retry. A load test against this reported the limiter's own
rejections as successful traffic and overstated throughput more than tenfold.

The threshold was a constant in the middleware, which made 200 QPS the ceiling
of every deployment with nothing in the configuration to reveal it. It now
reads extend.rateLimit.inboundQPS; an absent value keeps 200, so an upgrade
changes nothing, and zero disables the limiter for a deployment behind its own
gateway.

Also drops Strategy: system.BBR. Reading sentinel's source, the adaptive
strategy is consulted only for Load and CpuUsage - for InboundQPS the trigger
count is compared directly - so it read as if the limit adapted to the machine
when it never did.
2026-08-28 19:42:21 +08:00
zhangwenjian dcc2c8e175 fix🔒: stop logging the captcha answer
The answer was written at info level on every captcha request, so a currently
valid answer sat in the application log. Anyone able to read the log - an
operator, a log aggregator, anything that ships logs off the host - could
bypass the check the captcha exists to enforce.

The default log level records it, so this was not limited to debug builds.
2026-08-28 19:42:21 +08:00
zhangwenjian d991a285ba chore🔧: upgrade go-admin-core to v2.2.0
Carries four concurrency fixes and a bounded in-memory cache. The two that
reach this repository are the search resolver, which no longer panics on an
unexported field in a DTO and skips tag parsing for zero-valued ones, and the
captcha driver, which is built once rather than per request.

The cache bound does not apply here: config.CacheConfig.Setup() returns the
older Memory implementation, which core leaves unbounded.
2026-08-28 19:42:19 +08:00
wenjianzhang 76c9d1211e Merge pull request #880 from go-admin-team/fix/dsn-in-logs
ci🔧: migrate before deploying, roll back on failure — and stop logging the database password
2026-08-27 17:31:52 +08:00
zhangwenjian f5273f5a58 ci🔧: migrate before deploying, and roll back when the new version does not come up
Closes #871.

The deploy did docker rm -f then docker run. Nothing ran migrations, so
new code met old tables, and nothing checked the result - a container
that exits immediately left the site down with a green deploy.

Now, in order: pull the image, run the migration with it, and only then
touch what is running. A failed migration stops there, leaving old code
with the old schema, which is at least self-consistent.

The running container is renamed rather than removed, so it can be
started again unchanged if the new one does not become healthy. Healthy
means both an HTTP response and a database connection in the log: the
captcha endpoint answers without touching the database, so it alone
would call a container healthy that cannot reach MySQL.
2026-08-27 16:19:03 +08:00
zhangwenjian 54ffaac9c5 chore🔧: say which migration is running, not a column of ones
An applied migration printed its count - a bare '1' - so a database with
seven of them wrote seven lines of '1' at every start, and a failure said
only which error, never which migration.

It now names each one as it applies, reports the total, and says so when
there is nothing to do.
2026-08-27 16:19:03 +08:00
zhangwenjian 484de2e698 fix🔒: stop writing the database password into the log
The startup line printed the DSN whole:

  * => goadmin:<password>@tcp(host:3306)/go-admin?...

So every deployment wrote its own database credential into its own logs,
where a log shipper, a support bundle or a screenshot of a terminal
carries it onward. Found while reading deploy output, which is exactly
how it leaks.

The host and username stay - they are what makes the line worth printing
- and only the password is replaced. Both DSN shapes this project accepts
are covered, a sqlite path is left alone, and anything unparseable is
withheld rather than echoed, since it may hold a credential too.
2026-08-27 16:17:12 +08:00
wenjianzhang d72ff76aad Merge pull request #879 from go-admin-team/ci/config-path-secret
ci🔧: keep the host config path out of a public repository
2026-08-27 15:41:54 +08:00
zhangwenjian 4a523bed92 ci🔧: keep the host config path out of a public repository
The path is not a credential, and the file it points at is 600 and owned
by root, so this is not what protects it. But the repository is public
and there is no reason to publish the server's directory layout next to
the deploy that uses it.

DEMO_CONFIG_PATH holds it instead. It has to be set before this merges,
or the deploy stops at the guard - which is the intended failure: better
that than falling back to the sqlite in the image.
2026-08-27 15:37:09 +08:00
wenjianzhang 55dc33b865 Merge pull request #878 from go-admin-team/ci/demo-on-mysql
ci🔧: run the demo on the managed database instead of a bundled sqlite file
2026-08-27 15:33:15 +08:00
zhangwenjian 3d13f5856a ci🔧: point the demo at the managed database
The demo ran on the sqlite file baked into the image, so every deploy
reset it and nothing there resembled how anyone actually runs this.

The config is mounted from the host rather than taken from the image.
config/settings.demo.yml ships in a public repository and is copied into
a public image, so the connection string cannot live there; that copy
stays on sqlite, which is what a fresh clone should get.

The deploy refuses to start if the host config is missing, rather than
falling back to the image's sqlite and looking like it worked.
2026-08-27 12:48:32 +08:00
wenjianzhang aa2976ba17 Merge pull request #877 from go-admin-team/fix/mysql-fresh-install
fix🐛: MySQL installs could not log in — the migration run stopped at a tinyint overflow
2026-08-27 12:18:04 +08:00
zhangwenjian 8e141ff8a0 fix🐛: the code generator listed no tables at all
sys_columns and sys_tables were left out of the soft-delete conversion in
1786700003000. Their runtime models embed common.ModelTime, which is the
millisecond marker, so GORM queries them with deleted_at = 0 - against a
nullable datetime column holding NULL. Every row was invisible.

The repository carries two ModelTime types: the one under
cmd/migrate/migration/models still has a nullable gorm.DeletedAt and is
what builds the tables, while common/models has the marker and is what
queries them. Nothing connected the two, so a table could be built one
way and read the other with no signal at all.

The test now walks app/ for models embedding the marker and requires a
migration to cover each. tb_demo is exempt and says why: nothing reads it
at runtime.
2026-08-27 12:12:13 +08:00
zhangwenjian 2628ab8e3e fix🐛: a seeded menu overflowed its column and stopped the migration run
sort is gorm:"size:4", which MySQL builds as a tinyint holding -128..127.
The demo menu seeded Sort: 900, so on MySQL the run stopped at
1786700001000 with Error 1264, and every migration after it - including
the soft-delete conversion - never ran.

deleted_at therefore stayed NULL while the code queries deleted_at = 0,
and the login returned 'incorrect Username or Password' on a database
whose password hash was correct all along.

sqlite ignores the declared width, so a fresh install there passed and
the fault only appeared on MySQL.
2026-08-27 12:12:00 +08:00
wenjianzhang 1b7dcd843c Merge pull request #876 from go-admin-team/perf/data-permission
perf👌: the data-permission lookup ran on every request, including when it was switched off
2026-08-24 16:11:47 +08:00
zhangwenjian f0d91fb763 perf👌: read the data scope from the token instead of joining for it
The scope is decided by the user id, the role id, the department and the
data_scope string. Three of the four were already in the token; deptid
was not, though core's user.GetDeptId has always read that claim. Adding
it removes a sys_user join from every list, detail, update and delete.

This goes no more stale than rolekey does, which Casbin has read from
the token since the beginning: both settle on the next login.

A token minted before this still works. Its claims are incomplete, and
the lookup runs for it as before.
2026-08-24 15:36:11 +08:00
zhangwenjian 7238c6a26d perf👌: stop looking up a data scope that is switched off
Permission() returns the query untouched when EnableDP is false, so the
lookup feeding it has nothing to feed. The lookup ran anyway: a sys_user
join against sys_role on every list, detail, update and delete, with the
result discarded.

enabledp is false in settings.full.yml, so this was the default.
2026-08-24 15:35:33 +08:00
wenjianzhang 0964cf98e2 Merge pull request #875 from go-admin-team/fix/file-store-nil-client
fix🐛: the upload endpoint panicked on source=2, and cloud storage was never wired up
2026-08-24 15:00:31 +08:00
zhangwenjian 04c6a081ae fix🐛: source=3 uploaded to aliyun, and neither provider was ever configured
thirdUpload dispatched on the source parameter and then built the same
zero-value ALiYunOSS in both branches, so source=3 could not have
reached qiniu even with credentials.

Neither branch had credentials to use. OXS.Setup is the initialisation
path and nothing in the repository called it, and no configuration field
existed to fill. The store is now taken from extend.fileStore, and a
provider that was not configured says so rather than producing the
provider's own complaint about an empty bucket name.

The two handlers passed errors.New("") to e.Error, discarding what
actually went wrong; they now pass the error.
2026-08-24 13:25:54 +08:00
zhangwenjian fcbd9ae02e fix🐛: an unconfigured object store reports it instead of panicking
Each implementation keeps its provider client in an interface{} field that
Setup assigns, so an unconfigured store holds nil - and asserting nil to
the provider's client type panics:

  panic: interface conversion: interface {} is nil, not *oss.Client

The upload endpoint reaches that path for any request naming a provider
the deployment never configured.

Three more things were wrong in the same files. OXS.Setup printed a
failure and returned the store anyway, handing back exactly the broken
object that panics. HuaWeiOBS.UpLoad printed the provider's error and
returned nil, so a failed upload reported success. Both it and
QiNiuKODO.UpLoad asserted the local path was a string without checking.

The tests asked the reader to paste their own credentials, so they failed
for everyone who did not. They now cover the guards and skip the part
that needs a provider unless credentials are in the environment.
2026-08-24 13:23:07 +08:00
wenjianzhang d34d30a197 Merge pull request #874 from go-admin-team/ci/serialize-deploys
ci🔧: run one deploy at a time
2026-08-23 14:15:21 +08:00
zhangwenjian ecfea845c2 ci🔧: run one deploy at a time
Two merges seconds apart raced. Both runs do docker rm -f then docker
run; the second removed the container the first had just created, and
the first's docker run failed on the name conflict:

  Conflict. The container name "/go-admin-api" is already in use

The deploy went red and the demo stayed on the older image, which is the
worse half: a failure that leaves the wrong version running.

Grouping by ref serialises pushes to master while leaving pull request
runs independent, since those carry their own ref.
2026-08-23 14:11:49 +08:00
wenjianzhang e05ff7c809 Merge pull request #873 from go-admin-team/chore/drop-dockerfilebak
chore🔧: delete Dockerfilebak
2026-08-23 14:03:34 +08:00
wenjianzhang 28a9626661 Merge pull request #872 from go-admin-team/chore/skill-new-business-module
docs📝: add the new-business-module skill, and keep the rest of .claude out
2026-08-23 14:03:28 +08:00
zhangwenjian 96b2cb3acf chore🔧: delete Dockerfilebak
Added in 2022 and never touched since. Nothing references it - not the
workflows, not the Makefile, not a script - and it could not build
anyway: it copies config/settings.yml out of the builder, and that file
is gitignored.

It is a leftover from when the image was built inside the container,
before that was replaced by copying a binary built on the runner. Its
MAINTAINER line was the last one in the repository; Docker deprecated
the instruction in favour of LABEL maintainer years ago.
2026-08-23 13:43:40 +08:00
wenjianzhang 87fe6b7d9b Merge pull request #864 from go-admin-team/chore/core-v2
chore🔧: move to go-admin-core v2
2026-08-23 13:43:19 +08:00
zhangwenjian 722de8ea65 chore🔧: move the generator templates to v2 as well
The code generator writes Go files, and its templates still spelled the
old import paths, so a module generated after this migration did not
compile: the router it emits declares InitBusinessRouter with the v1
*GinJWTMiddleware while common.AuthInit now returns the v2 type.

Two of the paths moved rather than gaining a /v2 segment - the jwtauth
and response shims under sdk/pkg are gone in v2 - so this is not the
same rewrite the Go files got.
2026-08-23 13:28:17 +08:00
zhangwenjian 8ffde94433 chore🔧: move to go-admin-core v2
Every import of the module changes, not only the seven packages that
moved out of sdk/pkg: Go requires the major version in the path from v2
on. Both happen in one pass —

    go run github.com/go-admin-team/go-admin-core/tools/coreupgrade@v2.0.0 -w -v2 .
    go mod tidy

— which is the command the release notes give, run here as a consumer
would run it. 210 imports across 95 files.

The compatibility shims this used are gone in v2, so the paths that
moved had to move: sdk/pkg/captcha, sdk/pkg/jwtauth and its user
package, sdk/pkg/response and sdk/pkg/casbin.

The count of unformatted files is unchanged at 34, none of them touched
by this: the tool reformats a file only if it was already gofmt clean,
so a migration cannot disappear into whitespace.
2026-08-23 13:26:46 +08:00
wenjianzhang 08eef12bca Merge pull request #865 from go-admin-team/fix/codegen-inverted-guards
fix🐛: the code generator's guards were all written backwards
2026-08-23 13:24:50 +08:00
zhangwenjian ab0e8e6056 docs📝: add the new-business-module skill, and keep the rest of .claude out
The skill walks a single-table CRUD module end to end: migration, the
Actions-mode model, dto and router, and the sys_menu / sys_api /
casbin_rule seed data without which the module builds but never appears.

.claude was ignored wholesale. Un-ignoring the skills directory would
have committed every skill put there, including personal ones, so the
skills that ship are re-included one directory at a time.

AGENTS.md now points at 1786700001000_demo_menu.go for the seed data,
which is the runnable version of what the skill describes.
2026-08-23 13:20:26 +08:00
zhangwenjian 2cef52d906 chore🔧: record the modules the code imports as direct
go mod tidy moves glebarez/sqlite and gorm.io/plugin/soft_delete out of
the indirect block: the tests import the first and common/models the
second. CI runs tidy before building, so the tree was dirty from the
first command.
2026-08-23 13:19:15 +08:00
zhangwenjian 95077b116b fix🐛: the candidate table query assumed one database
The exclusion list was a subquery against `$GenConfig.DBName`.sys_tables,
so it named the schema by hand. Generating from a schema that is not the
one holding sys_tables made the whole query fail, and because the
subquery read the table directly it also counted soft-deleted entries:
deleting a generator entry never handed its table back.

Read the registrations through the model on this connection instead. An
empty list skips the clause - NOT IN (NULL) is unknown for every row,
which would leave a fresh install with nothing to generate from.
2026-08-23 13:19:15 +08:00
zhangwenjian d4cf11d313 fix🐛: report an unknown database driver instead of panicking
opens is a map, so opens[c.Driver] on a driver this build does not carry
returns a nil function, and gorm.Open calls it. The operator saw a nil
dereference inside gorm with nothing naming the driver.

sqlite3 is the case that bites: it needs cgo and is only compiled in
under the sqlite3 build tag, so the same config file works on one binary
and dies on another. Resolve the driver first and say which ones this
build supports.
2026-08-23 13:19:15 +08:00
zhangwenjian f201792d8f fix🐛: the mysql-only guard never fired
pkg.Assert panics when its condition is false, so pkg.Assert(true,
"目前只支持mysql数据库") is a no-op. On postgres or sqlserver the code
generator did not report that it needs MySQL: DBTables returned an empty
list with a nil error, and DBColumns ran its query on the zero-value
*gorm.DB left over from the branch that never assigned, which is a nil
dereference rather than a message.

Assert the driver up front instead of asserting a constant in an else,
which also removes the placeholder *gorm.DB the fall-through relied on.
DBColumns.GetPage had no guard at all and gets the same one.
2026-08-23 13:19:15 +08:00
zhangwenjian d16f5e7180 fix🐛: db columns endpoint rejected exactly the valid requests
pkg.Assert panics when its condition is false, so
Assert(TableName == "", "table name cannot be empty") rejected every
request that carried a table name and let the empty one through. The
model layer repeated the inversion with if TableName != "" { return
error }, so either one alone was enough to break the endpoint.

Flip both, and hoist the model guard out of the mysql branch so it
matches GetList ten lines below, which had it right all along.
2026-08-23 13:19:15 +08:00
wenjianzhang f8f697af2b Merge pull request #868 from go-admin-team/ci/stop-gitee-mirror
ci🔧: stop mirroring the repository
2026-08-23 13:18:19 +08:00
wenjianzhang eb8da38a46 Merge pull request #870 from go-admin-team/fix/demo-db-soft-delete
fix🐛: the soft-delete migration could not run, and the demo database never got it
2026-08-23 13:01:17 +08:00
zhangwenjian f19568c69a chore🔧: bring the bundled demo database up to the current migrations
go-admin-db.db ships in the repository and the Dockerfile copies it into
the image, which then runs only the server. Its last recorded migration
was from 2022, so every row still carried a null deleted_at while the
code queries deleted_at = 0. Nothing matched: not the login, not the
sixty-seven menus, not the five departments.

Anyone starting from the bundled sqlite database met the same wall, and
the failure reads as an incorrect username or password.
2026-08-23 12:57:05 +08:00
zhangwenjian 91bf25e5fe fix🐛: the soft-delete migration could not run against the real schema
Two assumptions held on the test's table and on nothing else.

It dropped deleted_at while an index still referred to it. MySQL and
PostgreSQL drop dependent indexes along with the column; SQLite refuses,
and the migration stopped at the first table with such an index - which
is all thirteen of them.

It also read the rows through a column named id. sys_dept keys on
dept_id, sys_user on user_id, and only some tables on id, so the pass
that carries the deletion timestamps across never ran.

The test's table had an id key and no index on deleted_at, which is
exactly the shape that lets both through. It now matches sys_user.
2026-08-23 12:56:50 +08:00
wenjianzhang 85666f160f Merge pull request #867 from go-admin-team/docs/readme-refresh
docs📝: repoint the README links that stopped resolving
2026-08-22 23:12:49 +08:00
zhangwenjian b2baf48dc6 ci🔧: stop mirroring the repository
Every push mirrored to Gitee and GitLab. Neither mirror is wanted any
more, so the workflow goes rather than half of it.

The GITEE_KEY and GITLAB_KEY secrets are left in place; restoring the
mirror is a revert of this commit.
2026-08-22 17:34:50 +08:00
zhangwenjian c906e1d503 docs📝: repoint the links that stopped resolving
The two tutorial links pointed at doc.zhangwj.com, which no longer
answers; the same paths serve from doc.go-admin.dev. golangroadmap.com
returns 503. The jwt-go credit pointed at dgrijalva/jwt-go, archived
years ago - this project builds on golang-jwt/jwt.

Also: the copyright years said 2022 and 2024, the English README asked
for a password in Chinese, and the Chinese README's link section lost
its only entry, so it gets the one the English side already had.
2026-08-22 15:26:44 +08:00
wenjianzhang 3b93ac19f8 Merge pull request #863 from go-admin-team/fix/soft-delete-groundwork
fix🐛: a unique constraint the database can actually keep
2026-08-22 11:59:12 +08:00
zhangwenjian 9914373d45 test🧪: run the assertion through the function it is about
Review caught that this reissued getByRoleName's query instead of
calling it, so it passed whether or not the production line still said
what it was supposed to — a test named for a change it did not touch.

It calls getByRoleName now, and restoring the hand-written clause fails
it for exactly the reason this PR exists: with the marker non-null,
"deleted_at is null" matches nothing and the query returns an empty
list.
2026-08-22 11:40:38 +08:00
zhangwenjian 4911730012 fix🐛: give the natural keys a constraint the database can keep
sys_user.username, sys_role.role_key and sys_dict_type.dict_type had no
unique index. Uniqueness was a SELECT COUNT followed by an INSERT, which
two concurrent requests both pass — and login resolves a username with
First, so which of the two accounts answers is whichever the database
returns.

The index cannot be on the key alone, because a soft-deleted row keeps
occupying the name and a deleted user's username could never be used
again. It has to include the delete marker, and the marker has to be
non-null: two live rows are (alice, NULL) and (alice, NULL), and NULL is
not equal to NULL, so an index over a nullable marker admits both. That
is the worst of the three states — a constraint that reads as protection
and binds nothing — and there is a test that demonstrates it rather than
asserting it.

ModelTime.DeletedAt is milliseconds since the epoch now, zero while the
row is live. Sixteen tables carry it; the migration converts each one,
preserving when each deleted row was deleted, then adds the three
indexes.

Written to be re-runnable rather than transactional, because DDL does not
roll back on MySQL and an operator whose first attempt failed halfway
should have nothing to do but run it again. It refuses before altering
anything if a table already holds duplicates, naming them, rather than
letting the index fail and leaving the operator to guess.

The timestamp conversion happens in Go: turning a timestamp into epoch
milliseconds is spelled differently by every dialect this supports, and
these row counts do not justify four versions of it.
2026-08-22 11:27:22 +08:00
zhangwenjian 88bab51056 fix🐛: stop hand-writing the soft-delete condition, and check the count
Two things in front of the unique-index work, both safe on their own.

getSysMenuByRoleName carried "deleted_at is null" in its where clause.
GORM adds that condition itself for a model with a DeletedAt field, so
it was a duplicate — and one phrased as a column being null, which stops
being true the moment the column stops being nullable. A schema that
moves to a non-null delete marker would have turned this query into one
that matches nothing, silently, for admin users only.

SysDictType.Insert dropped the error from its duplicate check: a query
that failed left the count at zero and the insert went ahead as though
the name were free.

The test pins what the removed clause was there for. Its counter-proof
is Unscoped rather than deleting the field — taking ModelTime off the
model fails to compile, which proves nothing.
2026-08-22 11:11:03 +08:00
wenjianzhang 0fd4f68b6c Merge pull request #861 from go-admin-team/docs/fix-stale-queue-redis-sample
fix: correct the commented-out queue.redis sample in settings.yml
2026-08-20 11:01:03 +08:00
zhangwenjian c66cb5c6a8 fix: correct the commented-out queue.redis sample in settings.yml
The sample had producer/consumer nested keys (streamMaxLength,
approximateMaxLength, visibilityTimeout, bufferSize, concurrency,
blockingTimeout, reclaimInterval) that don't exist on config.RedisQueue —
checked against sdk/config/queue.go, which only reads addr, password, and the
embedded RedisOptions fields, plus group, key_prefix and max_attempts. Filling
in the old sample as written would compile and start fine, since it's YAML
under a key the struct doesn't declare, and every one of those settings would
be silently ignored.

Replaced with the fields the struct actually has. Still commented out —
redis stays opt-in, this only fixes what filling it in would produce.
2026-08-20 10:54:53 +08:00
wenjianzhang b16ec0af77 Merge pull request #860 from go-admin-team/chore/upgrade-core
chore🔧: upgrade go-admin-core and route the queue through configuration
2026-08-18 22:48:00 +08:00
zhangwenjian 82ea8539eb chore🔧: upgrade go-admin-core and route the queue through configuration
The pinned core dated from April, before sdk stopped being a separate module,
so the build resolved sdk packages from the old module and core packages from
the new one. Dropping the separate requirement is what makes the two agree
again.

Most of the diff is renames that came with that: the tenant accessors gained a
ByTenant suffix, GetDb now returns one database and GetAllDb the map, and
casbin moved to v3.

The change that matters is four call sites moving from GetMemoryQueue to
GetQueuePrefix. GetMemoryQueue returns a queue fixed at construction, so the
login log, the operate log and the api check ran in process no matter what the
settings file selected — a second instance saw none of it. GetQueuePrefix
returns whatever the configuration built, which is the point of being able to
configure a queue at all.

Verified against core at main: build and vet clean. The two file_store failures
are unchanged from before this branch; they need cloud credentials.
2026-08-18 22:14:08 +08:00
wenjianzhang d17d5c1206 Merge pull request #859 from go-admin-team/docs/clarify-demo-sites
docs📝: 标注 antd 演示站对应 go-admin-pro
2026-08-16 19:31:25 +08:00
zhangwenjian 041d22d0d2 docs📝: 标注 antd 演示站对应 go-admin-pro
README 中两个演示地址并排列出、格式与账号密码完全相同,看不出 antd 站对应
的是另一个产品。用户在该站遇到问题时会认为是本仓库的缺陷(见 #857:登录
返回的错误码在本仓库中并不存在)。

仅在链接文字中补充产品名,不改变呈现方式。
2026-08-16 12:04:26 +08:00
wenjianzhang 5864058a81 Merge pull request #858 from go-admin-team/chore/bump-version-2.4.0
chore🔧: 版本号升至 2.4.0
2026-08-16 11:17:51 +08:00
zhangwenjian 45035a16e4 chore🔧: 版本号升至 2.4.0 2026-08-16 11:14:28 +08:00
wenjianzhang f4d0108d49 Merge pull request #855 from go-admin-team/fix/remove-refresh-token-endpoint
fix🐛: 移除 refresh_token 接口,修复 token 可无限续期问题
2026-08-16 11:08:41 +08:00
zhangwenjian b81611ba72 chore🔧: 清理 refresh_token 的残留权限数据
接口移除后,库中仍留有三类记录:sys_api 的接口登记、sys_menu_api_rule 的
菜单绑定、casbin_rule 的策略。留着会让「接口管理」列出一个不存在的端点,
角色配置里也仍可勾选。

- 新装:从 db.sql 与 db-sqlserver.sql 的种子数据中删除该接口
- 已有部署:新增迁移清理,按 path 匹配而非固定 id,因为执行过
  `server -a` 重新注册接口的库中 id 会与官方种子数据不同
2026-08-14 21:42:59 +08:00
zhangwenjian bb34108831 fix🐛: 移除 refresh_token 接口,修复 token 可无限续期问题
close #820

GET /api/v1/refresh_token 用业务 token 即可换取新 token,而续期上限
MaxRefresh 依据的 orig_iat 在每次续期时被一并重置,上限永远无法到达 ——
token 一旦泄露即等同于永久访问权,且无任何吊销手段。

该路由此前还位于 CasbinExclude 中,不受 Casbin 约束,任何角色的已登录用户
都可调用。

官方前端从未使用它:store 中虽有 refreshToken action,但全仓库无一处
dispatch,属死代码。移除不影响正常登录与鉴权流程。

破坏性变更:自行调用该端点实现续期的使用者需改为重新登录。正确的无感续期
应在 go-admin-core 中区分 access token 与 refresh token 后重新实现,不应
沿用此路由。
2026-08-14 21:42:52 +08:00
wenjianzhang b7fd92f39b Merge pull request #854 from go-admin-team/docs/agents-and-demo-module
feat✨: 新增 app/demo 参照模块与 AGENTS.md 规范文档
2026-08-14 21:37:57 +08:00
zhangwenjian 63b800a3ba docs📝: 补充 sqlite3 构建标签与迁移目录说明
driver 配置为 sqlite3 时不带 -tags sqlite3 会在 nil 函数上 panic,
报错不提及构建标签,容易误判为环境损坏;同时说明 version/ 与
version-local/ 的区别,后者已被 gitignore,提交到本仓库的迁移必须放 version/。
2026-08-14 21:17:37 +08:00
zhangwenjian ed9450a2d5 feat✨: 补充 demo 模块的菜单与权限种子数据
一个业务模块要在界面上可用,需要四类数据协同:

  sys_api           后端路由登记,Casbin 据此判定
  sys_menu          侧边栏菜单,含目录 M、菜单 C、按钮 F 三级
  sys_menu_api_rule 菜单与接口的关联,角色保存时据此生成策略
  casbin_rule       实际生效的权限策略

菜单的 menu_name 与前端组件 name 保持一致(DemoProduct),按钮的
permission 与前端 v-permisaction 标识一致(demo:product:add 等)。

策略写入 casbin_rule 而非 sys_casbin_rule:后者对应的 models.CasbinRule
是历史遗留,其 7 列 size:512 唯一索引在 MySQL 下会超出索引长度限制,实际
生效的是 adapter 创建的 casbin_rule 表。

所有写入均为存在则更新、不存在则插入,迁移可安全地在已有数据的库上执行。
实测:在含 67 条菜单、121 条接口的库上执行后各表数据正确;清除版本记录重
跑一次,各表行数不变,确认幂等。
2026-08-14 16:57:55 +08:00
zhangwenjian 1d551a10ab docs📝: 新增 AGENTS.md 与架构说明
AGENTS.md 是给 AI 编码工具与新贡献者的约定,只记录「不遵守就会出错」的
规则,技术栈版本与命令交由 go.mod 和 Makefile 表达,避免文档与代码脱节。
标准写法指向 app/demo/——那是可编译、有测试的参照物,文档与它冲突时以它
为准。

docs/architecture.md 承载不易从代码直接读出的语义:DataScope 五档的过滤
方式、定时任务的 JobExec 接口、多数据源约束、迁移目录的分工。

内容整理自此前未纳入版本控制的 CLAUDE.md,撰写时逐条对照代码核实,修正
了其中两处失效描述(构建工具已非 Vue CLI;JobExec 的方法是 Exec(interface{})
而非 Run(string))。CLAUDE.md 现改为指向 AGENTS.md 的软链,两者不再各自
漂移。
2026-08-14 16:49:48 +08:00
zhangwenjian 4d7c9e5a12 feat✨: 补充 demo 模块的建表迁移
放在 version/ 而非 version-local/:后者已被 .gitignore 忽略,是留给使用
者存放自身迁移脚本的位置,示例迁移需随框架一起分发。文件注释中说明了这
一区分。
2026-08-14 16:46:53 +08:00
zhangwenjian d1f5fe5681 feat✨: 新增 app/demo 标准 CRUD 参照模块
作为编码约定的可执行参照物:文档会滞后,而这个模块过时会导致构建或测试
失败,因此以它为准。

目录骨架与自动注册文件由项目自带的脚手架生成:

  go run main.go app -n demo

它同时产出 cmd/api/demo.go,其中的 init() 将路由追加进 AppRouters,
无需在任何中心文件手工登记。

模块本身演示了单表 CRUD 的推荐写法——直接使用 common/actions 提供的五个
通用 Action,因此只有 model、dto、router 三个业务文件,没有 apis 与
service。手写 Handler 的场景仅在业务超出单表 CRUD 时才需要。

DTO 中详情/删除入参内嵌 dto.ObjectById 以复用其 Bind 与 GetId,不重复
实现 uri 绑定与批量 ids 合并逻辑。

补充 8 项测试锁定通用 Action 的接口约束,其中最关键的是 Generate() 必须
返回副本——Action 在并发请求间复用实例,就地返回会串数据。反向验证:将
Generate 改为就地返回,测试立即失败。
2026-08-14 16:46:09 +08:00
zhangwenjian e8c2e0a966 chore🔧: 修正 .DS_Store 忽略规则
原规则 `*/.DS_Store` 只匹配子目录一层,仓库根目录下的 .DS_Store 不在其
中。改为 `.DS_Store`,匹配任意层级。
2026-08-14 16:45:55 +08:00
wenjianzhang cef0a19a9c Merge pull request #853 from go-admin-team/fix/community-pr-batch
fix🐛: 处理社区 PR 中仍然成立的四项修复
2026-08-14 15:46:43 +08:00
zhangwenjian c0e81363dc docs📝: 修正 Makefile 注释错别字
「实际决对路径」→「实际绝对路径」。

问题由 PR #847 指出。
2026-08-14 15:35:55 +08:00
zhangwenjian df2e4a2b48 fix🐛: 修正欢迎页 iframe 高度塌陷
页面通过 JS 计算并设置 iframe 高度,但 html 与 body 未声明高度,
百分比高度失去参照,iframe 在部分场景下塌陷为 0。

补充 html,body{height:100%} 与 iframe 的 height:100%,并为原先缺失的
overflow-y 声明补上分号。

问题由 PR #829 指出。
2026-08-14 15:35:55 +08:00
zhangwenjian 9088ebc2e1 refactor🎨: 修正文件名拼写 int_router.go → init_router.go
该文件内容为 init() 函数中的路由注册,原文件名少了一个字母。

问题由 PR #787 指出。
2026-08-14 15:35:55 +08:00
zhangwenjian 9f2dec3036 fix🐛: 修正 GeneralDelDto.GetIds 重复追加 Id
该方法先在开头追加了 Id,随后 else 分支中又追加一次:仅传 Id 时返回
[5 5],删除接口会对同一条记录执行两次 DELETE。

  if g.Id != 0 { ids = append(ids, g.Id) }
  if len(g.Ids) > 0 { ... } else {
      if g.Id > 0 { ids = append(ids, g.Id) }   // 重复
  }

去掉冗余分支,同时将首个判断由 != 0 收紧为 > 0,与 Ids 中逐个元素的
过滤条件保持一致(负数 Id 无意义)。

补充单元测试,覆盖仅 Id、仅 Ids、二者并存、含非正数、全空回退等场景。

问题由 PR #848 指出。
2026-08-14 15:35:55 +08:00
wenjianzhang ea049f9b06 Merge pull request #852 from go-admin-team/fix/ci-deploy-guard
fix🐛: 限制部署步骤仅在 master 收到 push 时执行
2026-08-12 15:41:26 +08:00
zhangwenjian 1f1349a685 docs📝: 更新在线体验地址
Element UI vue2 演示站已升级为 Element Plus + Vue 3,域名同步更换为
vue.go-admin.pro。

Arco Design vue3 演示站(vue3.go-admin.dev)已下线,移除对应条目。
2026-08-12 12:27:41 +08:00
zhangwenjian dcef2df38e fix🐛: 限制部署步骤仅在 master 收到 push 时执行
本工作流同时由 push 与 pull_request 触发,而推送镜像与重启服务两步没有
任何事件限制。其后果是:任何指向 master 的 PR 一经创建,就会把 PR 分支
构建出的镜像推送到镜像仓库,并 docker rm -f 掉线上容器、用该镜像重新启
动 API 服务——发生在代码被审查和合并之前。

同仓库分支发起的 PR 可以取到 secrets,因此该路径实际可达;历史运行记录
中已多次出现由 pull_request 事件触发的成功部署。

为两步加上 event_name 与 ref 双重判断。额外判断 ref 是考虑到日后若有人
向 on.push.branches 追加分支,部署不会随之扩散。

Tidy 与 Build 不受影响,PR 仍会执行编译校验。
2026-08-12 12:27:33 +08:00
zhangwenjian 92834d6e39 publish🚀: 版本号更新至 2.3.0 2026-08-12 00:22:31 +08:00
zhangwenjian f06540883b fix🐛: 修复 Docker 镜像发布的 tag 条件失效问题
if 表达式中不应使用 ${{ }} 包裹:startsWith(${{github.ref}}, 'refs/tags/')
会先将 github.ref 替换为裸字符串再参与表达式求值,导致条件判断失效,
使得每次 push 到 master 都会构建并推送镜像至 ghcr.io,而非仅在打 tag 时发布。

同时 on.push 缺少 tags 配置,打 tag 实际不会触发该工作流。

修正后:push 分支仅执行 Go 构建,打 tag 才发布镜像。
2026-08-11 11:09:39 +08:00
zhangwenjian 3c9ce5b6b0 chore🔧: 升级 x/image 修复 TIFF 解码漏洞 2026-08-10 22:17:28 +08:00
zhangwenjian ff8a59550a fix🐛: 修复镜像同步因浅克隆被拒绝的问题 2026-08-10 21:21:01 +08:00
zhangwenjian 7cddef33a2 git🙈: 将 go.sum 纳入版本控制 2026-08-10 20:51:00 +08:00
zhangwenjian 7013c2fa4a chore🔧: 移除依赖已封禁 action 的 issue 自动化流程 2026-08-10 20:51:00 +08:00
zhangwenjian 65bacacb38 docs📝: 更新 README 环境要求版本说明 2026-08-10 20:45:39 +08:00
zhangwenjian 45587028c3 config🔧: CI 升级 Go 版本并更新 Actions 至最新 2026-08-10 20:45:39 +08:00
zhangwenjian 887c9cca4b chore🔧: 升级 Go 至 1.26.5 并同步升级依赖 2026-08-10 20:45:36 +08:00
wenjianzhang a6ddb113fc Update LICENSE.md 2026-08-08 13:55:08 +08:00
wenjianzhang b83eef8670 Fix image source in README.md
Updated image source in README.md for go-admin.
2026-05-22 11:20:39 +08:00
zhangwenjian 43dcd61c51 config🔧: update go-version to 1.24 in build workflow
go.mod requires go 1.24, go mod tidy fails when runner uses 1.18.
2026-05-15 17:52:12 +08:00
zhangwenjian 1bd64d4562 config🔧: pin all GitHub Actions to full-length commit SHAs
Replace version tags (@v1/@v2/@v3/@master) with pinned commit SHAs
across all workflow files to satisfy go-admin-team organization
security policy requiring immutable action references.
2026-05-15 17:48:41 +08:00
zhangwenjian 44e81bc72f git🙈: 补充忽略本地开发配置文件
- 新增忽略 config/settings.local.dev.yml
2026-05-15 17:37:42 +08:00
zhangwenjian 3312f8b7b9 chore🔧: 升级依赖 mergo 模块路径
- 替换 github.com/imdario/mergo 为上游迁移后的 dario.cat/mergo v1.0.1
2026-05-15 17:37:42 +08:00
zhangwenjian d6a2272f9d git🙈: 完善 .gitignore 忽略规则
- 新增忽略编译产物 go-admin-server
- 新增忽略本地工具配置目录
2026-05-15 17:37:42 +08:00
wenjianzhang a5cc0a9e29 Add read and write timeout to HTTP server 2025-09-10 09:39:54 +08:00
wenjianzhang 3f995735e9 Merge pull request #834 from hosea3000/edit-no-confirm
点击编辑的时候不需要弹框确认,交互不太友好
2025-05-20 11:41:02 +08:00
wenjianzhang b65b74dee5 Merge pull request #832 from hosea3000/fix-number-input
fix🐛: 修复自动生成代码时选择字段类型为int64, 前端提交还是string 导致报错的问题
2025-05-20 11:40:21 +08:00
Hosea 98cf3ad95a fix🐛: 点击编辑的时候不需要弹框确认,交互不友好 2025-05-20 10:57:36 +08:00
Hosea 8649d8d791 fix🐛: 修复自动生成代码时选择字段类型为int64, 前端提交还是string 导致报错的问题 2025-05-13 15:48:45 +08:00
wenjianzhang 817e34c6aa refactor🎨: 重构文件上传逻辑,拆分处理函数以提高可读性和维护性 2025-04-13 22:20:06 +08:00
wenjianzhang 952cd92648 refactor🎨: 清理 sys_server_monitor.go 文件,移除未使用的导入并格式化代码 2025-04-13 22:17:17 +08:00
wenjianzhang 6b1e961a7f refactor🎨: 重构系统监控代码,拆分功能为多个函数以提高可读性和维护性 2025-04-13 22:15:10 +08:00
wenjianzhang 762eba5af7 refactor🎨: 重构 Setup 函数,拆分为多个子函数以提高可读性和维护性 2025-04-13 22:04:12 +08:00
wenjianzhang e82128f679 refactor🎨: 优化获取客户端 IP 的逻辑,增加对 X-Forwarded-For 和 X-Real-IP 的处理 2025-04-13 22:00:04 +08:00
wenjianzhang 8f8a197db1 delete🎉: 移除示例代码 run.go 2025-04-08 20:49:36 +08:00
wenjianzhang 364854eda0 docs📝: 更新 go-admin 版本号至 2.2.0 2025-04-08 20:49:29 +08:00
wenjianzhang b259e91f4d Merge remote-tracking branch 'origin/master'
# Conflicts:
#	go.mod
2025-04-08 20:45:25 +08:00
wenjianzhang 76411f80bc refactor🎨: 优化日志记录方式,统一使用 log.Info 替代 log.Println 2025-04-08 20:30:35 +08:00
wenjianzhang 5494353229 fix🐛: 修复获取本地主机IP的函数调用错误 2025-04-08 20:30:24 +08:00
wenjianzhang afe5efbe36 refactor🎨: remove unused distributed lock setup code in initialize.go 2025-04-08 20:30:05 +08:00
wenjianzhang db422785fc fix🐛: include captcha answer in GenerateCaptchaHandler for improved logging 2025-04-08 20:29:38 +08:00
wenjianzhang 4ac68323da fix: improve error logging in jobbase.go for better clarity 2025-04-08 20:23:23 +08:00
wenjianzhang 44002fcb11 chore: update dependencies in go.mod to latest versions 2025-04-08 20:22:59 +08:00
wenjianzhang 5bbd919745 chore: update dependencies in go.mod to latest versions 2025-03-25 17:16:40 +08:00
wenjianzhang 54dd3de5b6 chore: update dependencies in go.mod to latest versions 2025-03-25 16:48:47 +08:00
wenjianzhang 9540fdfc30 refactor: remove unused GetMenuIDS function and clean up code 2025-03-25 16:44:31 +08:00
wenjianzhang 937775e2a7 chore: update Go version from 1.21 to 1.24 in build configuration 2025-03-25 08:53:39 +08:00
wenjianzhang 84721265dd fix: simplify error handling in GenerateCaptchaHandler 2025-03-24 22:41:02 +08:00
wenjianzhang 3ab67dfa7d chore: update Go version from 1.21 to 1.24 2025-03-24 20:53:09 +08:00
wenjianzhang 6a1941a820 Merge pull request #814 from keemozhang/master
fix🐛: declaration of new local variable causes transactions to be ign…
2025-03-21 15:36:16 +08:00
wenjianzhang 3ae7c44585 Merge pull request #816 from Tiper-In-Github/patch-1
Fix:err is never used
2025-03-21 15:35:23 +08:00
wenjianzhang 9d809f6392 Merge pull request #821 from pigwantacat/master
fix:修复定时任务的日志打印
2024-12-18 00:11:54 +08:00
pigwantacat 4b477b3103 fix:修复定时任务的日志打印 2024-11-01 14:14:30 +08:00
wenjianzhang e7ae2fe019 更新 go_admin.go 2024-10-30 22:12:17 +08:00
wenjianzhang d5ba3d9770 更新 READMEN.md 2024-10-30 22:10:06 +08:00
Akiraka f3d744f6f5 修复获取getinfo时候,userName 事件结果为 nickName 问题 2024-10-24 09:30:15 +08:00
无别 0315631b53 Fix:err is never used
Fix the problem that err is overwritten and becomes invalid
2024-09-29 15:32:36 +08:00
wenjianzhang 48e7ce88ff perf👌: rollback base64Captcha 2024-09-09 15:46:05 +08:00
wenjianzhang 357db6b1c9 Merge remote-tracking branch 'origin/master' 2024-09-08 22:04:20 +08:00
wenjianzhang 83e0531f43 perf👌: format 2024-09-08 22:04:08 +08:00
wenjianzhang 898ba7d8eb Update README.Zh-cn.md 2024-09-06 23:11:48 +08:00
wenjianzhang 8751f34539 perf👌: correct attribute definition 2024-09-05 18:33:11 +08:00
wenjianzhang 4aa0068d2d perf👌: update SysDept Get First to FirstOrInit 2024-09-05 18:29:50 +08:00
keemozhang b954a2f092 fix🐛: declaration of new local variable causes transactions to be ignored 2024-09-05 15:46:20 +08:00
wenjianzhang 9227bd2be1 perf👌: format code 2024-09-04 20:25:02 +08:00
wenjianzhang e70a0b1314 perf👌: update SysConfig Get First to FirstOrInit 2024-09-04 20:22:49 +08:00
wenjianzhang 21c262a31e perf👌: update build file 2024-09-03 22:17:11 +08:00
wenjianzhang f30889bd19 perf👌: update SysApi Get Func First to FirstOrInit 2024-09-03 21:22:09 +08:00
wenjianzhang 23e519999e perf👌: update go mod 2024-08-30 16:00:29 +08:00
wenjianzhang bedf064ace Merge pull request #802 from zhanluxianshen/drop-base-model
replace basemodel by common.model
2024-08-29 16:26:22 +08:00
wenjianzhang 9a8e0cddde Merge pull request #803 from zhanluxianshen/clean-err-use-in-method
clean err define in methods.
2024-08-29 16:23:54 +08:00
wenjianzhang c0c16036d3 Merge pull request #811 from wangle201210/fix/logger
fix🐛: reset default logger fields
2024-08-29 16:17:18 +08:00
wanna dd905a2bed fix🐛: reset default logger fields 2024-08-23 16:49:21 +08:00
zhanluxianshen 2d76430f89 clean err define in methods.
Signed-off-by: zhanluxianshen <zhanluxianshen@163.com>
2024-07-10 15:03:33 +08:00
zhanluxianshen 5dde1d2a00 replace basemodel by common.model
Signed-off-by: zhanluxianshen <zhanluxianshen@163.com>
2024-07-10 11:26:52 +08:00
lwnmengjing 93f25c6cdf Add mss-boot-io link 2023-11-07 23:28:52 +08:00
wenjianzhang d366df372d feat✨: Log file size control and retention days control 2023-11-03 18:59:20 +08:00
wenjianzhang 7281d05efc fix🐛: Fixed system startup Network output problem 2023-11-03 17:42:01 +08:00
wenjianzhang e6d6a65267 Merge remote-tracking branch 'origin/master' 2023-11-03 17:36:21 +08:00
wenjianzhang 9ff094b6f5 fix🐛: Fixed data migration issue during multi-tenant configuration 2023-11-03 17:36:04 +08:00
wenjianzhang fc9c253a9f tag📌: Upgrade go1.21 2023-11-03 17:35:01 +08:00
wenjianzhang 9d735ed5aa docs📝: Update README.md 2023-11-02 17:42:40 +08:00
wenjianzhang d782b00117 tag📌: Change version 2023-11-02 17:10:52 +08:00
wenjianzhang 239159dd2a fix🐛: Fix the problem that el-popconfirm does not take effect 2023-11-02 17:08:58 +08:00
wenjianzhang 0c1e91c3b5 Add files via upload 2023-10-11 21:25:01 -05:00
wenjianzhang c09347b387 Merge pull request #768 from majiayu000/fix-pgerror
[BugFix] 修复一个``引发的bug
2023-10-11 21:18:42 -05:00
lif e49e47c7a1 Delete go.mod 2023-09-22 14:02:38 +08:00
wenjianzhang 98b46535aa Merge pull request #767 from zgxme/fix-gen-0909
[fix](gen) ignore default time type columns in table
2023-09-21 22:00:57 +08:00
lif 014a23aac3 [BugFix] Fix pgsql error with 2023-09-14 16:35:41 +08:00
zgxme f1dfba79e0 [fix](gen) ignore default time type columns in table 2023-09-09 22:59:45 +08:00
wenjianzhang a282e44b1d Merge pull request #753 from Vingurzhou/master
-installsuffix 参数没有指定后缀字符串。它被设定为空,这可能导致一些问题
2023-08-02 09:24:48 +08:00
wenjianzhang d1279e67fb Merge pull request #757 from NipGeihou/master
fix: 修复go generate命令不更新Swagger文档问题
2023-08-02 09:22:25 +08:00
wenjianzhang 37a5963cd6 perf👌: Optimize go warnings 2023-08-01 22:38:41 +08:00
wenjianzhang 69df1b3d34 perf👌: Remove unused attributes 2023-08-01 22:12:18 +08:00
wenjianzhang eae97f7a15 perf👌: update version 2023-08-01 22:08:47 +08:00
wenjianzhang ce0b5ff7bf perf👌: update version 2023-08-01 22:08:43 +08:00
NipGeihou 73118e49b9 fix: 修复go generate命令不更新Swagger文档问题
修复go generate不更新Swagger文档问题,并更新生成后文档文件
2023-06-20 00:37:59 +08:00
Vingurzhou 7b43982595 Update Makefile
fix(makefile): -installsuffix 参数没有指定后缀字符串。它被设定为空,这可能导致一些问题
2023-06-10 15:57:18 +08:00
wenjianzhang 31cd1ee768 Merge pull request #741 from wwhai/patch-2
fix: change 'os.Signal' channel to buffered
2023-05-14 11:04:04 +08:00
wenjianzhang 8df7551946 Merge pull request #740 from llussy/patch
fix setting.yml spelling
2023-05-14 11:03:47 +08:00
wenjianzhang 79c1295a70 Merge pull request #749 from sincatter/master_fix_pg_migrate
处理postgres迁移时insert提示类型不匹配问题
2023-05-14 11:03:07 +08:00
wenjianzhang 26d9a2e9e4 Merge pull request #747 from go-admin-team/dependabot/go_modules/golang.org/x/net-0.7.0
build(deps): bump golang.org/x/net from 0.0.0-20220722155237-a158d28d115b to 0.7.0
2023-05-13 15:38:46 +08:00
wenjianzhang b09b7b6ccc Merge pull request #729 from go-admin-team/dependabot/go_modules/github.com/prometheus/client_golang-1.11.1
build(deps): bump github.com/prometheus/client_golang from 1.11.0 to 1.11.1
2023-05-13 15:38:13 +08:00
dependabot[bot] ef6fdaa221 build(deps): bump golang.org/x/net
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.0.0-20220722155237-a158d28d115b to 0.7.0.
- [Commits](https://github.com/golang/net/commits/v0.7.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-13 07:38:07 +00:00
wenjianzhang 23c80f0217 Merge pull request #735 from go-admin-team/dependabot/go_modules/golang.org/x/text-0.3.8
build(deps): bump golang.org/x/text from 0.3.7 to 0.3.8
2023-05-13 15:37:14 +08:00
wenjianzhang 95dc699e2e Merge pull request #746 from haimait/fix_edit_master_role模块添加注释
fix_edit_master_role模块添加注释
2023-05-13 15:36:29 +08:00
wenjianzhang 74b7d62c75 处理postgres迁移时insert提示类型不匹配问题 2023-05-13 00:00:35 +08:00
wanghaima 68accd5448 fix_edit_master_role模块添加注释 2023-05-07 19:33:00 +08:00
wenjianzhang 3edbef8696 Merge pull request #745 from haimait/fix_edit_master_优化api筛选
优化API管理筛选
2023-05-07 19:22:23 +08:00
wanghaima 5527f6386a 优化API管理筛选 2023-05-07 18:47:36 +08:00
wwhai c48f70a7c6 fix: change 'os.Signal' channel to buffered 2023-05-04 23:25:43 +08:00
llussy a078e31664 fix setting.yml 2023-04-26 15:59:19 +08:00
wenjianzhang 04d2d7dde1 format🥚: Exclude empty permission identification 2023-04-19 18:50:35 +08:00
Akiraka b846053bea 恢复 common/middleware/demo.go 2023-04-14 19:51:48 +08:00
Akiraka a1a5634c4e 恢复修改 2023-04-14 19:51:22 +08:00
Akiraka 6036c6e4e3 接受参数位置错误 2023-04-14 19:07:01 +08:00
wenjianzhang 7d74e6f325 Merge pull request #732 from wenyoufu/master
【bug】修复普通用户只用查询权限时,无法修改个人信息(昵称、用户密码)的bug
2023-03-14 01:14:43 +08:00
dependabot[bot] 1bf9f74bdf build(deps): bump golang.org/x/text from 0.3.7 to 0.3.8
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.3.7 to 0.3.8.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.3.7...v0.3.8)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-23 00:08:28 +00:00
ford f61de5beeb 【bug】修复普通用户只用查询权限时,无法修改个人信息(昵称、用户密码)的bug 2023-02-17 19:24:50 +08:00
dependabot[bot] 79fb2d0bee build(deps): bump github.com/prometheus/client_golang
Bumps [github.com/prometheus/client_golang](https://github.com/prometheus/client_golang) from 1.11.0 to 1.11.1.
- [Release notes](https://github.com/prometheus/client_golang/releases)
- [Changelog](https://github.com/prometheus/client_golang/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prometheus/client_golang/compare/v1.11.0...v1.11.1)

---
updated-dependencies:
- dependency-name: github.com/prometheus/client_golang
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-15 01:38:52 +00:00
wenjianzhang c973d6819c docs📝: update readme 2022-12-13 11:47:04 +08:00
wenjianzhang 3d8b879e64 docs📝: update readme 2022-12-13 11:45:28 +08:00
wenjianzhang ac971bda4b fix🐛: 忽略pkg包 2022-12-08 18:00:33 +08:00
wenjianzhang 44f62abbca fix🐛: 添加引用 2022-11-16 16:47:32 +08:00
wenjianzhang 7d7d8484d4 fix🐛: demo中间件添加环境判断 2022-11-16 12:05:33 +08:00
zhangwenjian c8b27492eb fix🐛: update sqlite3 configuration 2022-11-09 17:36:04 +08:00
zhangwenjian 783f79dcb6 Merge remote-tracking branch 'origin/master' 2022-11-09 17:35:31 +08:00
zhangwenjian ddd97d5a9e fix🐛: Adjust the demo environment configuration 2022-11-09 17:35:16 +08:00
wenjianzhang fa73c3d6b1 patch🚑: update restart 2022-11-03 14:55:02 +08:00
wenjianzhang 5b2f3e9316 Merge pull request #720 from ruishawn/dev
Docs: update README
2022-11-03 14:03:35 +08:00
zhangwenjian 42f3025217 fix🐛: Fix the problem that api saving fails when creating a new menu 2022-11-03 14:00:48 +08:00
wenjianzhang 5df43b4d11 docs📝: update readme 2022-11-02 10:18:32 +08:00
wenjianzhang eac1bf197e docs📝: update readme 2022-11-01 19:16:01 +08:00
wenjianzhang 5c834939af docs📝: update readme 2022-11-01 19:13:37 +08:00
zhangwenjian 642e86951b Merge branch 'master' of github.com:go-admin-team/go-admin 2022-11-01 16:58:11 +08:00
zhangwenjian bc42412e92 perf👌: 更新logo 2022-11-01 16:57:28 +08:00
wenjianzhang d9122d29cb docs📝: update readme 2022-11-01 16:54:19 +08:00
wenjianzhang b532ad994c docs📝: update readme 2022-11-01 16:53:42 +08:00
zhangwenjian b62fbc803c perf👌: 更新演示环境数据库名称 2022-11-01 15:02:36 +08:00
zhangwenjian ed8bac8a1b perf👌: 更新ci脚本 2022-11-01 15:00:41 +08:00
zhangwenjian d56142463a perf👌: 添加演示环境配置项 2022-11-01 14:58:18 +08:00
zhangwenjian f795a356e7 perf👌: 更新CI脚本中的分支 2022-11-01 14:14:27 +08:00
zhangwenjian a359c25e36 perf👌: 添加CI脚本 2022-11-01 14:13:53 +08:00
xiaobo 0ef422d309 fix: update README
Update README file: update dependencies before build.
2022-10-27 16:12:50 +08:00
wenjianzhang e0519a4d7e docs📝: update antd view url 2022-10-26 23:38:18 +08:00
wenjianzhang 5043ce5411 docs📝: update antd view url 2022-10-26 23:37:16 +08:00
wenjianzhang cc0cdc7d0e Merge pull request #710 from zyd/master
fix🐛:e.Log.Errorf("db error:%s", err)输出的err没有被赋值
2022-10-08 15:00:33 +08:00
zhaodongdong c004b3d333 fix🐛:e.Log.Errorf("db error:%s", err)输出的err没有被赋值 2022-09-14 17:42:09 +08:00
wenjianzhang 453dd65cb1 docs📝: update readme zh 2022-09-14 12:24:02 +08:00
wenjianzhang b55cbe1992 docs📝: Update readme 2022-09-14 12:23:06 +08:00
wenjianzhang b6e1b7b210 Merge pull request #708 from zyd/master
fix🐛:模板Update方法,err没有被赋值,返回的err永远是nil
2022-09-12 11:50:41 +08:00
zhaoyidong 3685510d25 fix🐛:模板Update方法,err没有被赋值,返回的err永远是nil 2022-09-07 20:08:17 +08:00
wenjianzhang d7e685536c Merge pull request #707 from zyd/master
fix🐛:排序参数必须用string接收
2022-09-07 09:53:24 +08:00
zhaoyidong 4df859a0ea fix🐛:排序参数必须用string接收
优化了代码生成的格式,最后的空行无法删除,删除之后}前面会增加空格
2022-09-06 14:10:27 +08:00
wenjianzhang 7d1b84e837 Merge pull request #706 from haimait/master-test
1. 修复日志创建时间筛选报错的bug.
2022-09-05 19:58:06 +08:00
wenjianzhang be1f0be9b2 Merge pull request #703 from quanbisen/master
修复优雅重启不生效
2022-09-05 19:56:46 +08:00
wanghaima 0f742900f5 1. 修复日志创建时间筛选报错的bug.
2. 修复日志里操作人,修改人,userAgent为空的bug.
3. 迁移表时,日志表添加字段注释.
4. sys_opera_log表oper_param字段类型改为text,解决字段长度报错的问题
2022-09-04 10:02:26 +08:00
quanbisen e6f4fac859 修复优雅重启不生效 2022-08-31 18:14:33 +08:00
wenjianzhang d39faa1aca docs📝: update readme zh 2022-08-25 14:25:07 +08:00
wenjianzhang c3fe13d9dd docs📝: Update readme 2022-08-25 14:24:05 +08:00
wenjianzhang 90db381b5a fix🐛: 修复侧边栏菜单排序问题 (690) 2022-08-25 14:18:02 +08:00
wenjianzhang 508137da4b docs📝: update README.md 2022-08-25 13:56:14 +08:00
wenjianzhang 695ac7b29b docs📝: Update README.Zh-cn.md 2022-08-25 13:55:11 +08:00
wenjianzhang c06df13a75 docs📝: update readme zh 2022-08-25 13:44:59 +08:00
wenjianzhang e663de3697 docs📝: update readme 2022-08-25 13:44:24 +08:00
wenjianzhang 10b4f03ff5 Merge pull request #701 from NaturalGao/natural
feat ✨:update swag && add swag commond ssh
2022-08-25 13:42:42 +08:00
wenjianzhang c7a4434a0e docs📝: update readme 2022-08-25 13:40:24 +08:00
NaturalGao 1f8babd9e7 fix: fix sys_router && add swag commond 2022-08-25 01:19:55 +08:00
NaturalGao 8e8fe906fd perf: update swag 2022-08-25 01:00:57 +08:00
wenjianzhang 386d08a03f feat✨: update issue-labeled.yml 2022-08-24 16:27:19 +08:00
wenjianzhang af38e1694b feat✨: pr_cn.md 2022-08-24 11:26:01 +08:00
wenjianzhang 5609e004cc feat✨: PULL_REQUEST_TEMPLATE.md 2022-08-24 11:24:53 +08:00
wenjianzhang 5be468308a feat✨: update issue-labeled.yml 2022-08-23 11:55:03 +08:00
wenjianzhang 39702abfba feat✨: add issue-labeled.yml 2022-08-23 11:48:35 +08:00
wenjianzhang a97d86e801 feat✨: add issue-check-inactive.yml 2022-08-23 11:40:29 +08:00
wenjianzhang 75582539fe feat✨: add issue-close-require.yml 2022-08-23 11:39:19 +08:00
wenjianzhang 466723c55e Merge pull request #606 from npmmirror/master
Update https://registry.npm.taobao.org to https://registry.npmmirror.com
2022-08-23 11:30:20 +08:00
wenjianzhang 6b3b2125df docs📝: update README 2022-08-22 15:52:19 +08:00
wenjianzhang 8c8d268708 docs📝 update README 2022-08-22 15:51:33 +08:00
wenjianzhang 73ac7273a0 Merge pull request #695 from zyd/master
fix🐛:去除模板中的多余空格
2022-08-22 15:23:17 +08:00
wenjianzhang dcafcdc6ce Merge pull request #694 from infnan/master
处理postgre启动报错问题
2022-08-22 15:22:49 +08:00
zhaoyidong 5b1405391e fix🐛:去除模板中的多余空格 2022-08-18 18:36:50 +08:00
infnan 0993173b1f 处理postgre启动报错问题
Signed-off-by: infnan <38274826+infnan@users.noreply.github.com>
2022-08-18 16:50:54 +08:00
wenjianzhang 483ec2bf3e Create config.yml 2022-08-18 13:02:42 +08:00
wenjianzhang 60fe272ba0 refactor🎨: catch exception return error message
捕获runtime.Error异常,否则接口报错不返回任何信息
2022-08-18 10:14:12 +08:00
zhaoyidong 8df2e8190e 捕获runtime.Error异常,否则接口报错不返回任何信息
报错细节不应该隐藏,方便debug。500错误应该由前端统一处理,返回用户可读信息。
2022-08-18 10:02:00 +08:00
zhangwenjian 66c8eb5ee8 fix🐛: Fix create when creating a new create_by Problem with by value of 0 (#688) 2022-08-18 07:26:56 +08:00
zhangwenjian bb65e76219 fix🐛: Repair role creation prompt empty slice found (#687) 2022-08-18 07:19:24 +08:00
zhangwenjian a585e29073 Merge remote-tracking branch 'origin/master' 2022-08-18 06:57:20 +08:00
zhangwenjian 7655d0fd38 fix🐛: Repair document address (#692) 2022-08-18 06:57:02 +08:00
wenjianzhang 5bec640f20 fix🐛: Merge pull request #689 from zyd/master
修复模板get update delete错误
2022-08-16 11:58:33 +08:00
zhaoyidong 62d9084ee8 修复模板get update delete错误 2022-08-16 11:41:28 +08:00
wenjianzhang df8ab39aa0 config🔧: Merge pull request #685 from zyd/master
删除模板中间件重复初始化代码
2022-08-15 11:15:22 +08:00
wenjianzhang a7d3666811 config🔧: Merge pull request #686 from haimait/master_dev
编写dockerfile启动脚本
2022-08-15 11:15:07 +08:00
wanghaima ea9e3d2fe1 编写dockerfile启动脚本
编辑shell启动脚本
2022-08-14 23:32:58 +08:00
zhaoyidong f14085f3ee Merge pull request #1 from zyd/zyd-patch-1
删除模板中间件重复初始化代码
2022-08-13 17:39:14 +08:00
zhaoyidong e8b9db1df5 删除模板中间件重复初始化代码
go-admin app -n 创建目录,重复初始化会导致获取不到body中的参数
2022-08-13 17:37:55 +08:00
wenjianzhang dc625997c4 docs📝: Update README.Zh-cn.md 2022-08-10 01:00:34 +08:00
wenjianzhang 4f458591e8 docs📝: Update README.md 2022-08-10 00:47:42 +08:00
zhangwenjian 7a074d93cd config🔧: Modify the system default logo URL 2022-08-10 00:18:15 +08:00
wenjianzhang 9d1e1f6482 docs📝: Update README.Zh-cn.md 2022-08-09 23:24:35 +08:00
wenjianzhang 19153170bb docs📝: Update README.md 2022-08-09 23:23:18 +08:00
wenjianzhang 6bf774c463 fix🐛: fix rolemenu
fix🐛: fix rolemenu
2022-08-09 23:14:56 +08:00
wenjianzhang 0de5ba77aa docs📝: Update README.Zh-cn.md 2022-08-09 21:22:27 +08:00
wenjianzhang f4c0134d9c docs📝: Update Readme.md 2022-08-09 21:20:49 +08:00
wenjianzhang 2c5c1b69b4 docs📝: update readme 2022-08-09 20:46:37 +08:00
zhangwenjian d34a33b691 perf👌: update sqlite3 file 2022-08-09 18:21:40 +08:00
zhangwenjian 869394c898 perf👌: Remove caspin table from data migration 2022-08-09 18:21:00 +08:00
zhangwenjian b97bde11b2 perf👌: upgrade gorm,casbin,gin,uuid version 2022-08-09 18:19:02 +08:00
zhangwenjian 852cfa66e8 perf👌: remove casbin sys_ 2022-08-09 18:17:42 +08:00
zhangwenjian 289fbba8e0 perf👌: update casbin gorm adapter 2022-08-09 18:17:06 +08:00
zhangwenjian a6ffac657e fix🐛: Add MySQL judgment in data migration 2022-08-09 15:20:45 +08:00
zhangzhenlun 096663ac91 fix🐛: fix rolemenu 2022-08-09 14:26:43 +08:00
zhangwenjian d40a0c0837 fix🐛: fix github.com/alibaba/sentinel-golang middleware(#679) 2022-08-09 13:00:32 +08:00
zhangwenjian f94b437852 fix🐛: fix github.com/alibaba/sentinel-golang middleware 2022-08-09 12:59:31 +08:00
wenjianzhang 7e571b038f fix🐛: fix rolemenu 2022-08-09 10:18:21 +08:00
zhangwenjian 56968c0bd2 Merge remote-tracking branch 'origin/master' 2022-08-08 18:03:04 +08:00
zhangwenjian ef6b85faec config🔧: Modify the instruction createapp to app 2022-08-08 18:02:50 +08:00
zhangwenjian 0d47fb4e68 Merge branch 'master' of github.com:go-admin-team/go-admin 2022-08-08 16:28:34 +08:00
zhangwenjian 8bfee8af16 refactor🎨: 添加菜单paths默认数据 2022-08-08 16:28:26 +08:00
wenjianzhang 0fc7276ccd refactor🎨: set DB CHARSET utf8mb4 2022-08-08 11:39:11 +08:00
Vingurzhou 9a596397ca Update 1599190683659_tables.go 2022-08-08 11:28:55 +08:00
zhangwenjian 1bea64bb6d config🔧: set DB CHARSET utf8mb4(#674) 2022-08-08 10:16:43 +08:00
zhangwenjian 09bfdc3d39 config🔧: set DB CHARSET utf8mb4 2022-08-08 10:15:29 +08:00
wenjianzhang fe8b39691b patch🚑: go1.18 2022-08-08 10:00:24 +08:00
wenjianzhang 1465bfdf15 Merge branch 'master' into dev1.18 2022-08-08 09:59:57 +08:00
zhangwenjian bccbd67450 config🔧: update README 2022-08-08 09:42:31 +08:00
zhangwenjian 50a3b39666 config🔧: Modify the client IP acquisition method 2022-08-08 09:26:14 +08:00
zhangwenjian 087ba38c24 config🔧: update README.md 2022-08-08 09:22:36 +08:00
zhangwenjian 8a3c50ea1a config🔧: 修改actions配置文件 2022-08-07 21:52:02 +08:00
zhangwenjian 86187e4c79 fix🐛: 修复获取菜单接口menurole,数据不完整 (#676) 2022-08-07 21:49:24 +08:00
zhangwenjian 98c495abb1 refactor🎨: update readme 2022-08-07 20:43:34 +08:00
zhangwenjian c53c4fd9f8 refactor🎨: update readme 2022-08-07 20:42:24 +08:00
zhangwenjian b231705a67 Merge remote-tracking branch 'origin/master' 2022-08-04 17:25:17 +08:00
zhangwenjian 86f94a2cb9 refactor🎨: errors 添加go mod 2022-08-04 17:24:53 +08:00
zhangwenjian ef41e07550 docs📝: 添加开发环境要求 2022-08-04 17:24:07 +08:00
zhangwenjian 255c72d3f1 refactor🎨: update version 2022-07-29 18:51:55 +08:00
zhangwenjian 260eedfcc6 refactor🎨: 移除失效文档链接 2022-07-29 18:50:46 +08:00
zhangwenjian f43cd117e3 refactor🎨: 角色创建和更新后重新load policy策略 2022-07-29 18:47:12 +08:00
zhangwenjian 83b219458f fix🐛: 菜单中paths未设置问题修复 2022-07-29 18:44:22 +08:00
zhangwenjian 0f1b9369df fix🐛: 自定义错误中间件bug修复 2022-07-29 18:43:38 +08:00
zhangwenjian b31e1c0d58 feat✨: 升级go1.18 2022-07-27 22:27:38 +08:00
zhangwenjian 0122024789 feat✨: 修改版本号 2022-07-27 21:55:59 +08:00
zhangwenjian f469536174 fix🐛: 添加bcrypt包的引用 2022-07-27 21:49:24 +08:00
wenjianzhang 70bd8b26ad Merge pull request #673 from go-admin-team/dev
Dev
2022-07-27 21:36:11 +08:00
zhangwenjian dabc4d88b3 Merge remote-tracking branch 'origin/master' 2022-07-27 21:34:07 +08:00
wenjianzhang 214f90b366 Merge pull request #661 from wxxiong6/patch-1
fix UpdatePwd error
2022-07-27 21:20:07 +08:00
wenjianzhang 3c4cc054df Merge pull request #671 from Silicon-He/fix-readme-cgo-url
Fix readme cgo url
2022-07-27 21:19:29 +08:00
wenjianzhang 4d329287ce Merge pull request #664 from zhouxixi-dev/dev
bugfix: https://github.com/go-admin-team/go-admin/issues/539
2022-07-27 21:17:43 +08:00
siliconhe 866714d75e update doc url of cgo-issue 2022-07-17 21:14:26 +08:00
lwnmengjing b268d03e30 💚 update workflow 2022-07-12 11:54:24 +08:00
lwnmengjing 953d3b4135 🐛 fix: delete pkg error package 2022-07-12 10:55:05 +08:00
zhouxixi-dev 0d6b347d7e bugfix: https://github.com/go-admin-team/go-admin/issues/539 修复角色新增、修改时,sys_casbin_rule表drop,然后重新create的问题 2022-06-23 15:47:55 +08:00
wxxiong6 a19622f6ac fix UpdatePwd error
fix UpdatePwd error
2022-06-13 23:36:12 +08:00
zhangwenjian 45c8737601 refactor🎨: 引入github.com/pkg/errors 2022-06-05 11:12:19 +08:00
wenjianzhang 4925383f5e Merge pull request #593 from ziux/ziux
fix bug
2022-06-05 11:08:09 +08:00
wenjianzhang 62ab985050 Merge pull request #552 from wkf928592/wkf928592-patch-1
fix: arm32位系统环境下使用migrate迁移功能时,版本号作为整型处理会出现内存溢出的问题
2022-06-05 10:36:27 +08:00
wenjianzhang 50f14f7658 Merge branch 'dev' into wkf928592-patch-1 2022-06-05 10:36:20 +08:00
wenjianzhang 1cd31079d7 Merge pull request #634 from defool/bugfix/throw_error_on_migrate
Throw error if migrate failed
2022-06-05 10:33:08 +08:00
wenjianzhang 46b62a9809 Merge pull request #655 from stephenzhang0713/dev
Fix: Unable to load config file to Docker container
2022-06-05 10:31:54 +08:00
Han Zhang 8f70a1dca4 fix🐛: Fix Dockerfile to load config file
fix🐛: Fix Dockerfile to load config file
2022-06-03 20:38:54 +08:00
zhangwenjian 937b62e641 添加errors包 2022-05-29 12:58:53 +08:00
wenjianzhang 3873342f6c Merge pull request #650 from go-admin-team/dev
refactor🎨: 修复问题
2022-05-28 00:40:06 +08:00
zhangwenjian 717903a2b6 fix🐛: 修复关闭中的job能够启动问题(#638) 2022-05-28 00:34:08 +08:00
zhangwenjian 88030e301a patch🚑: 更新版本信息 2022-05-28 00:17:35 +08:00
zhangwenjian cd0792e3d2 refactor🎨: 更新readme(#623) 2022-05-28 00:14:12 +08:00
zhangwenjian 6ed2fcbf6c fix🐛: 添加roleKey验证(#649) 2022-05-27 22:47:57 +08:00
kaiyuan eb33515e29 throw error if migrate failed 2022-04-08 10:32:07 +08:00
wenjianzhang bf93b86bd0 Merge pull request #629 from go-admin-team/dev
docs📝: update readme
2022-04-01 14:14:01 +08:00
wenjianzhang c41672c21a docs📝: update readme 2022-03-31 15:08:49 +08:00
wenjianzhang 8716b073df Merge pull request #628 from go-admin-team/dev
docs📝:  update readme
2022-03-31 14:13:26 +08:00
wenjianzhang 638bab3c9d docs📝: update readme 2022-03-31 14:01:15 +08:00
wenjianzhang c5d7a8c740 fix🐛: Fix password reset
fix🐛: Fix password reset
2022-03-15 11:33:21 +08:00
wenjianzhang b030be8f80 fix🐛: Fix password reset 2022-03-12 13:00:19 +08:00
wenjianzhang 1fe19d1c3b patch🚑: dev merge
patch🚑:  dev merge
2022-03-05 11:54:10 +08:00
wenjianzhang 1508e850fe Merge branch 'master' into dev 2022-03-05 11:52:44 +08:00
zhangwenjian 81bc15d77c config🔧: go-admin version info 2022-03-05 11:49:56 +08:00
zhangwenjian 24adca55e4 feat✨: added file update sdk;kodo、obs 2022-03-05 11:44:23 +08:00
wenjianzhang 9c8974a26e fix🐛: 修复前端设置数据权限不生效问题
fix🐛: 修复前端设置数据权限不生效问题
2022-03-05 11:23:41 +08:00
wenjianzhang 01e8984b79 fix🐛: Fix readme 404 link.
fix🐛:  Fix readme 404 link.
2022-03-05 11:13:08 +08:00
wenjianzhang 7f1aa89539 fix🐛: Fix the newline problem in time package in code generation
Fix gen code problem
2022-03-05 11:11:34 +08:00
zhangwenjian 4876fc0aa1 fix🐛: Fix password reset caused by modifying user information 2022-03-05 11:00:52 +08:00
zhangwenjian f998d20a86 feat✨: added obs,kodo 2022-02-21 18:07:37 +08:00
zhangwenjian cdb5faf043 refactor🎨: upgrade OXS interface 2022-02-21 18:06:11 +08:00
zhangwenjian dfaa2ff51e test✅: added oss test 2022-02-21 18:04:46 +08:00
zhangwenjian 8754ff8147 refactor🎨: upgrade oss 2022-02-21 18:04:18 +08:00
zhangwenjian cca84c3c21 docs📝: update License Copyright 2022-02-21 17:56:12 +08:00
wenjianzhang 72391f0201 Merge pull request #598 from go-admin-team/dev
fix🐛: fix monitor macos env error (#605)
2022-02-13 00:54:52 +08:00
zhangwenjian 39e26d738c docs📝: update version 2.0.9 2022-02-13 00:31:46 +08:00
zhangwenjian f114424079 fix🐛: fix monitor macos env error 2022-02-13 00:23:20 +08:00
NPM Mirror Bot 98b60f0564 update https://registry.npm.taobao.org to https://registry.npmmirror.com 2022-02-12 05:56:42 +00:00
wenjianzhang d02b52f383 feat✨: 添加sqlserver支持 2022-02-08 18:41:09 +08:00
horizonzy b52da434bb fix code gen problem. 2022-01-31 13:00:21 +08:00
horizonzy 3cfa7a2767 fix code gen problem. 2022-01-31 12:00:26 +08:00
horizonzy 054199d1e4 fix 404 link. 2022-01-30 17:19:50 +08:00
zhangwenjian 02b62a288d refactor🎨: 删除历史的sqlite文件 2022-01-22 23:05:38 +08:00
zhangwenjian 24908a8732 refactor🎨: 添加error判断返回 2022-01-22 23:03:01 +08:00
wenjianzhang 26ee7b7985 refactor🎨: 清空sqlite数据库文件 2022-01-22 21:49:42 +08:00
wenjianzhang b76db48112 refactor🎨: 修正针对sqlite3的事务问题 2022-01-22 21:49:11 +08:00
wenjianzhang e2c5075319 v2.0.8
1、修改sqplite的支持
2、修正已知问题
2022-01-22 20:03:21 +08:00
wenjianzhang e9f36e74ca refactor🎨: 修改版本号 2022-01-22 19:44:36 +08:00
wenjianzhang 0b73bd7b25 refactor🎨: 修改sqplite的支持 2022-01-22 19:37:56 +08:00
yangyu ccccab3104 fix bug 2022-01-12 17:10:52 +08:00
wenjianzhang ae8e32d806 Update README.Zh-cn.md 2022-01-10 13:18:59 +08:00
wenjianzhang fd2709affa Update README.md 2022-01-10 13:18:23 +08:00
wenjianzhang 34b3395d15 Update README.md 2022-01-10 13:17:28 +08:00
inits abdc80b756 修复前端设置数据权限不生效问题 2022-01-10 10:21:10 +08:00
lwnmengjing 492ac31973 Merge pull request #580 from go-admin-team/dev
push docker
2021-12-08 11:09:01 +08:00
linwenxiang 3ac1878c3c perf ⚡ performance docker build 2021-12-07 23:37:33 +08:00
linwenxiang 0cc27355f7 fix 🐛 push to gihub 2021-12-07 23:24:19 +08:00
linwenxiang 562f761807 feat ✨ add dev to ci 2021-12-07 22:47:44 +08:00
linwenxiang 88e4b37c03 feat ✨ push docker to github 2021-12-07 22:44:39 +08:00
wenjianzhang b73d88d6cf Merge pull request #564 from go-admin-team/dev
merge: 修正数据初始化的部分问题
2021-10-22 12:15:05 +08:00
wenjianzhang 443c30d48c Update 1599190683659_tables.go 2021-10-22 12:05:39 +08:00
wenjianzhang 64cbf31184 Update db.sql 2021-10-22 12:04:48 +08:00
wkf928592 ce9d9bd3ec fix:在32位系统中做迁移时,版本号作为整型处理会造成内存溢出的问题
修改版本号作为字符串处理
2021-09-10 10:19:33 +08:00
linwenxiang 57330784ac feat ✨ mirror to gitlab 2021-09-07 21:45:25 +08:00
lwnmengjing 85e1c6fe54 Merge branch 'dev' 2021-09-07 11:21:33 +08:00
lwnmengjing 7ca776bfab 💚 修复流水线CI bug 2021-09-07 11:20:55 +08:00
linwenxiang 082c369d41 feat ✨ 同步代码到gitee 2021-09-06 21:51:07 +08:00
lwnmengjing 0ac9f41e1a Merge pull request #549 from go-admin-team/dev
fix 🐛 gcc强依赖问题修复
2021-09-02 20:38:36 +08:00
linwenxiang 16701d38a6 feat ✨ 增加release pipeline 2021-09-02 20:31:00 +08:00
linwenxiang 30eb280698 fix 🐛 gcc强依赖问题修复 2021-09-02 20:21:18 +08:00
wenjianzhang 974a8096ca Merge pull request #546 from go-admin-team/dev
Dev
2021-08-21 14:20:26 +08:00
wenjianzhang bb83a97613 refactor🎨: 修改post接口文档 2021-08-20 18:28:04 +08:00
wenjianzhang 8baae5e712 fix🐛: 修复jwt密钥引用错误问题(#545) 2021-08-20 18:27:29 +08:00
wenjianzhang 49e4c19cbb Merge pull request #544 from go-admin-team/dev
Dev
2021-08-19 19:36:42 +08:00
wenjianzhang 6f67628012 Merge branch 'dev' of github.com:go-admin-team/go-admin into dev 2021-08-19 19:28:04 +08:00
wenjianzhang 8a1573cc14 docs📝: 更新2.0.6 2021-08-19 19:27:55 +08:00
wenjianzhang 03b916ef8a Merge pull request #543 from go-admin-team/dev
Dev
2021-08-19 19:26:31 +08:00
wenjianzhang 9d25648c1f Merge pull request #540 from ninstein/patch-8
BUGFIX:角色状态修改异常修复
2021-08-19 19:13:16 +08:00
wenjianzhang aa6c3df892 Merge pull request #542 from go-admin-team/dev
Dev
2021-08-19 19:12:32 +08:00
wenjianzhang bdaa6e0db0 refactor🎨: 升级包go-admin-core v1.3.7和go-admin-core/sdk v1.3.7至v1.3.8 2021-08-19 19:10:32 +08:00
wenjianzhang 4740a39808 refactor🎨: 删除移除功能的数据初始化 2021-08-19 19:08:47 +08:00
wenjianzhang 386c620b48 refactor🎨: 优化角色修改时循环AddNamedPolicy 2021-08-19 19:04:03 +08:00
wenjianzhang 2441412714 fix🐛: 修复参数验证信息 2021-08-19 19:03:19 +08:00
ninstein 9db940150a BUGFIX:角色状态修改异常修复
切换角色状态时参数传递丢失,导致切换异常新增了一条空记录
2021-08-18 14:45:22 +08:00
wenjianzhang 8c5639af53 Merge pull request #535 from go-admin-team/dev
Dev
2021-08-13 21:17:00 +08:00
wenjianzhang b4a6f82f5f Merge pull request #534 from appleboy/patch
chore: upgrade gin to v1.7.3
2021-08-13 21:15:58 +08:00
Bo-Yi Wu 7dd62a4cf8 chore: upgrade gin to v1.7.3
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2021-08-13 20:53:37 +08:00
wenjianzhang 095ed7c2fd Merge pull request #529 from go-admin-team/dev
Dev
2021-08-10 16:39:54 +08:00
zhangwenjian 76567eea84 docs📝: 更新2.0.5 2021-08-10 14:58:55 +08:00
zhangwenjian 5a65fcd477 fix🐛: 修复菜单树 2021-08-10 14:58:04 +08:00
wenjianzhang 27b0e1a07a Merge pull request #528 from go-admin-team/dev
Dev
2021-08-10 03:55:34 +08:00
zhangwenjian 3e20e93797 fix🐛: 修复菜单编辑未赋权接口列表 2021-08-10 03:47:31 +08:00
zhangwenjian 5d3b1c3d0f docs📝: 更新2.0.4 2021-08-10 03:37:02 +08:00
zhangwenjian b5a57e6dd9 refactor🎨: 优化生成功能的修改和删除询问提示 2021-08-10 03:36:20 +08:00
zhangwenjian 2decf43b4c fix🐛: 统一生成后的路由 2021-08-10 03:35:36 +08:00
wenjianzhang 7dd3e2b27e Merge pull request #525 from go-admin-team/dev
Dev
2021-08-06 10:49:41 +08:00
zhangwenjian 325c91989c refactor🎨: api自动添加不设置默认类型 2021-08-06 10:35:09 +08:00
wenjianzhang 96250bafb1 Merge pull request #521 from qliang/master
完善:接口检查新增记录-根据接口注释补充接口名称信息
2021-08-06 10:28:07 +08:00
wenjianzhang fff795ce5a Merge pull request #524 from go-admin-team/dev
fix🐛: 修复代码生成字典的问题 (#523  #517)
2021-08-06 10:27:32 +08:00
zhangwenjian 9887250407 docs📝: 更新2.0.3 2021-08-06 10:03:44 +08:00
zhangwenjian e42191c6af fix🐛: 修复代码生成字典的问题 (#523 #517) 2021-08-06 10:00:17 +08:00
lq adce44dc1f 完善:接口检查新增记录-根据接口注释补充接口名称信息 2021-08-03 17:24:58 +08:00
wenjianzhang a70ee44466 Merge pull request #511 from go-admin-team/dev
patch🚑:  merge dev
2021-07-28 10:00:12 +08:00
zhangwenjian fd0fa49f1c docs📝: 更新2.0.2 2021-07-28 09:06:23 +08:00
zhangwenjian 10491f9745 fix🐛: 修复删除部门的问题 (#510) 2021-07-28 08:53:18 +08:00
zhangwenjian 981313c0e2 fix🐛: 修复创建用户时的问题 ( #506) 2021-07-28 08:45:39 +08:00
zhangwenjian 6b88c9a004 fix🐛: 更新接口文档注释 (#507) 2021-07-27 19:16:47 +08:00
wenjianzhang 25395b5006 Merge pull request #504 from go-admin-team/dev
1. 修复菜单的目录(#500)
1. 调整字段判断逻辑
2021-07-23 00:43:34 +08:00
zhangwenjian 2f516b49cf refactor🎨: 调整字段判断逻辑 2021-07-23 00:33:39 +08:00
zhangwenjian 41ff26edc8 fix🐛: 修复菜单的目录(#500) 2021-07-23 00:33:00 +08:00
wenjianzhang a1c6f586cf Merge pull request #503 from go-admin-team/dev
fix🐛: 修复createapp时的问题(#493)
2021-07-22 23:11:56 +08:00
zhangwenjian 8b01126e0f fix🐛: 修复createapp时的问题(#493) 2021-07-22 23:03:44 +08:00
wenjianzhang e59d40af21 Merge pull request #495 from go-admin-team/dev
Dev
2021-07-22 22:22:20 +08:00
wenjianzhang 6b476bfab7 Update go.mod 2021-07-18 22:29:34 +08:00
wenjianzhang 12429d4585 Merge pull request #489 from Cassuis/dev
fix:修复createapp未初始化导致无法创建app以及修改资本资料导致密码重复加密问题
2021-07-16 20:52:40 +08:00
Vincent 6fe2edbe89 fix:修复修改基本资料导致密码重复加密问题 2021-07-15 11:13:37 +08:00
Vincent cee6bd6abd fix:修复createapp未初始化导致无法创建app的问题 2021-07-15 10:21:26 +08:00
zhangwenjian 4ac3350920 refactor🎨: 部分函数名称优化 2021-07-15 00:53:43 +08:00
zhangwenjian a45113258c refactor🎨: update request mode name 2021-07-15 00:43:06 +08:00
zhangwenjian 4a2659573b docs📝: 用户接口文档 2021-07-14 22:36:03 +08:00
zhangwenjian c74080664f refactor🎨: update version 2021-07-14 22:24:26 +08:00
wenjianzhang 84e06395a5 Merge pull request #487 from go-admin-team/dev
Dev
2021-07-14 16:24:46 +08:00
zhangwenjian 411b85afcd publish🚀: 2.0.0 2021-07-14 11:49:54 +08:00
zhangwenjian 57d128144d feat✨: Add the createapp command 2021-07-14 11:48:40 +08:00
wenjianzhang a7fa7e079b Merge pull request #486 from go-admin-team/dev
Dev
2021-07-14 11:40:05 +08:00
zhangwenjian 2781e413dc refactor🎨: 修改版本号 2021-07-14 11:16:27 +08:00
zhangwenjian 41d8daac97 fix🐛: 修改用户其它信息导致密码被置空,数据权限 #484 2021-07-14 11:13:26 +08:00
zhangwenjian dd22d55ee7 refactor🎨: request name cancel 2021-07-14 09:14:44 +08:00
zhangwenjian 32a1bd2511 refactor🎨: 升级gin和gorm版本 2021-07-05 00:31:31 +08:00
zhangwenjian 1130d20f14 refactor🎨: dto》request 2021-07-05 00:03:38 +08:00
wenjianzhang 90b17e995a Merge pull request #478 from go-admin-team/dev
Dev
2021-07-04 23:33:55 +08:00
zhangwenjian 1c41b0ec72 refactor🎨: 操作log dto模型名称修改 2021-07-04 23:26:43 +08:00
zhangwenjian 3f90605589 refactor🎨: 操作log添加字符限制 2021-07-04 23:13:14 +08:00
zhangwenjian c1347fbb5d refactor🎨: 升级依赖关系 2021-07-04 23:12:21 +08:00
zhangwenjian 0d1cb2ee33 docs📝: 升级qq群至2000人 2021-07-04 23:11:58 +08:00
zhangwenjian b6be297a1e refactor🎨: 添加默认demo代码生成表 2021-07-04 13:43:32 +08:00
zhangwenjian b9b3cbee93 refactor🎨: 调整登陆日志和api和操作日志模块 2021-07-04 13:43:11 +08:00
zhangwenjian 37d318b4d9 feat✨: vue-cli@3 升级为 vue-cli@4、Change Node Sass to Dart Sass、代码生成工具
1. vue-cli@3 升级为 vue-cli@4
2. Change Node Sass to Dart Sass
3. 代码生成工具
2021-07-04 05:46:20 +08:00
wenjianzhang 5368cfbcb8 Merge pull request #475 from G-Akiraka/patch-4
增加磁盘列表主机名称与当前时间
2021-07-02 22:26:09 +08:00
wenjianzhang 72a4ba077c Merge pull request #472 from G-Akiraka/patch-1
Update settings.yml
2021-07-02 22:25:53 +08:00
wenjianzhang fba03625d0 Merge pull request #473 from G-Akiraka/patch-2
翻译错误,管理员管理应该是用户管理
2021-07-02 22:24:25 +08:00
G-Akiraka 007807e776 增加磁盘列表主机名称与当前时间
上一个pr提交作废
2021-07-02 10:06:48 +08:00
G-Akiraka f2ae95d932 翻译错误,管理员管理应该是用户管理 2021-07-02 09:09:20 +08:00
G-Akiraka 25d7323ed1 Update settings.yml 2021-07-02 09:05:25 +08:00
wenjianzhang f7e737534d Merge pull request #471 from go-admin-team/dev
Dev
2021-07-01 23:13:03 +08:00
zhangwenjian 760c6b2814 refactor🎨: 修改版本号 2021-07-01 22:25:43 +08:00
zhangwenjian d0f49ef8c7 refactor🎨: 修改错误信息提示(#165) 2021-07-01 22:24:32 +08:00
wenjianzhang 1295b1fd35 Merge pull request #469 from go-admin-team/dev
DEV (#468)
2021-06-30 22:48:45 +08:00
zhangwenjian eb8062d19b refactor🎨: 生成逻辑调整 2021-06-30 22:36:26 +08:00
zhangwenjian d82129d364 refactor🎨: 代码生成模版升级 2021-06-30 22:35:49 +08:00
zhangwenjian 16923017b2 refactor🎨: 配置文件默认使用memory cache 2021-06-30 22:35:29 +08:00
zhangwenjian f4396e7e83 fix🐛: 用户修改头像接口入参模型分离(#468) 2021-06-30 18:55:16 +08:00
wenjianzhang acee466fc8 Merge pull request #467 from go-admin-team/dev
Dev(#457)
2021-06-30 02:04:10 +08:00
zhangwenjian 862f24d8a7 refactor🎨: 移除服务管理 2021-06-30 01:52:47 +08:00
wenjianzhang e2cb033670 refactor🎨: 增加server manager,提升服务启动流程规范
feature ✨ 增加server manager,提升服务启动流程规范
2021-06-29 16:58:50 +08:00
zhangwenjian 029c505501 refactor🎨: 修改包引用 2021-06-29 16:46:00 +08:00
zhangwenjian dd5f0c52fb refactor🎨: 修改错误信息提示 2021-06-29 16:33:03 +08:00
zhangwenjian f80e64688e refactor🎨: 修改请求参数命名 2021-06-29 16:32:44 +08:00
zhangwenjian 3fd34db3c1 docs📝: 修改接口文档 2021-06-29 16:30:47 +08:00
zhangwenjian 0607d462d0 docs📝: 修改config接口文档 2021-06-29 16:28:08 +08:00
zhangwenjian 7f8c302405 refactor🎨: 调整index to go-admin 接口 2021-06-29 16:27:10 +08:00
zhangwenjian c82c58443c refactor🎨: 验证码文档修改,去掉token验证 2021-06-29 16:26:27 +08:00
zhangwenjian 9591be883f refactor🎨:登陆模块接口文档整理 2021-06-25 11:34:26 +08:00
zhangwenjian acdcd0c867 refactor🎨:接口文档重新生成 2021-06-25 11:33:55 +08:00
zhangwenjian 0f623521c4 refactor🎨:代码生成功能迁移 2021-06-25 11:33:41 +08:00
wenjianzhang 91b93a3f48 refactor🎨:模版升级 2021-06-24 20:21:40 +08:00
wenjianzhang 32d123eb89 refactor🎨:格式化函数名称 2021-06-24 20:18:20 +08:00
wenjianzhang 2025809d91 refactor🎨:修改Syspost模块功能 2021-06-24 20:17:58 +08:00
wenjianzhang d552875e8a Merge pull request #461 from go-admin-team/dev
Dev
2021-06-23 12:21:13 +08:00
wenjianzhang 6994857f4b Merge pull request #460 from Cassuis/dev
bugfix:修正用户修改密码put接口url错误导致的无法修改密码问题,修正初始化SQL异常导致部分表无缺省参数问题
2021-06-23 12:08:37 +08:00
Vincent 7ac941c1d0 bugfix:
1.修正用户修改密码put接口url错误导致的无法修改密码问题
2.修正初始化SQL异常导致部分表无缺省参数问题
2021-06-23 09:46:51 +08:00
wenjianzhang af68778436 Merge pull request #455 from go-admin-team/dev
docs📝:  更新swagger文档
2021-06-20 00:59:39 +08:00
zhangwenjian 1ab11c46ba docs📝: 更新swagger文档 2021-06-20 00:51:55 +08:00
wenjianzhang add355637d Merge pull request #450 from go-admin-team/dev
merge Dev
2021-06-20 00:51:05 +08:00
zhangwenjian 65380695f2 refactor🎨:格式化函数名称 2021-06-20 00:43:17 +08:00
zhangwenjian a6116ede02 refactor🎨: 修改字典类型status为int 2021-06-20 00:39:43 +08:00
zhangwenjian dafa627e31 refactor🎨:升级依赖版本 2021-06-20 00:15:54 +08:00
zhangwenjian 993115c8ae fix🐛: 修复获取部门数据查询参数问题 2021-06-20 00:15:34 +08:00
zhangwenjian b97b3bc6d8 refactor🎨:部门创建添加事务,已经修改status字段为int类型 2021-06-20 00:14:45 +08:00
zhangwenjian 636294b6f5 refactor🎨: 岗位删除修改为data传值方式 2021-06-20 00:13:17 +08:00
zhangwenjian 37fe63126c fix🐛: 修复2.0 字典类型删除接口500并没有提示消息 (#452) 2021-06-18 22:24:10 +08:00
zhangwenjian 9ace1d8201 fix🐛: 修复2.0 字典数据删除404 (#451) 2021-06-18 22:23:37 +08:00
zhangwenjian 25472887c9 refactor🎨:移除内容管理、行政区管理和资源管理 2021-06-18 21:34:57 +08:00
zhangwenjian 5e7d2614b3 refactor🎨:修改版本号 2021-06-17 22:14:07 +08:00
zhangwenjian 484246e146 refactor🎨:更新数据初始化sql 2021-06-17 22:10:10 +08:00
zhangwenjian 65fb965f66 refactor🎨:修改行政区数据sql 2021-06-17 21:46:42 +08:00
zhangwenjian 493d714723 refactor🎨:修改行政区数据sql 2021-06-17 21:46:19 +08:00
zhangwenjian a911e73238 refactor🎨:调整行政区命名 2021-06-17 21:45:37 +08:00
zhangwenjian dff133bbbc refactor🎨:注释数据权限控制历史版本方法 2021-06-17 21:11:58 +08:00
zhangwenjian 60d9c59544 refactor🎨:删除历史版本菜单、角色、角色部门关系、角色菜单关系业务 2021-06-17 21:11:09 +08:00
zhangwenjian 185df737c8 refactor🎨:调整管理员和字典相关结构体字段顺序 2021-06-17 21:10:12 +08:00
zhangwenjian a0b7d9969a Revert "refactor🎨:注释未使用的对象"
This reverts commit 3358eeb54c.
2021-06-17 11:28:51 +08:00
zhangwenjian 3358eeb54c refactor🎨:注释未使用的对象 2021-06-17 11:28:37 +08:00
wenjianzhang d32751ea5d refactor🎨:文件上传修改为本地路径 2021-06-16 18:34:51 +08:00
wenjianzhang 8f637e02d0 refactor🎨:菜单、角色、用户模块调整 2021-06-16 18:34:25 +08:00
wenjianzhang e4ffd1df14 refactor🎨:注释返回数据记录 2021-06-16 18:33:56 +08:00
wenjianzhang 869bea2163 refactor🎨:系统监控接口 2021-06-16 18:33:14 +08:00
linwenxiang 7e9919e3ae feature ✨ 增加server manager,提升服务启动流程规范 2021-06-16 10:13:26 +08:00
wenjianzhang 5afe67bd1b refactor🎨:更新角色模块 2021-06-15 19:03:37 +08:00
wenjianzhang 13f09d6059 refactor🎨:数据迁移结构体重命名 2021-06-15 19:02:57 +08:00
wenjianzhang 1c9d2075d7 refactor🎨:调整接口和行政区结构体 2021-06-15 17:54:46 +08:00
wenjianzhang 3a688c06a1 refactor🎨:初始化脚本针对关键字添加引号 2021-06-15 17:54:04 +08:00
wenjianzhang 2d4b4d617d Merge branch 'dev' 2021-06-15 12:28:02 +08:00
wenjianzhang 9fb23b45cd Merge branch 'dev' 2021-06-15 12:25:46 +08:00
wenjianzhang af7a3e99a8 efactor🎨:修改行政区域数据结构
主键不需要自增
2021-06-15 12:22:30 +08:00
wenjianzhang 992d892523 refactor🎨:补充初始化数据 2021-06-15 12:16:44 +08:00
zhangwenjian 7699d8cf42 refactor🎨: 调整行政区管理相关 2021-06-15 09:29:35 +08:00
zhangwenjian f81c9c2ca0 refactor🎨: 调整删除时获取使用函数获取id 2021-06-15 09:28:58 +08:00
zhangwenjian 76351fe685 refactor🎨: 修正结构定义方法和绑定数据类型 2021-06-15 09:28:04 +08:00
zhangwenjian f0e8f18c6d refactor🎨: 更新客户端ip获取方法 2021-06-14 20:08:30 +08:00
zhangwenjian 880a3700d1 refactor🎨: 添加日志排序 2021-06-14 20:07:48 +08:00
zhangwenjian 273f2ba8b0 fix🐛: merge 的遗漏 2021-06-13 23:20:30 +08:00
zhangwenjian a3507998f7 Merge branch 'dev' 2021-06-13 23:14:34 +08:00
zhangwenjian 67d393a222 docs📝: update readme & dockfile 2021-06-13 23:09:11 +08:00
zhangwenjian 372248c819 Merge branch 'dev' 2021-06-13 23:07:37 +08:00
zhangwenjian b837489af0 docs📝: 更新readme 2021-06-13 21:52:15 +08:00
zhangwenjian e7223be040 refactor🎨: 升级依赖 2021-06-13 21:48:51 +08:00
zhangwenjian e37743733d refactor🎨: 更新初始化数据sql 2021-06-13 21:48:03 +08:00
zhangwenjian 58a9b00120 refactor🎨: 注释演示环境代码 2021-06-13 21:29:32 +08:00
zhangwenjian d8a627f880 refactor🎨: 优化资源管理的路由函数名称 2021-06-13 21:28:14 +08:00
zhangwenjian df46f86130 fix🐛: 修复菜单更新是不能更新绑定api的问题 2021-06-13 21:27:14 +08:00
zhangwenjian c98dd649eb refactor🎨: 添加更新handle 2021-06-13 21:25:47 +08:00
zhangwenjian da15a2d3bb refactor🎨: 调整SysChinaAreaData Api的函数名称以及路由引用 2021-06-13 21:24:09 +08:00
zhangwenjian 00c87d7c80 feat✨: api rabc检测时将排除列表中的path剔除不在参与验证 2021-06-13 21:22:55 +08:00
zhangwenjian 7c8c285fb8 feat✨: 添加排除路由列表 2021-06-13 21:20:44 +08:00
zhangwenjian e0cf7af7a9 refactor🎨: 调整客户端ip获取方法以及日志中对应位置更新 2021-06-13 21:20:07 +08:00
zhangwenjian ed52efaa44 refactor🎨: 修改数据字典路由注册 2021-06-13 21:16:55 +08:00
zhangwenjian 4a2aa02210 refactor🎨: 批量修改通过id获取详情返回消息 2021-06-13 21:14:17 +08:00
wenjianzhang cc0dab3cd0 refactor🎨: 开放接口无需认证 2021-06-11 17:30:17 +08:00
zhangwenjian 7b6e57b8dd Merge branch 'dev' of https://github.com/go-admin-team/go-admin into dev 2021-06-11 16:05:06 +08:00
zhangwenjian 325b2cc0a2 refactor🎨: demo环境中间件 2021-06-11 16:05:03 +08:00
wenjianzhang 52f45e362b Merge branch 'dev' of github.com:go-admin-team/go-admin into dev 2021-06-11 15:26:41 +08:00
wenjianzhang 1391366ece refactor🎨: 添加行政区模型 2021-06-11 15:26:35 +08:00
zhangwenjian 40668581b8 refactor🎨: 添加登陆验证 2021-06-11 09:26:22 +08:00
zhangwenjian 261e448577 refactor🎨: 操作日志去除菜单关联查询 2021-06-11 09:26:00 +08:00
zhangwenjian 7c7cd7ef7e refactor🎨: engine 初始化调整 2021-06-11 09:25:35 +08:00
zhangwenjian 860226ab41 refactor🎨: engine 初始化调整 2021-06-11 09:25:10 +08:00
zhangwenjian 898b1ea1e6 refactor🎨: 预览环境打包使用 2021-06-11 09:24:32 +08:00
linwenxiang f4d63c57e9 bugfix 🐛 提交遗漏代码 2021-06-11 09:20:27 +08:00
linwenxiang 3aa64d107b feature ✨ 优化setup 2021-06-10 17:15:13 +08:00
zhangwenjian 0e3e733745 Merge branch 'dev' of https://github.com/go-admin-team/go-admin into dev 2021-06-10 14:47:02 +08:00
zhangwenjian e6384de265 refactor🎨: 升级依赖 2021-06-10 14:46:29 +08:00
linwenxiang b9e8759ef1 feature ✨ 支持大文件分割配置 2021-06-10 11:54:02 +08:00
zhangwenjian ff5d498c53 refactor🎨: job和代码生成模块调整 2021-06-10 11:25:39 +08:00
zhangwenjian a8820a0aac refactor🎨: 菜单以及菜单角色模块调整 2021-06-10 11:24:59 +08:00
zhangwenjian 24c78519ed refactor🎨: 数据迁移模型调整 2021-06-10 11:24:35 +08:00
zhangwenjian 49c6febdf0 refactor🎨: 日志中的位置获取函数添加key传入 2021-06-10 11:24:17 +08:00
zhangwenjian 3d620d0149 refactor🎨: 添加高德地图key自定义扩展配置 2021-06-10 11:22:53 +08:00
zhangwenjian 352224b994 refactor🎨: 修改数据迁移脚本 2021-06-10 11:22:23 +08:00
zhangwenjian 897b9e6919 Merge branch 'dev' of https://github.com/go-admin-team/go-admin into dev 2021-06-09 21:36:57 +08:00
zhangwenjian 1b579fb814 feat✨: 添加修改角色状态接口 2021-06-09 21:31:31 +08:00
linwenxiang ab9020e7c7 feature ✨ gin请求纳入性能指标 2021-06-09 21:21:45 +08:00
wenjianzhang 54e116818b refactor🎨: 数据初始化 2021-06-09 18:30:47 +08:00
wenjianzhang 6a31ac916a refactor🎨: 移除v1版本中的数据迁移脚本 2021-06-09 18:25:00 +08:00
linwenxiang f35a808975 perf ⚡ 优化配置文件加载 2021-06-09 16:30:24 +08:00
linwenxiang b8ab38308d feature ✨ 参数校验支持国际化 2021-06-09 14:11:29 +08:00
wenjianzhang 91d902389a refactor🎨: 调整角色授权写法 2021-06-07 20:37:44 +08:00
wenjianzhang 5948c5c9a6 refactor🎨: 引用格式化 2021-06-07 20:37:20 +08:00
wenjianzhang 9a2c0729f6 refactor🎨: 缩减函数名称 2021-06-07 20:37:01 +08:00
wenjianzhang c96d9c35a7 refactor🎨 :支持名称和编码模糊搜索 2021-06-07 18:05:05 +08:00
zhangwenjian 65e0b58be9 refactor🎨: 去除log中间件日志打印 2021-06-07 16:41:21 +08:00
zhangwenjian dad4b4cca8 refactor🎨: 添加redis配置 2021-06-07 16:40:43 +08:00
zhangwenjian 3be02f1364 refactor🎨: 简化数据绑定 2021-06-07 16:39:59 +08:00
zhangwenjian 190dcfedc0 refactor🎨: 缩减函数名称 2021-06-07 16:39:26 +08:00
zhangwenjian 6e01c13e1c refactor🎨: 缩减函数名称 2021-06-07 16:38:30 +08:00
zhangwenjian bb77450f2c refactor🎨: 调整数据库模型字段类型,以适配其他数据库类型 2021-06-07 16:36:50 +08:00
wenjianzhang 4dfd4e4647 refactor🎨 :统一格式 2021-06-03 19:39:19 +08:00
zhangwenjian 9a49700d09 refactor🎨: 调整对象定义方式 2021-06-03 09:31:10 +08:00
zhangwenjian 107a8d8f90 docs📝: 修改GetPermissionFromContext函数注解 2021-06-03 09:30:04 +08:00
zhangwenjian b70b853016 refactor🎨: 调整格式 2021-06-03 09:29:19 +08:00
zhangwenjian dd2ed9f9a5 refactor🎨: login文档注解修改 2021-06-03 09:28:44 +08:00
zhangwenjian 1a645f8521 refactor🎨: 操作日志添加文档注解 2021-06-03 09:28:27 +08:00
zhangwenjian c05cb63bc7 refactor🎨: 改造升级用户管理模块 2021-06-03 09:27:34 +08:00
zhangwenjian 602ff26988 docs📝: 修改api文档注解 2021-06-03 09:23:48 +08:00
zhangwenjian b7d6b6786c docs📝: 添加参数api文档注解 2021-06-03 09:18:44 +08:00
zhangwenjian 95c794c80d docs📝: 修改菜单列表api文档注解 2021-06-03 09:18:11 +08:00
zhangwenjian e59dd88f97 docs📝: 更新api文档 2021-06-03 09:16:53 +08:00
wenjianzhang 974d5b2889 Merge pull request #438 from go-admin-team/1.3.x 2021-06-01 07:42:05 +08:00
zhangwenjian fb42953fbe Merge branch '1.3.x' of https://github.com/go-admin-team/go-admin into 1.3.x 2021-06-01 07:35:06 +08:00
zhangwenjian 277129e830 docs📝 update 2021-06-01 07:34:48 +08:00
wenjianzhang cdc5c1246e Merge pull request #437 from ninstein/patch-5
bugfix:必填字段判断错误修复
2021-06-01 00:21:34 +08:00
zhangwenjian c0f920d43c fix🐛 定时任务,触发函数,无法正常关闭(#432) 2021-06-01 00:17:35 +08:00
zhangwenjian f31d1a137f perf👌 调整应用中间件 2021-05-31 23:52:56 +08:00
zhangwenjian b1d3924294 perf👌 优化job处理方式 2021-05-31 23:52:32 +08:00
zhangwenjian 526a993698 fix🐛 定时任务,触发函数,无法正常关闭(#432) 2021-05-31 23:51:47 +08:00
zhangwenjian f5d9a22f83 perf👌 调整菜单代码结构 2021-05-31 23:37:04 +08:00
zhangwenjian 5ae3ef3a15 perf👌 修正菜单搜索条件信息 2021-05-31 23:36:41 +08:00
zhangwenjian 0773de2fc5 perf👌 修正接口文档配置信息 2021-05-31 23:36:20 +08:00
zhangwenjian 48a57c4244 perf👌 更新版本 2021-05-31 23:35:03 +08:00
zhangwenjian 9b1cba311e perf👌 added menu type enum 2021-05-31 23:34:50 +08:00
ninstein b5bfece9f1 bugfix:必填字段判断错误修复 2021-05-31 21:12:04 +08:00
zhangwenjian 06000a6dac perf👌 runtime接管 中间件 2021-05-31 18:11:19 +08:00
zhangwenjian a54d4ba0c1 format🥚 代码格式化 2021-05-31 18:10:23 +08:00
zhangwenjian a7cc943b8e Merge remote-tracking branch 'origin/dev' into dev 2021-05-31 18:04:59 +08:00
linwenxiang 2cb81654a6 fix 🐛 修复queue redis模式阿里云不工作问题 2021-05-31 14:43:43 +08:00
linwenxiang 0314991f9e fix 🐛 修复queue redis模式阿里云不工作问题 2021-05-31 14:39:27 +08:00
wenjianzhang da16b4af7a fix🐛 query built from **** sources 2021-05-30 22:17:11 +08:00
wenjianzhang 32d8f4384a feat✨ 参数更新功能 2021-05-28 17:12:55 +08:00
wenjianzhang d69b7807c1 feat✨ 添加修改配置接口 2021-05-27 19:33:41 +08:00
wenjianzhang dc32d92755 feat ✨ 开放部分中间件 2021-05-25 19:37:56 +08:00
wenjianzhang ca8fd2178d feat ✨ 操作日志多余参数去掉 2021-05-25 19:37:40 +08:00
wenjianzhang b565b72cd3 feat ✨ 上传文件去掉默认标识验证 2021-05-25 19:37:19 +08:00
wenjianzhang 8d272e8862 feat ✨ 排序字段接受参数名调整 2021-05-25 19:36:57 +08:00
wenjianzhang dd7b50e0fa feat ✨ 操作日志功能更换bind方式 2021-05-25 19:36:20 +08:00
wenjianzhang 623e796c92 feat ✨ 操作日志功能更换bind方式 2021-05-25 19:35:45 +08:00
wenjianzhang 126f62ce59 feat ✨ 参数设置添加接口文档 2021-05-25 19:35:05 +08:00
zhangwenjian 77c149af04 refactor🎨 api业务dto bind()、Generate()优化 2021-05-25 07:33:35 +08:00
wenjianzhang b21f665760 feat ✨ 添加队列和缓存的默认配置信息 2021-05-24 18:40:57 +08:00
wenjianzhang be36c595c3 feat ✨ 移除重复注册中间件 2021-05-24 18:40:32 +08:00
wenjianzhang 1ac6568f67 feat ✨ 日志中间件调整 2021-05-24 18:39:53 +08:00
wenjianzhang b902ab2a5f feat ✨ 用户模块添加列排序 2021-05-24 18:39:32 +08:00
wenjianzhang 5069c3074b feat ✨ 用户模块添加列排序 2021-05-24 18:39:21 +08:00
wenjianzhang e0bd26d837 feat ✨ 角色模块添加列排序 2021-05-24 18:39:00 +08:00
wenjianzhang cc74686108 feat ✨ 接口管理模块添加列排序 2021-05-24 16:30:21 +08:00
wenjianzhang 7880151ef2 refactor🎨 系统监控更名Monitor》ServerMonitor 2021-05-24 10:37:16 +08:00
wenjianzhang cfa88b5ecf refactor🎨 系统监控地址格式化 2021-05-24 10:35:52 +08:00
zhangwenjian 452a561309 feat ✨ 数据字典根据key获取 业务页面使用 2021-05-24 07:40:48 +08:00
zhangwenjian 2ac8f925c9 refactor🎨 api业务功能调整 2021-05-23 17:52:43 +08:00
zhangwenjian 6cbded6241 fix🐛 修复部门数据权限 2021-05-22 23:11:36 +08:00
zhangwenjian f40b300c16 docs📝 修改readme 2021-05-22 23:01:16 +08:00
zhangwenjian e473f158e8 refactor🎨 核心业务结构调整 2021-05-22 22:54:08 +08:00
wenjianzhang 408dcc5057 refactor🎨 部分功能重写 2021-05-21 18:25:51 +08:00
wenjianzhang 765775c54d Merge branch 'dev' of github.com:go-admin-team/go-admin into dev 2021-05-20 23:00:49 +08:00
wenjianzhang 44545f3d5b feat✨ 结构统一调整 2021-05-20 22:59:09 +08:00
linwenxiang e23a1f615f feat ✨ 优化logger使用 2021-05-19 19:31:04 +08:00
linwenxiang d3fa3ecf6c Merge branch 'dev' of github.com:go-admin-team/go-admin into dev 2021-05-18 08:51:32 +08:00
wenjianzhang 6b1c3d9226 refactor🎨 api数据初始化调整 2021-05-17 23:09:35 +08:00
linwenxiang 70d4976595 Merge branch 'dev' of github.com:go-admin-team/go-admin into dev 2021-05-17 22:26:56 +08:00
wenjianzhang b2345039e4 refactor🎨 移除设置log函数 2021-05-16 21:47:49 +08:00
zhangwenjian 33275573f9 refactor🎨 链式调用改造 2021-05-16 16:17:37 +08:00
wenjianzhang 9fdde1a13b Merge pull request #424 from GizmoOAO/dev
fix🐛 修复vue模板的条件判断 #423
2021-05-15 17:55:13 +08:00
CunYu 09cc51e5de fix🐛 修复vue模板的条件判断 #423 2021-05-15 09:03:01 +08:00
wenjianzhang 20e7f79f4f refactor🎨 添加默认字段排序 2021-05-14 19:32:53 +08:00
wenjianzhang b82c3d9f99 refactor🎨 升级gin版本 2021-05-14 12:22:41 +08:00
wenjianzhang dfd460c50b feat✨ apis路径简化 2021-05-14 12:19:22 +08:00
wenjianzhang 8adc79a5f7 feat✨ 新增省市区基础数据 2021-05-13 08:45:27 +08:00
wenjianzhang 2580be08ab feat✨ 优化写法 2021-05-12 18:50:13 +08:00
wenjianzhang fd9df69d1f feat✨ 检查并写入api 2021-05-12 18:48:38 +08:00
wenjianzhang d0b2e8d03f feat✨ 添加api管理 2021-05-12 18:48:01 +08:00
wenjianzhang 70998c424d refactor🎨 优化Context设置方法 2021-05-12 18:47:29 +08:00
wenjianzhang abcdf880fd refactor🎨 优化模版 2021-05-12 18:46:23 +08:00
linwenxiang fac18b28f0 Merge branch 'dev' of github.com:go-admin-team/go-admin into dev
 Conflicts:
	common/apis/api.go
2021-05-11 22:12:14 +08:00
wenjianzhang ee15329bd2 feat✨ systables 数据迁移模块更新 2021-05-11 18:53:40 +08:00
wenjianzhang 98e0ee92a7 Default Changelist 2021-05-11 18:51:16 +08:00
wenjianzhang 54158b8824 feat✨ systables 》 sys_tables 2021-05-11 18:50:40 +08:00
wenjianzhang 75cd2f374a feat✨ gen模块文件名和路径规则调整 2021-05-11 18:49:41 +08:00
wenjianzhang a78cc33cd1 feat✨ 重置router 2021-05-11 18:48:44 +08:00
wenjianzhang fea425c36c feat✨ 分离gen router 2021-05-11 18:47:45 +08:00
wenjianzhang 61c89bca8d feat✨ 重置config router 2021-05-11 18:43:52 +08:00
wenjianzhang 76e83de8cd feat✨ 重置dept router 2021-05-11 18:42:56 +08:00
wenjianzhang c9d9350476 feat✨ 分离字典相关路由 2021-05-11 18:42:20 +08:00
wenjianzhang 34a1eea45e feat✨ 重置loginlog router 2021-05-11 18:41:43 +08:00
wenjianzhang c505884cf2 feat✨ 修改删除接口传参方式 2021-05-11 18:40:59 +08:00
wenjianzhang b95f517a4c feat✨ 重置operalog router 2021-05-11 18:39:48 +08:00
wenjianzhang 50da7825bb feat✨ 重置post路由 2021-05-11 18:38:44 +08:00
wenjianzhang 0a3e3be12c feat✨ 添加api管理 2021-05-11 18:35:55 +08:00
wenjianzhang c13d13ccf4 feat✨ 添加api结构体 2021-05-11 18:34:57 +08:00
wenjianzhang 0317c3aaf5 feat✨ 添加生成模块前端文件名 2021-05-11 18:33:29 +08:00
wenjianzhang 03eaad5b8b feat✨ 统一api生成路径 2021-05-11 08:37:27 +08:00
wenjianzhang e091603bc8 feat✨ 添加api管理功能 2021-05-10 18:24:47 +08:00
wenjianzhang cd29c1728d refactor🎨 删除模版生成提示代码 2021-05-10 18:23:41 +08:00
wenjianzhang 65b86353e3 fix🐛 修改合并代码产生的问题 2021-05-10 18:21:11 +08:00
wenjianzhang 5f594d6bae refactor🎨 修改参数删除,由url参数改为body 2021-05-10 18:20:14 +08:00
wenjianzhang bde8148eb1 Merge branch 'dev' of https://github.com/go-admin-team/go-admin into dev 2021-05-10 17:04:33 +08:00
wenjianzhang ae34ff8f82 feat✨优化router import 2021-05-10 17:02:26 +08:00
wenjianzhang ef33508e2b fix🐛 update 2021-05-08 18:29:14 +08:00
wenjianzhang a8c5f19075 refactor🎨 修改工具写法 2021-05-08 18:28:51 +08:00
wenjianzhang 1c046d9ddd Merge branch '1.3.x' into github-dev 2021-05-08 17:21:35 +08:00
wenjianzhang 6222765e20 feat✨优化配置信息 2021-05-08 16:50:51 +08:00
wenjianzhang f56839926e Merge remote-tracking branch 'github/dev' into github-dev 2021-05-08 13:53:49 +08:00
zhangwenjian c6a52134b3 feat✨优化字典数据错误判断写法 2021-05-08 13:53:27 +08:00
zhangwenjian 7fffcffcdd feat✨ 分离app 2021-05-08 09:35:49 +08:00
linwenxiang b0225d9bab feat ✨ 增加bind通用方法 2021-04-27 11:48:03 +08:00
356 changed files with 27104 additions and 14769 deletions
+100
View File
@@ -0,0 +1,100 @@
---
name: new-business-module
description: Scaffold a new single-table CRUD business module end to end — migration, Actions-mode model/dto/router, and the sys_menu/sys_api/casbin seed data that makes it show up in the UI with working permissions. Use when the user wants to add a new business table/module to go-admin, not for cross-table or non-CRUD business logic.
---
# 新增业务模块
给一张新的业务表配齐"能跑、能看见、能授权"的完整闭环:迁移 → 后端代码 → 菜单与权限种子数据。
只适用于单表增删改查;跨表事务、外部调用、复杂校验等超出这个范围(见下方"何时不适用")。
开始前先读 `AGENTS.md`(分层边界、通用 Action 使用前提、命名规则)和 `app/demo/` 下的全部文件——
这是可编译、有测试、CI 会跑的参照物,本文与它冲突时以它为准。
## 何时不适用
业务超出单表 CRUD(跨表事务、外部服务调用、复杂校验)时,不要用这个 skill 硬套——
改成手写 Handler + Service,参照 `app/admin/apis/sys_post.go` 及其 Service,遵守
`AGENTS.md` 的分层约束(Api 不碰 Orm,Service 不碰 `gin.Context`,一律用 `e.Orm`)。
## 步骤
### 1. 确认表结构
表结构需符合命名规范:`sys_`/业务前缀 + 下划线(如 `tb_article`)。核对字段是否已有
`created_at`/`updated_at`/`deleted_at` 这类约定字段。
### 2. 写数据库迁移
放在 `cmd/migrate/migration/version/` 目录(**不是** `version-local/` —— 后者在
`.gitignore` 中,提交时会被忽略,`git status` 也看不到)。
- 文件名前 13 位是时间戳版本号
- 已执行过的迁移文件不可修改;需要修正时新增一个迁移
- 包名为 `version`
### 3. 生成 model / dto / router 三个文件(Actions 模式)
不要手写 Api 与 Service。使用 `common/actions` 的通用 Action,一个模块只需
model、dto、router 三个文件,完整写法照抄 `app/demo/` 的结构。
**关键正确性要求**(这三条是实际出问题最多的地方):
- Model 实现 `models.ActiveRecord`(`Generate` / `GetId` / `TableName`),
`TableName()` 必须显式声明——GORM 配置了 `SingularTable`,不会自动推导
- **`Generate()` 必须返回副本,不要就地返回**——Action 在并发请求间复用实例,
就地返回会导致请求之间串数据;这个问题单人测试时几乎不出现,上线后才暴露
- 完成后确认 `cmd/api/` 中已用 `_` 导入新包,否则路由不会被注册
### 4. 写菜单、接口与权限种子数据
这一步最容易被漏掉——代码能编译、接口能测通,但界面上看不到菜单、点了按钮说
没权限,往往就是漏了这一步。结构参照 `cmd/migrate/migration/version/1786700001000_demo_menu.go`
——它是可运行、幂等(用 `upsert`,重复跑不会报错)的真实例子。
:::danger
**但不要照抄它的 import。** 那个文件用的是 `cmd/migrate/migration/models`,
只因为它的版本号排在软删除转换(`1786700003000`)之前才是安全的。
**你新写的迁移版本号在转换之后,必须改用 `app/` 下的运行时模型**
(`app/admin/models.SysApi`、`SysMenu`),否则第一条 insert 就会
`NOT NULL constraint failed: sys_api.deleted_at`。
`TestPostConversionMigrationsAvoidFrozenSeedModels` 会拦住这个错误。
:::
一个模块要在界面上可用,需要四类数据,缺一样都不行:
| 表 | 作用 |
|---|---|
| `sys_api` | 后端路由登记,Casbin 据此判定权限 |
| `sys_menu` | 侧边栏菜单(目录用 `M`、菜单用 `C`、按钮用 `F`) |
| `sys_menu_api_rule` | 菜单与接口的多对多关联,角色保存时据此生成策略 |
| `casbin_rule` | 实际生效的权限策略(**不是** `sys_casbin_rule`,那张表的唯一索引在 MySQL 下会超长,不要迁移它) |
必须核对的两处一致性——**错了不会报错,只会在界面上表现为"看不到/点不动"**:
- `sys_menu.menu_name` 必须与前端组件的 `defineOptions({ name: 'XxxManage' })` 一致,
否则 `keep-alive` 缓存静默失效
- 按钮级 `sys_menu.permission`(格式 `模块:资源:操作`)必须与前端
`v-permisaction="['模块:资源:操作']"` 完全一致,否则按钮权限判断静默失效
### 5. 收尾检查
| 检查项 | 出错后果 |
| --- | --- |
| `Generate()` 是否返回副本 | 并发请求之间串数据 |
| 是否使用 `e.Orm` 而非全局 DB | 多租户下拿到错误的数据库连接 |
| `TableName()` 是否显式声明 | GORM 不会自动推导 |
| 迁移文件是否放在 `version/` | 放进 `version-local/` 会被忽略,别人拉代码看不到 |
| `sys_menu.menu_name` 是否与前端组件 `name` 一致 | keep-alive 缓存静默失效 |
| `sys_menu.permission` 是否与前端 `v-permisaction` 一致 | 按钮权限静默失效 |
跑一遍 `go run -tags sqlite3 . migrate -c config/settings.sqlite.yml` 验证迁移可执行,
再 `go run -tags sqlite3 . server -c config/settings.sqlite.yml` 启动服务,用 admin
账号登录确认新菜单和按钮权限都出现了。
如果前端页面还没生成,下一步用 go-admin-ui 仓库里的 `new-list-page` skill——两边靠
`sys_menu.permission` / `v-permisaction` 这个字符串对齐。
> 不要把 `config/settings.yml` 的真实内容贴给 AI 工具——`database.source` 含数据库
> 账号密码,`jwt.secret` 泄露后可被用来伪造任意用户的 token。
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: 🆕 Create new issue
url: http://new-issue.go-admin.dev
about: The issue which is not created via http://new-issue.go-admin.dev will be closed immediately.
- name: 🆕 创建一个新 Issue
url: http://new-issue.go-admin.dev
about: 不是用 http://new-issue.go-admin.dev 创建的 issue 会被机器人自动关闭。
+66
View File
@@ -0,0 +1,66 @@
<!--
First of all, thank you for your contribution! 😄
For requesting to pull a new feature or bugfix, please send it from a feature/bugfix branch based on the `master` branch.
Before submitting your pull request, please make sure the checklist below is confirmed.
Your pull requests will be merged after one of the collaborators approve.
Thank you!
-->
[[中文版模板 / Chinese template](https://github.com/go-admin-team/go-admin/blob/master/.github/PULL_REQUEST_TEMPLATE/pr_cn.md)]
### 🤔 This is a ...
- [ ] New feature
- [ ] Bug fix
- [ ] Site / documentation update
- [ ] Demo update
- [ ] Component style update
- [ ] TypeScript definition update
- [ ] Bundle size optimization
- [ ] Performance optimization
- [ ] Enhancement feature
- [ ] Internationalization
- [ ] Refactoring
- [ ] Code style optimization
- [ ] Test Case
- [ ] Branch merge
- [ ] Other (about what?)
### 🔗 Related issue link
<!--
1. Put the related issue or discussion links here.
-->
### 💡 Background and solution
<!--
1. Describe the problem and the scenario.
2. GIF or snapshot should be provided if includes UI/interactive modification.
3. How to fix the problem, and list the final API implementation and usage sample if that is a new feature.
-->
### 📝 Changelog
<!--
Describe changes from the user side, and list all potential break changes or other risks.
--->
| Language | Changelog |
| ---------- | --------- |
| 🇺🇸 English | |
| 🇨🇳 Chinese | |
### ☑️ Self-Check before Merge
⚠️ Please check all items below before review. ⚠️
- [ ] Doc is updated/provided or not needed
- [ ] Demo is updated/provided or not needed
- [ ] TypeScript's definition is updated/provided or not needed
- [ ] Changelog is provided or not needed
+61
View File
@@ -0,0 +1,61 @@
<!--
首先,感谢你的贡献!😄
新特性请提交至 feature 分支,其余可提交至 master 分支。
在维护者审核通过后会合并。
请确保填写以下 pull request 的信息,谢谢!~
-->
[[English Template / 英文模板](https://github.com/go-admin-team/go-admin/blob/master/.github/PULL_REQUEST_TEMPLATE.md)]
### 🤔 这个变动的性质是?
- [ ] 新特性提交
- [ ] 日常 bug 修复
- [ ] 站点、文档改进
- [ ] 演示代码改进
- [ ] 组件样式/交互改进
- [ ] TypeScript 定义更新
- [ ] 包体积优化
- [ ] 性能优化
- [ ] 功能增强
- [ ] 国际化改进
- [ ] 重构
- [ ] 代码风格优化
- [ ] 测试用例
- [ ] 分支合并
- [ ] 其他改动(是关于什么的改动?)
### 🔗 相关 Issue
<!--
1. 描述相关需求的来源,如相关的 issue 讨论链接。
-->
### 💡 需求背景和解决方案
<!--
1. 要解决的具体问题。
2. 列出最终的 API 实现和用法。
3. 涉及UI/交互变动需要有截图或 GIF。
-->
### 📝 更新日志
<!--
从用户角度描述具体变化,以及可能的 breaking change 和其他风险。
-->
| 语言 | 更新描述 |
| ------- | -------- |
| 🇺🇸 英文 | |
| 🇨🇳 中文 | |
### ☑️ 请求合并前的自查清单
⚠️ 请自检并全部**勾选全部选项**。⚠️
- [ ] 文档已补充或无须补充
- [ ] 代码演示已提供或无须提供
- [ ] TypeScript 定义已补充或无须补充
- [ ] Changelog 已提供或无须提供
+146
View File
@@ -0,0 +1,146 @@
name: Build
# Documentation-only changes skip this workflow entirely.
#
# A push to master here does not just build - it pushes an image, runs the
# migrations and restarts the demo container, so the site takes a short outage.
# Paying that for a README edit is waste at best; at worst a deploy fails for a
# reason unrelated to anything in the change. Code coverage is unaffected,
# because go.yml still builds every push and pull request.
on:
push:
branches: [ master ]
paths-ignore:
- '**.md'
- 'docs/**'
- 'LICENSE*'
- '.github/ISSUE_TEMPLATE/**'
pull_request:
branches: [ master ]
paths-ignore:
- '**.md'
- 'docs/**'
- 'LICENSE*'
- '.github/ISSUE_TEMPLATE/**'
# One deploy at a time. Two merges seconds apart raced here: both runs did
# docker rm -f then docker run, the second removed the container the first had
# just created, and the first's docker run then failed on a name conflict -
# leaving the demo on the older image with a red deploy.
concurrency:
group: deploy-${{ github.ref }}
cancel-in-progress: false
env:
IMAGE_NAME: registry.ap-northeast-1.aliyuncs.com/go-admin/go-admin-api # 镜像名称
TAG: ${{ github.sha }}
IMAGE_NAME_TAG: registry.ap-northeast-1.aliyuncs.com/go-admin/go-admin-api:${{ github.sha }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: 1.26.5
- name: Tidy
run: go mod tidy
- name: Build
run: env CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -tags "sqlite3,json1" --ldflags "-extldflags -static" -o main .
# 以下推镜像与重启步骤仅在 master 收到 push 时执行。
# pull_request 事件同样会触发本工作流,若不加限制,任何指向 master 的
# PR 一经创建就会把 PR 分支的镜像推上仓库,并直接重启线上 API 服务,
# 且发生在合并之前。构建与编译校验不受影响,PR 仍会执行。
- name: Build the Docker image and push
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
run: |
docker login --username=${{ secrets.DOCKER_USERNAME }} registry.ap-northeast-1.aliyuncs.com --password=${{ secrets.DOCKER_PASSWORD }}
echo "************ docker login end"
docker build -t go-admin-api:latest .
echo "************ docker build end"
docker tag go-admin-api ${{ env.IMAGE_NAME_TAG }}
echo "************ docker tag end"
docker images
echo "************ docker images end"
docker push ${{ env.IMAGE_NAME_TAG }} # 推送
echo "************ docker push end"
- name: Restart server # 第五步,重启服务
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
uses: appleboy/ssh-action@0ff4204d59e8e51228ff73bce53f80d53301dee2 # v1.2.5
env:
GITHUB_SHA_X: ${GITHUB_SHA}
with:
host: ${{ secrets.SSH_HOST }} # 下面三个配置与上一步类似
username: ${{ secrets.SSH_USERNAME }}
key: ${{ secrets.DEPLOY_KEY }}
# 重启的脚本,根据自身情况做相应改动,一般要做的是migrate数据库以及重启服务器
#
# 配置从宿主机挂载,不使用镜像里的那份:演示站连的是托管数据库,
# 而 config/settings.demo.yml 会随仓库公开、也会打进镜像,凭据不能写在那里。
# 镜像里那份保持 sqlite,供 clone 仓库的人开箱即用。
#
# 路径本身走 secret:它不是凭据,但本仓库公开,没有理由把服务器的
# 目录结构一并公布。DEMO_CONFIG_PATH 指向宿主机上那份配置。
#
# 顺序是有意的:迁移先跑,跑不过就保持现有版本不动;
# 旧容器改名保留而不是删除,新容器不健康时能原样恢复。
# 健康检查两条都要过——HTTP 活着不代表数据库通了。
script: |
set -u
CFG="${{ secrets.DEMO_CONFIG_PATH }}"
IMG="${{ env.IMAGE_NAME_TAG }}"
NAME=go-admin-api
PREV="$NAME-prev"
test -f "$CFG" || { echo "宿主机配置缺失,中止部署"; exit 1; }
sudo docker login --username=${{ secrets.DOCKER_USERNAME }} registry.ap-northeast-1.aliyuncs.com --password=${{ secrets.DOCKER_PASSWORD }}
sudo docker pull "$IMG" || { echo "拉取镜像失败,中止部署"; exit 1; }
# 迁移用新镜像跑。失败时线上仍是旧版本配旧 schema,是自洽的;
# 硬切过去才会得到代码与表对不上的服务。
if ! sudo docker run --rm -v "$CFG":/config/settings.yml:ro "$IMG" \
/main migrate -c /config/settings.yml; then
echo "迁移失败,保持现有版本"; exit 1
fi
if sudo docker ps -a --format '{{.Names}}' | grep -qx "$NAME"; then
sudo docker rm -f "$PREV" >/dev/null 2>&1 || true
sudo docker rename "$NAME" "$PREV"
sudo docker stop "$PREV" >/dev/null
fi
sudo docker run -d -p 8000:8000 \
-v "$CFG":/config/settings.yml:ro \
--name "$NAME" "$IMG"
ok=0
for i in $(seq 1 20); do
sleep 3
code=$(curl -s -o /dev/null -w '%{http_code}' -m 5 http://127.0.0.1:8000/api/v1/captcha 2>/dev/null || true)
if [ "$code" = "200" ] && sudo docker logs "$NAME" 2>&1 | grep -q 'connect success'; then
ok=1; echo "健康检查通过(第 $i 次探测)"; break
fi
done
if [ "$ok" = "1" ]; then
sudo docker rm -f "$PREV" >/dev/null 2>&1 || true
else
echo "健康检查失败,回滚到上一版本"
sudo docker logs --tail 40 "$NAME" 2>&1 || true
sudo docker rm -f "$NAME" >/dev/null 2>&1 || true
if sudo docker ps -a --format '{{.Names}}' | grep -qx "$PREV"; then
sudo docker rename "$PREV" "$NAME"
sudo docker start "$NAME" >/dev/null
echo "已恢复"
fi
exit 1
fi
+4 -4
View File
@@ -19,11 +19,11 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
uses: github/codeql-action/init@24c7eb380a2dc368f2d129e4c65e51d172983a1e # v4
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -34,7 +34,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
uses: github/codeql-action/autobuild@24c7eb380a2dc368f2d129e4c65e51d172983a1e # v4
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -48,4 +48,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
uses: github/codeql-action/analyze@24c7eb380a2dc368f2d129e4c65e51d172983a1e # v4
-60
View File
@@ -1,60 +0,0 @@
name: build
on:
push:
branches: [ dev-lwx ]
pull_request:
branches: [ dev-lwx ]
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.15
uses: actions/setup-go@v1
with:
go-version: 1.15
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Get dependencies
run: |
go get -v -t -d ./...
if [ -f Gopkg.toml ]; then
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
dep ensure
fi
- name: Build
run: |
CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -a -installsuffix cgo -o go-admin .
mv go-admin ./scripts
- uses: Azure/docker-login@v1
with:
login-server: registry.cn-shanghai.aliyuncs.com
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- run: |
docker build ./scripts -t registry.cn-shanghai.aliyuncs.com/go-admin-team/go-admin:${{ github.sha }}
docker push registry.cn-shanghai.aliyuncs.com/go-admin-team/go-admin:${{ github.sha }}
- uses: Azure/k8s-set-context@v1
with:
kubeconfig: ${{ secrets.KUBE_CONFIG }}
- uses: Azure/k8s-create-secret@v1
with:
namespace: 'go-admin'
container-registry-url: registry.cn-shanghai.aliyuncs.com
container-registry-username: ${{ secrets.REGISTRY_USERNAME }}
container-registry-password: ${{ secrets.REGISTRY_PASSWORD }}
secret-name: aliyuncs-k8s-secret
- uses: Azure/k8s-deploy@v1
with:
namespace: 'go-admin'
manifests: 'scripts/k8s/deploy.yml'
images: 'registry.cn-shanghai.aliyuncs.com/go-admin-team/go-admin:${{ github.sha }}'
imagepullsecrets: 'aliyuncs-k8s-secret'
kubectl-version: 'latest'
+59 -12
View File
@@ -2,9 +2,13 @@ name: build
on:
push:
branches: [ master ]
branches: [ master, dev ]
tags: [ 'v*', '[0-9]*' ]
pull_request:
branches: [ master ]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
@@ -13,22 +17,65 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.14
uses: actions/setup-go@v1
- name: Set up Go 1.26
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: 1.14
go-version: 1.26.5
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Get dependencies
run: |
go get -v -t -d ./...
if [ -f Gopkg.toml ]; then
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
dep ensure
fi
run: go mod tidy
# go build does not compile _test.go, so building alone never ran a single
# test. This is the only workflow that fires on every push and pull request,
# which makes it the one place a test gate belongs.
- name: Test
run: make test
- name: Build
run: go build -v .
run: make build
# Fails the build on the silent-failure classes listed in
# tools/checksilent, one of which is the contract boundary: nothing under
# common/ may import app/. A boundary that is only written down erodes; this
# is what keeps it true.
- name: Silent-failure checks
run: make checksilent
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
if: startsWith(github.ref, 'refs/tags/')
- name: Log in to the Container registry
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
if: startsWith(github.ref, 'refs/tags/')
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
if: startsWith(github.ref, 'refs/tags/')
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
flavor: |
latest=auto
tags: |
type=schedule
type=ref,event=tag
type=sha,prefix=,format=long,enable=true,priority=100
- name: Build and push Docker image
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
if: startsWith(github.ref, 'refs/tags/')
with:
context: .
file: scripts/Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+24 -6
View File
@@ -1,15 +1,19 @@
.idea
.vscode
*/.DS_Store
.DS_Store
static/uploadfile
main.exe
*.exe
go-admin
go-admin.exe
# `go build ./tools/checksilent` drops the binary here, next to the one for the
# server. Anchored with a leading slash: unanchored, the same pattern matches
# tools/checksilent/ as well and the tool's own source never gets committed.
/checksilent
temp/
!temp
vendor
config/settings.dev.yml
go-admin
common/middleware/demo.go
config/settings.dev.*.yml
config/settings.dev.*.yml.log
temp/logs
@@ -17,8 +21,22 @@ config/settings.dev.yml.log
config/settings.b.dev.yml
cmd/migrate/migration/version-local/*
!cmd/migrate/migration/version-local/doc.go
*/.DS_Store
# go sum
go.sum
config/settings.deva.yml
go-admin-server
CLAUDE.md
# Everything under .claude is private by default. Skills meant for people using
# go-admin are re-included one directory at a time, so a personal one dropped in
# here is never committed by accident.
.claude/*
!.claude/skills/
.claude/skills/*
!.claude/skills/new-business-module/
config/settings.local.dev.yml
# Go workspace files. They exist to point this module at a local checkout of
# go-admin-core while the two are developed together, which is a private
# arrangement between one machine's directories - committing one would break
# the build for everyone else.
go.work
go.work.sum
+260
View File
@@ -0,0 +1,260 @@
# AGENTS.md — go-admin 后端
> 给 AI 编码工具与新贡献者的约定。**只写"不遵守就会出错"的规则**;技术栈版本以
> `go.mod` 为准,命令以 `Makefile` 为准,此处不复述,避免与代码脱节。
>
> 标准 CRUD 模块的完整写法见 **`app/demo/`** —— 那是可编译、有测试、CI 会跑的参照物。
> 本文与它冲突时,以 `app/demo/` 为准。
## 分层
```
Router → Api → Service → Model
路由注册 参数绑定 业务逻辑 GORM 结构体
中间件链 调用 Service 操作数据库 TableName()
```
对应目录:`app/{模块}/router|apis|service|models`,DTO 位于 `service/dto`。
**不可跨层**:Api 不直接操作 `Orm`,Service 不接触 `gin.Context`。
## 优先使用通用 Action
单表 CRUD **不要手写 Handler 与 Service**。`common/actions` 提供的五个
Action 已覆盖参数绑定、数据权限过滤、操作人注入、分页与错误响应:
```go
r := v1.Group("/demo-product").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
m := &models.DemoProduct{}
r.GET("", actions.PermissionAction(), actions.IndexAction(m, new(dto.DemoProductSearch), func() interface{} {
list := make([]models.DemoProduct, 0); return &list
}))
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.DemoProductById), func() interface{} {
return &models.DemoProduct{}
}))
r.POST("", actions.CreateAction(new(dto.DemoProductControl)))
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.DemoProductControl)))
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.DemoProductById)))
}
```
这样一个模块只需 **model + dto + router** 三个文件,完整示例见 `app/demo/`。
使用通用 Action 的前提:
- Model 实现 `models.ActiveRecord`(`Generate` / `GetId` / `TableName`)
- 列表 DTO 实现 `dto.Index`,增改删 DTO 实现 `dto.Control`
- **所有 `Generate()` 必须返回副本** —— Action 在并发请求间复用实例,
就地返回会串数据(`app/demo` 的测试锁定了这一点)
- 详情/删除 DTO 内嵌 `dto.ObjectById` 即可继承 `Bind` 与 `GetId`,无需重写
仅当业务超出单表 CRUD(跨表事务、外部调用、复杂校验)时才自行编写 Handler
与 Service,写法见下。
## Api 层(仅在通用 Action 不适用时)
结构体嵌入 `api.Api`,链式初始化后**必须检查 `Errors`**:
```go
func (e SysPost) GetPage(c *gin.Context) {
s := service.SysPost{}
req := dto.SysPostPageReq{}
err := e.MakeContext(c).MakeOrm().Bind(&req, binding.Form).MakeService(&s.Service).Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
// ... 调用 s.GetPage(...)
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
```
响应一律走 `e.OK` / `e.PageOK` / `e.Error`,不要自行 `c.JSON`。
## Service 层(仅在通用 Action 不适用时)
结构体嵌入 `service.Service`(持有 `Orm` 与 `Log`)。查询通过 Scopes 组合:
```go
err = e.Orm.Model(&data).Scopes(
cDto.MakeCondition(c.GetNeedSearch()), // 由 search tag 生成 WHERE
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
actions.Permission(data.TableName(), p), // 数据权限,列表/详情必须带
).Find(list).Limit(-1).Offset(-1).Count(count).Error
```
**遗漏 `actions.Permission` 会使数据权限配置静默失效** —— 这是最容易出的错。
错误一律 `return err` 向上传递,日志用 `e.Log.Errorf`,不使用 `panic`。
## DTO
搜索条件由 tag 声明,`MakeCondition` 据此拼 SQL:
```go
type SysPostPageReq struct {
dto.Pagination `search:"-"`
PostName string `form:"postName" search:"type:contains;column:post_name;table:sys_post"`
}
func (m *SysPostPageReq) GetNeedSearch() interface{} { return *m }
```
`type` 可选:`exact` `iexact` `contains` `gt` `gte` `lt` `lte` `order` `left`(联表)。
## Model
```go
type SysPost struct {
PostId int `gorm:"primaryKey;autoIncrement" json:"postId"`
// ... 业务字段
models.ControlBy // CreateBy / UpdateBy
models.ModelTime // CreatedAt / UpdatedAt / DeletedAt
}
func (SysPost) TableName() string { return "sys_post" }
```
`TableName()` 必须显式声明(GORM 配置了 `SingularTable`,不会自动推导复数)。
## 公共契约面
第三方应用(`app/` 下的业务模块)可以稳定依赖哪些包、路由与迁移怎么注册、
哪些约束是硬的,见 `docs/contract.md`。
两条与主仓贡献者直接相关的:
- **`common/`、`core/` 不得 import `app/`** —— `make checksilent` 在 CI 里守着,违反即红。
- **注册类 API(`AppRouters` / `sdk.Runtime.SetAppRouters` / `migration.ForApp`)
只允许在 `init()` 中调用** —— 注册期靠 Go 的包初始化顺序保证无并发写,
core 侧的 setter 没有加锁。
## 路由注册
通过 `init()` 自注册,不在中心文件手工添加:
```go
func init() { routerCheckRole = append(routerCheckRole, registerSysPostRouter) }
func registerSysPostRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := apis.SysPost{}
r := v1.Group("/post").
Use(authMiddleware.MiddlewareFunc()).
Use(middleware.AuthCheckRole()). // Casbin 鉴权
Use(actions.PermissionAction()) // 注入数据权限
{ r.GET("", api.GetPage); r.POST("", api.Insert); /* ... */ }
}
```
新增路由文件后,需确认 `cmd/api/` 中已用 `_` 导入该包。
## 命名
| 对象 | 规则 | 示例 |
|---|---|---|
| 数据表 | `sys_` 前缀 + 下划线 | `sys_post` |
| API 路径 | `/api/v1/` + kebab-case | `/api/v1/sys-user` |
| DTO | `{Model}{Action}Req` | `SysPostPageReq` |
| 权限标识 | `模块:资源:操作` | `admin:sysPost:add` |
权限标识需与前端 `v-permisaction` 一致,并写入 `sys_menu` 种子数据——完整可运行的
参照见 `cmd/migrate/migration/version/1786700001000_demo_menu.go`(sys_api /
sys_menu / sys_menu_api_rule / casbin_rule 四张表如何配齐,用的是幂等 upsert,
可以直接照抄结构)。
## Swagger
Handler 必须带完整注解,`go generate` 会据此生成文档:
```go
// @Summary 岗位列表
// @Tags 岗位
// @Success 200 {object} response.Response
// @Router /api/v1/post [get]
// @Security Bearer
```
## 本地运行
**配置 `driver: sqlite3` 时必须带构建标签**,否则启动即 panic:
```bash
go run -tags sqlite3 . migrate -c config/settings.sqlite.yml
go run -tags sqlite3 . server -c config/settings.sqlite.yml
```
原因:`common/database/open.go` 带 `//go:build !sqlite3`,不加标签时编进的是
不含 sqlite3 的版本,`opens["sqlite3"]` 为 nil,调用时在 nil 函数上崩溃。
报错信息不会提到构建标签,容易误判成环境损坏。MySQL / PostgreSQL 无此问题。
对应 `Makefile` 的 `build-sqlite` 目标。
## 数据库迁移
文件名前 13 位为时间戳版本号。**已执行过的迁移文件不可修改** ——
`sys_migration` 表按版本号去重,改动不会重跑,只能新增一个迁移来修正。
放哪个目录取决于身份:
| 目录 | 用途 | 是否入库 |
|---|---|---|
| `version/` | 框架自带迁移,随仓库分发给所有使用者 | 是 |
| `version-local/` | 使用者自己项目的迁移 | 否(已在 `.gitignore`) |
**向本仓库提交迁移必须放 `version/`** —— 放进 `version-local/` 会被忽略掉,
`git status` 看不到,PR 里也不会出现。两个目录的包名分别是 `version` 与
`version_local`(后者与目录名不一致,因为标识符不能含连字符)。
### 写种子数据用哪个 models 包
`1786700003000` 之后新增的迁移,**种子数据要用 `app/` 下的运行时模型**
(如 `app/admin/models.SysApi`、`SysMenu`),**不要用 `cmd/migrate/migration/models`**。
后者的 `ModelTime` 声明的是可空的 `gorm.DeletedAt`,这对它之前的迁移是对的(那正是
当时列的形状),转换之后就不再成立,两个方向都会出问题:
- **写**:往 NOT NULL 列里塞 NULL,第一条 insert 就 `NOT NULL constraint failed`
- **读**:GORM 拼 `WHERE deleted_at IS NULL`,而活跃行存的是 `0`,静默查不到——
照抄 `demo_menu.go` 的授权段落会因此跳过授权,菜单建好、权限没授、迁移仍记为成功
干净库跑不出这个问题,今天所有用该包的迁移都排在转换之前。完整推导见
`schema_coverage_test.go` 里 `TestPostConversionMigrationsAvoidFrozenSeedModels`
的注释,那个测试也守着这条边界。
## 静默失败校验
`make checksilent` 检查六类**不报错、不记日志、行为悄悄变得不对**的问题,
CI 会跑,命中 ERROR 即失败:
| 检查 | 级别 | 静默后果 |
|---|---|---|
| `modeltime-mix` | ERROR | 两个 `ModelTime` 混用,整张表查不到数据 |
| `menu-sort-overflow` | ERROR | 菜单 `sort` 超 127,MySQL tinyint 拒绝写入,迁移中断 |
| `config-value-truncation` | ERROR | `sys_config.config_value` 超 255 字符被静默截断 |
| `menu-id-collision` | ERROR | 两个模块硬编码同一菜单 ID,互相覆盖 |
| `contract-import-boundary` | ERROR | 契约包 import `app/`,应用无法独立编译 |
| `menu-name-mismatch` | WARN | 菜单名与前端组件 `name` 不一致,keep-alive 缓存静默失效 |
最后一条要跨仓库比对,只能做正则启发式,因此是 WARN,**不影响退出码**,
且默认跳过;要跑它得指定前端目录:
```bash
make checksilent UI_DIR=../go-admin-ui/src
```
升级门槛:连续 2 个发版周期零误报后转为 ERROR。
## 提交规范
格式 `type+emoji: 描述`:
`feat✨` `fix🐛` `style💄` `docs📝` `perf👌` `test✅` `refactor🎨` `chore🔧`
一个提交只做一件事。改动跨越多个语义时拆分提交,不要混在一起。
## 红线
- 不使用全局 DB 变量,一律用 `e.Orm`(来自请求上下文,多租户依赖它)
- 不在 Service 中引用 `gin.Context`
- 生产部署前确认 `mode: prod` 且已修改 `jwt.secret`(dev 模式下 token 几乎不过期)
- 不提交 `config/settings.yml` 中的真实凭据
+13 -21
View File
@@ -1,26 +1,18 @@
FROM golang:alpine as builder
MAINTAINER lwnmengjing
ENV GOPROXY https://goproxy.cn/
WORKDIR /go/release
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
RUN apk update && apk add tzdata
COPY go.mod ./go.mod
RUN go mod download
COPY . .
RUN pwd && ls
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -a -installsuffix cgo -o go-admin .
FROM alpine
COPY --from=builder /go/release/go-admin /
# ENV GOPROXY https://goproxy.cn/
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
RUN apk update --no-cache
RUN apk add --update gcc g++ libc6-compat
RUN apk add --no-cache ca-certificates
RUN apk add --no-cache tzdata
ENV TZ Asia/Shanghai
COPY ./main /main
COPY ./config/settings.demo.yml /config/settings.yml
COPY ./go-admin-db.db /go-admin-db.db
EXPOSE 8000
CMD ["/go-admin","server","-c", "/config/settings.yml"]
RUN chmod +x /main
CMD ["/main","server","-c", "/config/settings.yml"]
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2020 wenjianzhang
Copyright (c) 2026 go-admin-team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+63 -5
View File
@@ -2,13 +2,71 @@ PROJECT:=go-admin
.PHONY: build
build:
CGO_ENABLED=0 go build -o go-admin main.go
CGO_ENABLED=0 go build -ldflags="-w -s" -a -installsuffix "" -o go-admin .
# make build-linux
build-linux:
@docker build -t go-admin:latest .
@echo "build successful"
build-sqlite:
go build -tags sqlite3 -o go-admin main.go
#.PHONY: test
#test:
# go test -v ./... -cover
go build -tags sqlite3 -ldflags="-w -s" -a -installsuffix -o go-admin .
# make run
run:
# delete go-admin-api container
@if [ $(shell docker ps -aq --filter name=go-admin --filter publish=8000) ]; then docker rm -f go-admin; fi
# 启动方法一 run go-admin-api container docker-compose 启动方式
# 进入到项目根目录 执行 make run 命令
@docker-compose up -d
# 启动方式二 docker run 这里注意-v挂载的宿主机的地址改为部署时的实际绝对路径
#@docker run --name=go-admin -p 8000:8000 -v /home/code/go/src/go-admin/go-admin/config:/go-admin-api/config -v /home/code/go/src/go-admin/go-admin-api/static:/go-admin/static -v /home/code/go/src/go-admin/go-admin/temp:/go-admin-api/temp -d --restart=always go-admin:latest
@echo "go-admin service is running..."
# delete Tag=<none> 的镜像
@docker image prune -f
@docker ps -a | grep "go-admin"
stop:
# delete go-admin-api container
@if [ $(shell docker ps -aq --filter name=go-admin --filter publish=8000) ]; then docker-compose down; fi
#@if [ $(shell docker ps -aq --filter name=go-admin --filter publish=8000) ]; then docker rm -f go-admin; fi
#@echo "go-admin stop success"
# -race is worth the extra minute here: common/actions reuses model instances
# across concurrent requests, so a Generate() that returns in place instead of
# a copy leaks data between them - and that is invisible to a single-threaded
# test run.
.PHONY: test
test:
go test -race -cover ./...
# Reports the failures that do not announce themselves - see
# tools/checksilent. Exits non-zero on an ERROR; the one WARN-level check
# prints and does not fail the build.
#
# Pass UI_DIR to enable the cross-repository menu-name check, which is skipped
# without it: make checksilent UI_DIR=../go-admin-ui/src
.PHONY: checksilent
checksilent:
ifdef UI_DIR
go run ./tools/checksilent -ui-dir $(UI_DIR)
else
go run ./tools/checksilent
endif
#.PHONY: docker
#docker:
# docker build . -t go-admin:latest
# make deploy
deploy:
#@git checkout master
#@git pull origin master
make build-linux
make run
+122 -59
View File
@@ -1,27 +1,30 @@
# go-admin
<img align="right" width="320" src="https://gitee.com/mydearzwj/image/raw/master/img/go-admin.svg">
<img align="right" width="320" src="https://doc-image.zhangwj.com/img/go-admin.svg">
[![Build Status](https://github.com/wenjianzhang/go-admin/workflows/build/badge.svg)](https://github.com/go-admin-team/go-admin)
[![Build Status](https://github.com/go-admin-team/go-admin/actions/workflows/go.yml/badge.svg?branch=master)](https://github.com/go-admin-team/go-admin)
[![Release](https://img.shields.io/github/release/go-admin-team/go-admin.svg?style=flat-square)](https://github.com/go-admin-team/go-admin/releases)
[![License](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/go-admin-team/go-admin)
[![License](https://img.shields.io/github/license/go-admin-team/go-admin.svg)](https://github.com/go-admin-team/go-admin)
[English](https://github.com/go-admin-team/go-admin/blob/master/README.md) | 简体中文
[English](https://github.com/go-admin-team/go-admin/blob/master/README.md) | 简体中文 | [繁體中文](https://github.com/go-admin-team/go-admin/blob/master/README.zh-TW.md) | [日本語](https://github.com/go-admin-team/go-admin/blob/master/README.ja-JP.md)
基于Gin + Vue + Element UI OR Arco Design OR Ant Design的前后端分离权限管理系统,系统初始化极度简单,只需要配置文件中,修改数据库连接,系统支持多指令操作,迁移指令可以让初始化数据库信息变得更简单,服务指令可以很简单的启动api服务
基于Gin + Vue + Element UI的前后端分离权限管理系统,系统初始化极度简单,只需要配置文件中,修改数据库连接,系统支持多指令操作,迁移指令可以让初始化数据库信息变得更简单,服务指令可以很简单的启动api服务
[在线文档](https://doc.go-admin.dev)
[github在线文档](https://wenjianzhang.github.io)
[gitee在线文档](http://mydearzwj.gitee.io/go-admin-doc/)
[在线文档](https://www.go-admin.pro)
[前端项目](https://github.com/go-admin-team/go-admin-ui)
[视频教程](https://space.bilibili.com/565616721/channel/detail?cid=125737)
## 🎬 在线体验
Element Plus vue3 体验:[https://vue.go-admin.pro](https://vue.go-admin.pro/#/login)
> ⚠️⚠️⚠️ 账号 / 密码: admin / 123456
antd 体验(go-admin-pro):[https://antd.go-admin.pro](https://antd.go-admin.pro/)
> ⚠️⚠️⚠️ 账号 / 密码: admin / 123456
## ✨ 特性
- 遵循 RESTful API 设计规范
@@ -34,7 +37,7 @@
- 支持 Swagger 文档(基于swaggo)
- 基于 GORM 的数据库存储,可扩展多种类型数据库
- 基于 GORM 的数据库存储,可扩展多种类型数据库
- 配置文件简单的模型映射,快速能够得到想要的配置
@@ -44,11 +47,13 @@
- 多指令模式
- TODO: 单元测试
- 多租户的支持
- TODO: 单元测试
## 🎁 内置
1. 多租户:系统默认支持多租户,按库分离,一个库一个租户。
1. 用户管理:用户是系统操作者,该功能主要完成系统用户配置。
2. 部门管理:配置系统组织机构(公司、部门、小组),树结构展现支持数据权限。
3. 岗位管理:配置系统用户所属担任职务。
@@ -63,6 +68,7 @@
1. 表单构建:自定义页面样式,拖拉拽实现页面布局。
1. 服务监控:查看一些服务器的基本信息。
1. 内容管理:demo功能,下设分类管理、内容管理。可以参考使用方便快速入门。
1. 定时任务:自动化任务,目前支持接口调用和函数调用。
## 准备工作
@@ -72,11 +78,11 @@
### 轻松实现go-admin写出第一个应用 - 文档教程
[步骤一 - 基础内容介绍](http://doc.zhangwj.com/go-admin-site/guide/intro/tutorial01.html)
[步骤一 - 基础内容介绍](https://www.go-admin.pro/guide/intro/tutorial01.html)
[步骤二 - 实际应用 - 编写增删改查](http://doc.zhangwj.com/go-admin-site/guide/intro/tutorial02.html)
[步骤二 - 实际应用 - 编写增删改查](https://www.go-admin.pro/guide/intro/tutorial02.html)
### 手把手教你从入门到放弃 - 视频教程
### 手把手教你从入门到放弃 - 视频教程
[如何启动go-admin](https://www.bilibili.com/video/BV1z5411x7JG)
@@ -94,11 +100,18 @@
[go-admin数据权限使用说明](https://www.bilibili.com/video/BV1LK4y1s71e) [必看]
**如有问题请先看上述使用文档和文章,若不能满足,欢迎 issue 和 pr ,视频教程和文档持续更新中**
## 📦 本地开发
### 环境要求
go 1.26.5
node版本: v22+(推荐 v24 LTS)
包管理器: pnpm v9+(UI 项目使用 pnpm)
### 开发目录创建
```bash
@@ -121,7 +134,6 @@ git clone https://github.com/go-admin-team/go-admin-ui.git
```
### 启动说明
#### 服务端启动说明
@@ -130,19 +142,22 @@ git clone https://github.com/go-admin-team/go-admin-ui.git
# 进入 go-admin 后端项目
cd ./go-admin
# 更新整理依赖
go mod tidy
# 编译项目
go build
# 修改配置
# 文件路径 go-admin/config/settings.yml
vi ./config/setting.yml
vi ./config/settings.yml
# 1. 配置文件中修改数据库信息
# 注意: settings.database 下对应的配置数据
# 2. 确认log路径
```
:::tip ⚠️注意 在windows环境如果没有安装中CGO,会出现这个问题;
⚠️注意 在windows环境如果没有安装中CGO,会出现这个问题;
```bash
E:\go-admin>go build
@@ -158,19 +173,18 @@ D:\Code\go-admin>go build
cgo: exec gcc: exec: "gcc": executable file not found in %PATH%
```
[解决cgo问题进入](https://doc.go-admin.dev/guide/other/faq.html#_5-cgo-exec-missing-cc-exec-missing-cc-file-does-not-exist)
[解决cgo问题进入](https://www.go-admin.pro/zh-CN/guide/faq#cgo-%E7%9A%84%E9%97%AE%E9%A2%98)
:::
#### 初始化数据库,以及服务启动
``` bash
# 首次配置需要初始化数据库资源信息
# macOS or linux 下使用
$ ./go-admin migrate -c=config/settings.dev.yml
$ ./go-admin migrate -c config/settings.dev.yml
# ⚠️注意:windows 下使用
$ go-admin.exe migrate -c=config/settings.dev.yml
$ go-admin.exe migrate -c config/settings.dev.yml
# 启动项目,也可以用IDE进行调试
@@ -182,6 +196,13 @@ $ ./go-admin server -c config/settings.yml
$ go-admin.exe server -c config/settings.yml
```
#### sys_api 表的数据如何添加
在项目启动时,使用`-a true` 系统会自动添加缺少的接口数据
```bash
./go-admin server -c config/settings.yml -a true
```
#### 使用docker 编译启动
```shell
@@ -193,8 +214,6 @@ docker build -t go-admin .
docker run --name go-admin -p 8000:8000 -v /config/settings.yml:/config/settings.yml -d go-admin-server
```
#### 文档生成
```bash
@@ -202,6 +221,7 @@ go generate
```
#### 交叉编译
```bash
# windows
env GOOS=windows GOARCH=amd64 go build main.go
@@ -214,45 +234,83 @@ env GOOS=linux GOARCH=amd64 go build main.go
### UI交互端启动说明
```bash
# 安装依赖
npm install
# 安装 pnpm(若未安装)
npm install -g pnpm
# 建议不要直接使用 cnpm 安装依赖,会有各种诡异的 bug。可以通过如下操作解决 npm 下载速度慢的问题
npm install --registry=https://registry.npm.taobao.org
# 安装依赖
pnpm install
# 国内网络可指定镜像源加速
pnpm install --registry=https://registry.npmmirror.com
# 启动服务
npm run dev
pnpm dev
```
## 🎬 在线体验
> admin / 123456
演示地址:[http://www.go-admin.dev](http://www.go-admin.dev/#/login)
## 📨 互动
<table>
<tr>
<tr>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq.png" width="200px"></td>
<td><img src="https://doc-image.zhangwj.com/img/qrcode_for_gh_b798dc7db30c_258.jpg" width="180px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq2.png" width="200px"></td>
<td><a href="https://space.bilibili.com/565616721">wenjianzhang</a></td>
</tr>
<tr>
<td>微信</td>
<td>此群已满</td>
<td>公众号🔥🔥🔥</td>
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=0f2bf59f5f2edec6a4550c364242c0641f870aa328e468c4ee4b7dbfb392627b"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流乙号" title="go-admin技术交流乙号"></a></td>
<td>哔哩哔哩🔥🔥🔥</td>
</tr>
</table>
## 💎 主要成员
<a href="https://github.com/wenjianzhang"> <img src="https://avatars.githubusercontent.com/u/3890175?s=460&u=20eac63daef81588fbac611da676b99859319251&v=4" width="80px"></a>
<a href="https://github.com/lwnmengjing"> <img src="https://avatars.githubusercontent.com/u/12806223?s=400&u=a89272dce50100b77b4c0d5c81c718bf78ebb580&v=4" width="80px"></a>
<a href="https://github.com/chengxiao"> <img src="https://avatars.githubusercontent.com/u/1379545?s=460&u=557da5503d0ac4a8628df6b4075b17853d5edcd9&v=4" width="80px"></a>
<a href="https://github.com/bing127"> <img src="https://avatars.githubusercontent.com/u/31166183?s=460&u=c085bff88df10bb7676c8c0351ba9dcd031d1fb3&v=4" width="80px"></a>
## 💎 贡献者
<span style="margin: 0 5px;" ><a href="https://github.com/wenjianzhang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3890175?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/G-Akiraka" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45746659?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/lwnmengjing" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/12806223?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bing127" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31166183?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/chengxiao" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1379545?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NightFire0307" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19854086?v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/appleboy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/21979?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/ninstein" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/580303?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/kikiyou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/17959053?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/horizonzy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/22524871?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Cassuis" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/48005724?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/hqcchina" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/5179057?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/nodece" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16235121?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stephenzhang0713" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/18169290?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhouxixi-dev" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/100399679?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Jalins" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31172582?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wkf928592" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6063351?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxxiong6" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6983441?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Silicon-He" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/52478309?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/GizmoOAO" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20385106?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bestgopher" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/36840497?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxb1207" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20775558?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/misakichan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16569274?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhuxuyang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19301024?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/mss-boot" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/109259065?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/AuroraV" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/37330199?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Vingurzhou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/57127283?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/haimait" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/40926384?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zyd" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3446278?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/infnan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/38274826?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/d1y" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45585937?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/qlijin" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/515900?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/logtous
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/88697234?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stepway
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/9927079?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NaturalGao
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/43291304?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/DemoLiang
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/23476007?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/jfcg
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1410597?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Nicole0724
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/10487328?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
## JetBrains 开源证书支持
@@ -260,18 +318,22 @@ npm run dev
<a href="https://www.jetbrains.com/?from=kubeadm-ha" target="_blank"><img src="https://raw.githubusercontent.com/panjf2000/illustrations/master/jetbrains/jetbrains-variant-4.png" width="250" align="middle"/></a>
## 🤝 特别感谢
1. [chengxiao](https://github.com/chengxiao)
2. [gin](https://github.com/gin-gonic/gin)
2. [casbin](https://github.com/casbin/casbin)
2. [spf13/viper](https://github.com/spf13/viper)
2. [gorm](https://github.com/jinzhu/gorm)
2. [gin-swagger](https://github.com/swaggo/gin-swagger)
2. [jwt-go](https://github.com/dgrijalva/jwt-go)
2. [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)
2. [ruoyi-vue](https://gitee.com/y_project/RuoYi-Vue)
2. [form-generator](https://github.com/JakHuang/form-generator)
1. [ant-design](https://github.com/ant-design/ant-design)
2. [ant-design-pro](https://github.com/ant-design/ant-design-pro)
2. [arco-design](https://github.com/arco-design/arco-design)
2. [arco-design-pro](https://github.com/arco-design/arco-design-pro)
4. [gin](https://github.com/gin-gonic/gin)
5. [casbin](https://github.com/casbin/casbin)
6. [spf13/viper](https://github.com/spf13/viper)
7. [gorm](https://github.com/go-gorm/gorm)
8. [gin-swagger](https://github.com/swaggo/gin-swagger)
9. [golang-jwt](https://github.com/golang-jwt/jwt)
10. [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)
11. [ruoyi-vue](https://gitee.com/y_project/RuoYi-Vue)
12. [form-generator](https://github.com/JakHuang/form-generator)
## 🤟 打赏
@@ -280,10 +342,11 @@ npm run dev
<img class="no-margin" src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/pay.png" height="200px" >
## 🤝 链接
[Go开发者成长线路图](http://www.golangroadmap.com/)
- [mss-boot-io](https://docs.mss-boot-io.top/)
## 🔑 License
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
Copyright (c) 2020 wenjianzhang
Copyright (c) 2026 wenjianzhang
+350
View File
@@ -0,0 +1,350 @@
# go-admin
<img align="right" width="320" src="https://doc-image.zhangwj.com/img/go-admin.svg">
[![Build Status](https://github.com/go-admin-team/go-admin/actions/workflows/go.yml/badge.svg?branch=master)](https://github.com/go-admin-team/go-admin)
[![Release](https://img.shields.io/github/release/go-admin-team/go-admin.svg?style=flat-square)](https://github.com/go-admin-team/go-admin/releases)
[![License](https://img.shields.io/github/license/go-admin-team/go-admin.svg)](https://github.com/go-admin-team/go-admin)
[English](https://github.com/go-admin-team/go-admin/blob/master/README.md) | [简体中文](https://github.com/go-admin-team/go-admin/blob/master/README.Zh-cn.md) | [繁體中文](https://github.com/go-admin-team/go-admin/blob/master/README.zh-TW.md) | 日本語
Gin + Vue + Element UI / Arco Design / Ant Design による、フロントエンドとバックエンドを分離した権限管理システムです。初期化は非常に簡単で、設定ファイルのデータベース接続情報を変更するだけで動作します。複数のコマンドに対応しており、マイグレーションコマンドでデータベースの初期化が容易になり、サーバーコマンドで API を手軽に起動できます。
[オンラインドキュメント](https://www.go-admin.pro)
[フロントエンドプロジェクト](https://github.com/go-admin-team/go-admin-ui)
[動画チュートリアル](https://space.bilibili.com/565616721/channel/detail?cid=125737)
## 🎬 オンラインデモ
Element Plus vue3 デモ:[https://vue.go-admin.pro](https://vue.go-admin.pro/#/login)
> ⚠️⚠️⚠️ アカウント / パスワード: admin / 123456
antd デモ(go-admin-pro):[https://antd.go-admin.pro](https://antd.go-admin.pro/)
> ⚠️⚠️⚠️ アカウント / パスワード: admin / 123456
## ✨ 特徴
- RESTful API の設計規約に準拠
- GIN WEB API フレームワークをベースに、豊富なミドルウェアを提供(ユーザー認証、CORS、アクセスログ、トレース ID など)
- Casbin による RBAC アクセス制御モデル
- JWT 認証
- Swagger ドキュメントに対応(swaggo ベース)
- GORM によるデータベース永続化、複数種類のデータベースに拡張可能
- 設定ファイルからモデルへの単純なマッピングで、必要な設定をすぐに取得
- コード生成ツール
- フォームビルダー
- マルチコマンド方式
- マルチテナント対応
- TODO: ユニットテスト
## 🎁 標準機能
1. マルチテナント:デフォルトで対応。データベース単位で分離し、1 データベースにつき 1 テナント。
1. ユーザー管理:システムの操作者であるユーザーの設定を行います。
2. 部門管理:組織構造(会社・部門・グループ)を設定します。ツリー構造で表示し、データ権限に対応します。
3. 役職管理:ユーザーが担当する職務を設定します。
4. メニュー管理:メニュー、操作権限、ボタン権限識別子、API 権限などを設定します。
5. ロール管理:ロールへのメニュー権限の割り当て、および組織単位でのデータ範囲権限の設定を行います。
6. 辞書管理:システム内で頻繁に使う固定的なデータを管理します。
7. パラメータ管理:よく使うパラメータを動的に設定します。
8. 操作ログ:正常系の操作ログと異常情報のログを記録・検索します。
9. ログインログ:ログイン履歴を記録・検索します。ログイン異常も含みます。
1. API ドキュメント:業務コードから API ドキュメントを自動生成します。
1. コード生成:テーブル定義から CRUD 業務を生成します。すべて画面上で操作でき、基本的な業務をコードなしで実現できます。
1. フォームビルダー:ページのスタイルをカスタマイズし、ドラッグ&ドロップでレイアウトを作成します。
1. サービス監視:サーバーの基本情報を確認します。
1. コンテンツ管理:デモ機能。カテゴリ管理とコンテンツ管理を含み、入門用の参考実装として利用できます。
1. スケジュールタスク:自動実行タスク。現在は API 呼び出しと関数呼び出しに対応しています。
## 事前準備
ローカルに [go] [gin] [node](http://nodejs.org/) と [git](https://git-scm.com/) をインストールしてください。
ダウンロードから使いこなすまでを解説した動画とドキュメントのチュートリアルを用意しています。本プロジェクトを試す前に、まずこれらに目を通すことを強くおすすめします。
### go-admin で最初のアプリケーションを作る - ドキュメント
[ステップ 1 - 基礎の紹介](https://www.go-admin.pro/guide/intro/tutorial01.html)
[ステップ 2 - 実践 - CRUD を書く](https://www.go-admin.pro/guide/intro/tutorial02.html)
### 動画チュートリアル
[go-admin の起動方法](https://www.bilibili.com/video/BV1z5411x7JG)
[生成ツールで業務を手軽に実装する](https://www.bilibili.com/video/BV1Dg4y1i79D)
[v1.1.0 のコード生成ツール](https://www.bilibili.com/video/BV1N54y1i71P) [応用]
[マルチコマンドでの起動方法と IDE 設定](https://www.bilibili.com/video/BV1Fg4y1q7ph)
[go-admin のメニュー設定](https://www.bilibili.com/video/BV1Wp4y1D715) [必見]
[メニュー情報と API 情報の設定方法](https://www.bilibili.com/video/BV1zv411B7nG) [必見]
[go-admin の権限設定](https://www.bilibili.com/video/BV1rt4y197d3) [必見]
[go-admin のデータ権限](https://www.bilibili.com/video/BV1LK4y1s71e) [必見]
**不明点はまず上記のドキュメントと記事をご確認ください。解決しない場合は issue や pr をお寄せください。動画とドキュメントは継続的に更新しています**
## 📦 ローカル開発
### 動作要件
go 1.26.5
node バージョン: v22 以上(v24 LTS 推奨)
パッケージマネージャー: pnpm v9 以上(UI プロジェクトは pnpm を使用)
### 開発ディレクトリの作成
```bash
# 開発ディレクトリを作成
mkdir goadmin
cd goadmin
```
### コードの取得
> 重要:2 つのプロジェクトは同じディレクトリに配置してください。
```bash
# バックエンドのコードを取得
git clone https://github.com/go-admin-team/go-admin.git
# フロントエンドのコードを取得
git clone https://github.com/go-admin-team/go-admin-ui.git
```
### 起動方法
#### サーバーの起動
```bash
# go-admin バックエンドプロジェクトへ移動
cd ./go-admin
# 依存関係を整理
go mod tidy
# ビルド
go build
# 設定を変更
# ファイルパス go-admin/config/settings.yml
vi ./config/settings.yml
# 1. 設定ファイル内のデータベース情報を変更
# 注意: settings.database 配下の設定項目
# 2. log のパスを確認
```
⚠️注意 Windows 環境で CGO が未導入の場合、次のエラーが発生します。
```bash
E:\go-admin>go build
# github.com/mattn/go-sqlite3
cgo: exec /missing-cc: exec: "/missing-cc": file does not exist
```
or
```bash
D:\Code\go-admin>go build
# github.com/mattn/go-sqlite3
cgo: exec gcc: exec: "gcc": executable file not found in %PATH%
```
[cgo の問題の解決方法はこちら](https://www.go-admin.pro/zh-CN/guide/faq#cgo-%E7%9A%84%E9%97%AE%E9%A2%98)
#### データベースの初期化とサービス起動
``` bash
# 初回はデータベースのリソース情報を初期化する必要があります
# macOS または linux の場合
$ ./go-admin migrate -c config/settings.dev.yml
# ⚠️注意: windows の場合
$ go-admin.exe migrate -c config/settings.dev.yml
# プロジェクトを起動します。IDE からデバッグ実行することもできます
# macOS または linux の場合
$ ./go-admin server -c config/settings.yml
# ⚠️注意: windows の場合
$ go-admin.exe server -c config/settings.yml
```
#### sys_api テーブルへのデータ追加方法
起動時に `-a true` を付けると、不足している API データが自動的に追加されます。
```bash
./go-admin server -c config/settings.yml -a true
```
#### docker でのビルドと起動
```shell
# イメージをビルド
docker build -t go-admin .
# コンテナを起動します。1 つ目の go-admin はコンテナ名、2 つ目はイメージ名です
# -v は設定ファイルのマウント ローカルパス:コンテナ内パス
docker run --name go-admin -p 8000:8000 -v /config/settings.yml:/config/settings.yml -d go-admin-server
```
#### ドキュメント生成
```bash
go generate
```
#### クロスコンパイル
```bash
# windows
env GOOS=windows GOARCH=amd64 go build main.go
# or
# linux
env GOOS=linux GOARCH=amd64 go build main.go
```
### UI 側の起動方法
```bash
# pnpm をインストール(未導入の場合)
npm install -g pnpm
# 依存関係をインストール
pnpm install
# 中国本土のネットワークではミラーを指定すると高速化できます
pnpm install --registry=https://registry.npmmirror.com
# 開発サーバーを起動
pnpm dev
```
## 📨 コミュニティ
<table>
<tr>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
<td><img src="https://doc-image.zhangwj.com/img/qrcode_for_gh_b798dc7db30c_258.jpg" width="180px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq2.png" width="200px"></td>
<td><a href="https://space.bilibili.com/565616721">wenjianzhang</a></td>
</tr>
<tr>
<td>微信</td>
<td>公众号🔥🔥🔥</td>
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=0f2bf59f5f2edec6a4550c364242c0641f870aa328e468c4ee4b7dbfb392627b"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流乙号" title="go-admin技术交流乙号"></a></td>
<td>哔哩哔哩🔥🔥🔥</td>
</tr>
</table>
## 💎 コントリビューター
<span style="margin: 0 5px;" ><a href="https://github.com/wenjianzhang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3890175?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/G-Akiraka" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45746659?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/lwnmengjing" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/12806223?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bing127" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31166183?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/chengxiao" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1379545?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NightFire0307" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19854086?v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/appleboy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/21979?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/ninstein" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/580303?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/kikiyou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/17959053?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/horizonzy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/22524871?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Cassuis" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/48005724?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/hqcchina" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/5179057?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/nodece" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16235121?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stephenzhang0713" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/18169290?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhouxixi-dev" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/100399679?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Jalins" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31172582?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wkf928592" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6063351?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxxiong6" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6983441?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Silicon-He" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/52478309?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/GizmoOAO" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20385106?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bestgopher" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/36840497?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxb1207" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20775558?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/misakichan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16569274?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhuxuyang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19301024?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/mss-boot" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/109259065?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/AuroraV" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/37330199?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Vingurzhou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/57127283?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/haimait" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/40926384?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zyd" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3446278?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/infnan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/38274826?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/d1y" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45585937?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/qlijin" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/515900?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/logtous
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/88697234?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stepway
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/9927079?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NaturalGao
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/43291304?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/DemoLiang
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/23476007?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/jfcg
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1410597?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Nicole0724
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/10487328?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
## JetBrains のオープンソースライセンス支援
`go-admin` は一貫して JetBrains 社の GoLand 統合開発環境で開発されています。**free JetBrains Open Source license(s)** による正規の無償ライセンス提供に、この場を借りて感謝を申し上げます。
<a href="https://www.jetbrains.com/?from=kubeadm-ha" target="_blank"><img src="https://raw.githubusercontent.com/panjf2000/illustrations/master/jetbrains/jetbrains-variant-4.png" width="250" align="middle"/></a>
## 🤝 謝辞
1. [ant-design](https://github.com/ant-design/ant-design)
2. [ant-design-pro](https://github.com/ant-design/ant-design-pro)
2. [arco-design](https://github.com/arco-design/arco-design)
2. [arco-design-pro](https://github.com/arco-design/arco-design-pro)
4. [gin](https://github.com/gin-gonic/gin)
5. [casbin](https://github.com/casbin/casbin)
6. [spf13/viper](https://github.com/spf13/viper)
7. [gorm](https://github.com/go-gorm/gorm)
8. [gin-swagger](https://github.com/swaggo/gin-swagger)
9. [golang-jwt](https://github.com/golang-jwt/jwt)
10. [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)
11. [ruoyi-vue](https://gitee.com/y_project/RuoYi-Vue)
12. [form-generator](https://github.com/JakHuang/form-generator)
## 🤟 支援
> このプロジェクトがお役に立ちましたら、作者にジュースを一杯おごる形で応援いただけます :tropical_drink:
<img class="no-margin" src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/pay.png" height="200px" >
## 🤝 関連リンク
- [mss-boot-io](https://docs.mss-boot-io.top/)
## 🔑 License
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
Copyright (c) 2026 wenjianzhang
+95 -33
View File
@@ -1,23 +1,31 @@
# go-admin
<img align="right" width="320" src="https://gitee.com/mydearzwj/image/raw/master/img/go-admin.svg">
<img align="right" width="320" src="https://raw.githubusercontent.com/wenjianzhang/image/203c5930b9ed08d5cf2fcb4516b85e412f8e0e60/img/go-admin.svg">
[![Build Status](https://github.com/wenjianzhang/go-admin/workflows/build/badge.svg)](https://github.com/go-admin-team/go-admin)
[![Build Status](https://github.com/go-admin-team/go-admin/actions/workflows/go.yml/badge.svg?branch=master)](https://github.com/go-admin-team/go-admin)
[![Release](https://img.shields.io/github/release/go-admin-team/go-admin.svg?style=flat-square)](https://github.com/go-admin-team/go-admin/releases)
[![License](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/go-admin-team/go-admin)
[![License](https://img.shields.io/github/license/go-admin-team/go-admin.svg)](https://github.com/go-admin-team/go-admin)
English | [简体中文](https://github.com/go-admin-team/go-admin/blob/master/README.Zh-cn.md)
English | [简体中文](https://github.com/go-admin-team/go-admin/blob/master/README.Zh-cn.md) | [繁體中文](https://github.com/go-admin-team/go-admin/blob/master/README.zh-TW.md) | [日本語](https://github.com/go-admin-team/go-admin/blob/master/README.ja-JP.md)
The front-end and back-end separation authority management system based on Gin + Vue + Element UI is extremely simple to initialize the system. You only need to modify the database connection in the configuration file. The system supports multi-instruction operations. Migration instructions can make it easier to initialize database information. Service instructions It's easy to start the api service.
The front-end and back-end separation authority management system based on Gin + Vue + Element UI OR Arco Design OR Ant Design is extremely simple to initialize the system. You only need to modify the database connection in the configuration file. The system supports multi-instruction operations. Migration instructions can make it easier to initialize database information. Service instructions It's easy to start the api service.
[documentation](https://doc.go-admin.dev)
[documentation](https://www.go-admin.pro)
[Front-end project](https://github.com/go-admin-team/go-admin-ui)
[Video tutorial](https://space.bilibili.com/565616721/channel/detail?cid=125737)
## 🎬 Online Demo
Element Plus vue3 demo:[https://vue.go-admin.pro](https://vue.go-admin.pro/#/login)
> Account / Password: admin / 123456
antd demo (go-admin-pro):[https://antd.go-admin.pro](https://antd.go-admin.pro/)
> Account / Password: admin / 123456
>
## ✨ Feature
- Follow RESTful API design specifications
@@ -68,9 +76,9 @@ At the same time, a series of tutorials including videos and documents are provi
### Easily implement go-admin to write the first application-documentation tutorial
[Step 1 - basic content introduction](http://doc.zhangwj.com/go-admin-site/guide/intro/tutorial01.html)
[Step 1 - basic content introduction](https://www.go-admin.pro/guide/intro/tutorial01.html)
[Step 2 - Practical application - writing database operations](http://doc.zhangwj.com/go-admin-site/guide/intro/tutorial02.html)
[Step 2 - Practical application - writing database operations](https://www.go-admin.pro/guide/intro/tutorial02.html)
### Teach you from getting started to giving up-video tutorial
@@ -94,6 +102,14 @@ At the same time, a series of tutorials including videos and documents are provi
## 📦 Local development
### Environmental requirements
go 1.26.5
nodejs: v22+ (v24 LTS recommended)
package manager: pnpm v9+ (the UI project uses pnpm)
### Development directory creation
```bash
@@ -124,19 +140,22 @@ git clone https://github.com/go-admin-team/go-admin-ui.git
# Enter the go-admin backend project
cd ./go-admin
# Update dependencies
go mod tidy
# Compile the project
go build
# Change setting
# File path go-admin/config/settings.yml
vi ./config/setting.yml
vi ./config/settings.yml
# 1. Modify the database information in the configuration file
# Note: The corresponding configuration data under settings.database
# 2. Confirm the log path
```
:::tip ⚠️Note that this problem will occur if CGO is not installed in the windows environment;
⚠️ Note that this problem will occur if CGO is not installed in the windows10+ environment;
```bash
E:\go-admin>go build
@@ -152,19 +171,17 @@ D:\Code\go-admin>go build
cgo: exec gcc: exec: "gcc": executable file not found in %PATH%
```
[Solve the cgo problem and enter](https://doc.go-admin.dev/guide/other/faq.html#_5-cgo-exec-missing-cc-exec-missing-cc-file-does-not-exist)
:::
[Solve the cgo problem and enter](https://www.go-admin.pro/guide/faq#cgo-%E7%9A%84%E9%97%AE%E9%A2%98)
#### Initialize the database, and start the service
``` bash
# The first configuration needs to initialize the database resource information
# Use under macOS or linux
$ ./go-admin migrate -c=config/settings.dev.yml
$ ./go-admin migrate -c config/settings.dev.yml
# ⚠️Note: Use under windows
$ go-admin.exe migrate -c=config/settings.dev.yml
$ go-admin.exe migrate -c config/settings.dev.yml
# Start the project, you can also use the IDE for debugging
# Use under macOS or linux
@@ -207,38 +224,79 @@ env GOOS=linux GOARCH=amd64 go build main.go
### UI interactive terminal startup instructions
```bash
# Install pnpm if you don't have it
npm install -g pnpm
# Installation dependencies
npm install # or cnpm install
pnpm install
# Start service
npm run dev
pnpm dev
```
## 🎬 Online Demo
> admin / 123456
演示地址:[http://www.go-admin.dev](http://www.go-admin.dev/#/login)
## 📨 Interactive
<table>
<tr>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
<td><img src="https://doc-image.zhangwj.com/img/qrcode_for_gh_b798dc7db30c_258.jpg" width="180px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq2.png" width="200px"></td>
<td><a href="https://space.bilibili.com/565616721">wenjianzhang</a></td>
</tr>
<tr>
<td>Wechat</td>
<td>Wechat公众号🔥🔥🔥</td>
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=0f2bf59f5f2edec6a4550c364242c0641f870aa328e468c4ee4b7dbfb392627b"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流乙号" title="go-admin技术交流乙号"></a></td>
<td>bilibili🔥🔥🔥</td>
</tr>
</table>
## 💎 Members
## 💎 Contributors
<a href="https://github.com/wenjianzhang"> <img src="https://avatars.githubusercontent.com/u/3890175?s=460&u=20eac63daef81588fbac611da676b99859319251&v=4" width="80px"></a>
<a href="https://github.com/lwnmengjing"> <img src="https://avatars.githubusercontent.com/u/12806223?s=400&u=a89272dce50100b77b4c0d5c81c718bf78ebb580&v=4" width="80px"></a>
<a href="https://github.com/chengxiao"> <img src="https://avatars.githubusercontent.com/u/1379545?s=460&u=557da5503d0ac4a8628df6b4075b17853d5edcd9&v=4" width="80px"></a>
<a href="https://github.com/bing127"> <img src="https://avatars.githubusercontent.com/u/31166183?s=460&u=c085bff88df10bb7676c8c0351ba9dcd031d1fb3&v=4" width="80px"></a>
<span style="margin: 0 5px;" ><a href="https://github.com/wenjianzhang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3890175?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/G-Akiraka" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45746659?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/lwnmengjing" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/12806223?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bing127" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31166183?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/chengxiao" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1379545?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NightFire0307" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19854086?v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/appleboy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/21979?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/ninstein" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/580303?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/kikiyou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/17959053?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/horizonzy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/22524871?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Cassuis" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/48005724?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/hqcchina" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/5179057?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/nodece" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16235121?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stephenzhang0713" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/18169290?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhouxixi-dev" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/100399679?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Jalins" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31172582?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wkf928592" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6063351?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxxiong6" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6983441?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Silicon-He" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/52478309?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/GizmoOAO" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20385106?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bestgopher" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/36840497?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxb1207" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20775558?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/misakichan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16569274?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhuxuyang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19301024?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/mss-boot" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/109259065?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/AuroraV" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/37330199?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Vingurzhou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/57127283?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/haimait" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/40926384?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zyd" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3446278?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/infnan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/38274826?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/d1y" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45585937?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/qlijin" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/515900?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/logtous
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/88697234?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stepway
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/9927079?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NaturalGao
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/43291304?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/DemoLiang
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/23476007?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/jfcg
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1410597?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Nicole0724
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/10487328?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
@@ -250,13 +308,17 @@ The `go-admin` project has always been developed in the GoLand integrated develo
## 🤝 Thanks
1. [chengxiao](https://github.com/chengxiao)
1. [ant-design](https://github.com/ant-design/ant-design)
2. [ant-design-pro](https://github.com/ant-design/ant-design-pro)
2. [arco-design](https://github.com/arco-design/arco-design)
2. [arco-design-pro](https://github.com/arco-design/arco-design-pro)
2. [gin](https://github.com/gin-gonic/gin)
2. [casbin](https://github.com/casbin/casbin)
2. [spf13/viper](https://github.com/spf13/viper)
2. [gorm](https://github.com/jinzhu/gorm)
2. [gorm](https://github.com/go-gorm/gorm)
2. [gin-swagger](https://github.com/swaggo/gin-swagger)
2. [jwt-go](https://github.com/dgrijalva/jwt-go)
2. [golang-jwt](https://github.com/golang-jwt/jwt)
2. [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)
2. [ruoyi-vue](https://gitee.com/y_project/RuoYi-Vue)
2. [form-generator](https://github.com/JakHuang/form-generator)
@@ -268,10 +330,10 @@ The `go-admin` project has always been developed in the GoLand integrated develo
<img class="no-margin" src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/pay.png" height="200px" >
## 🤝 Link
[Go developer growth roadmap](http://www.golangroadmap.com/)
- [mss-boot-io](https://docs.mss-boot-io.top/)
## 🔑 License
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
Copyright (c) 2020 wenjianzhang
Copyright (c) 2026 wenjianzhang
+350
View File
@@ -0,0 +1,350 @@
# go-admin
<img align="right" width="320" src="https://doc-image.zhangwj.com/img/go-admin.svg">
[![Build Status](https://github.com/go-admin-team/go-admin/actions/workflows/go.yml/badge.svg?branch=master)](https://github.com/go-admin-team/go-admin)
[![Release](https://img.shields.io/github/release/go-admin-team/go-admin.svg?style=flat-square)](https://github.com/go-admin-team/go-admin/releases)
[![License](https://img.shields.io/github/license/go-admin-team/go-admin.svg)](https://github.com/go-admin-team/go-admin)
[English](https://github.com/go-admin-team/go-admin/blob/master/README.md) | [简体中文](https://github.com/go-admin-team/go-admin/blob/master/README.Zh-cn.md) | 繁體中文 | [日本語](https://github.com/go-admin-team/go-admin/blob/master/README.ja-JP.md)
基於 Gin + Vue + Element UI OR Arco Design OR Ant Design 的前後端分離權限管理系統。系統初始化極為簡單,只需在設定檔中修改資料庫連線資訊即可。系統支援多指令操作:遷移指令讓資料庫初始化變得更簡單,服務指令則能輕鬆啟動 API 服務。
[線上文件](https://www.go-admin.pro)
[前端專案](https://github.com/go-admin-team/go-admin-ui)
[影片教學](https://space.bilibili.com/565616721/channel/detail?cid=125737)
## 🎬 線上體驗
Element Plus vue3 體驗:[https://vue.go-admin.pro](https://vue.go-admin.pro/#/login)
> ⚠️⚠️⚠️ 帳號 / 密碼: admin / 123456
antd 體驗(go-admin-pro):[https://antd.go-admin.pro](https://antd.go-admin.pro/)
> ⚠️⚠️⚠️ 帳號 / 密碼: admin / 123456
## ✨ 特性
- 遵循 RESTful API 設計規範
- 基於 GIN WEB API 框架,提供豐富的中介軟體支援(使用者認證、跨域、存取日誌、追蹤 ID 等)
- 基於 Casbin 的 RBAC 存取控制模型
- JWT 認證
- 支援 Swagger 文件(基於 swaggo)
- 基於 GORM 的資料庫儲存,可擴充多種類型資料庫
- 設定檔簡單的模型映射,快速取得所需設定
- 程式碼產生工具
- 表單建構工具
- 多指令模式
- 多租戶的支援
- TODO: 單元測試
## 🎁 內建
1. 多租戶:系統預設支援多租戶,按資料庫分離,一個資料庫一個租戶。
1. 使用者管理:使用者是系統操作者,該功能主要完成系統使用者設定。
2. 部門管理:設定系統組織架構(公司、部門、小組),以樹狀結構呈現並支援資料權限。
3. 職位管理:設定系統使用者所擔任的職務。
4. 選單管理:設定系統選單、操作權限、按鈕權限標識、介面權限等。
5. 角色管理:角色選單權限分配、設定角色按機構進行資料範圍權限劃分。
6. 字典管理:對系統中經常使用且較為固定的資料進行維護。
7. 參數管理:對系統動態設定常用參數。
8. 操作日誌:系統正常操作的日誌記錄與查詢;系統異常資訊的日誌記錄與查詢。
9. 登入日誌:系統登入日誌記錄查詢,包含登入異常。
1. 介面文件:根據業務程式碼自動產生相關的 API 介面文件。
1. 程式碼產生:根據資料表結構產生對應的增刪改查業務,全程視覺化操作,讓基本業務可以零程式碼實現。
1. 表單建構:自訂頁面樣式,拖拉放實現頁面佈局。
1. 服務監控:檢視伺服器的基本資訊。
1. 內容管理:demo 功能,下設分類管理、內容管理,可參考使用以快速入門。
1. 排程任務:自動化任務,目前支援介面呼叫與函式呼叫。
## 準備工作
你需要在本機安裝 [go] [gin] [node](http://nodejs.org/) 和 [git](https://git-scm.com/)
同時配套了系列教學(含影片與文件),說明如何從下載到熟練使用。強烈建議先看完這些教學再來實作本專案!!!
### 輕鬆用 go-admin 寫出第一個應用 - 文件教學
[步驟一 - 基礎內容介紹](https://www.go-admin.pro/guide/intro/tutorial01.html)
[步驟二 - 實際應用 - 撰寫增刪改查](https://www.go-admin.pro/guide/intro/tutorial02.html)
### 手把手教你從入門到放棄 - 影片教學
[如何啟動 go-admin](https://www.bilibili.com/video/BV1z5411x7JG)
[使用產生工具輕鬆實現業務](https://www.bilibili.com/video/BV1Dg4y1i79D)
[v1.1.0 版本程式碼產生工具 - 釋放雙手](https://www.bilibili.com/video/BV1N54y1i71P) [進階]
[多指令啟動方式講解以及 IDE 設定](https://www.bilibili.com/video/BV1Fg4y1q7ph)
[go-admin 選單的設定說明](https://www.bilibili.com/video/BV1Wp4y1D715) [必看]
[如何設定選單資訊以及介面資訊](https://www.bilibili.com/video/BV1zv411B7nG) [必看]
[go-admin 權限設定使用說明](https://www.bilibili.com/video/BV1rt4y197d3) [必看]
[go-admin 資料權限使用說明](https://www.bilibili.com/video/BV1LK4y1s71e) [必看]
**如有問題請先參閱上述文件與文章,若仍無法解決,歡迎提出 issue 與 pr。影片教學與文件持續更新中**
## 📦 本機開發
### 環境需求
go 1.26.5
node 版本: v22+(建議 v24 LTS)
套件管理器: pnpm v9+(UI 專案使用 pnpm)
### 建立開發目錄
```bash
# 建立開發目錄
mkdir goadmin
cd goadmin
```
### 取得程式碼
> 重點注意:兩個專案必須放在同一資料夾下;
```bash
# 取得後端程式碼
git clone https://github.com/go-admin-team/go-admin.git
# 取得前端程式碼
git clone https://github.com/go-admin-team/go-admin-ui.git
```
### 啟動說明
#### 伺服器端啟動說明
```bash
# 進入 go-admin 後端專案
cd ./go-admin
# 更新整理相依套件
go mod tidy
# 編譯專案
go build
# 修改設定
# 檔案路徑 go-admin/config/settings.yml
vi ./config/settings.yml
# 1. 在設定檔中修改資料庫資訊
# 注意: settings.database 下對應的設定資料
# 2. 確認 log 路徑
```
⚠️注意 在 Windows 環境若未安裝 CGO,會出現這個問題;
```bash
E:\go-admin>go build
# github.com/mattn/go-sqlite3
cgo: exec /missing-cc: exec: "/missing-cc": file does not exist
```
or
```bash
D:\Code\go-admin>go build
# github.com/mattn/go-sqlite3
cgo: exec gcc: exec: "gcc": executable file not found in %PATH%
```
[解決 cgo 問題請進入](https://www.go-admin.pro/zh-CN/guide/faq#cgo-%E7%9A%84%E9%97%AE%E9%A2%98)
#### 初始化資料庫,以及服務啟動
``` bash
# 首次設定需要初始化資料庫資源資訊
# macOS or linux 下使用
$ ./go-admin migrate -c config/settings.dev.yml
# ⚠️注意:windows 下使用
$ go-admin.exe migrate -c config/settings.dev.yml
# 啟動專案,也可以用 IDE 進行除錯
# macOS or linux 下使用
$ ./go-admin server -c config/settings.yml
# ⚠️注意:windows 下使用
$ go-admin.exe server -c config/settings.yml
```
#### sys_api 表的資料如何新增
在專案啟動時,使用 `-a true` 系統會自動新增缺少的介面資料
```bash
./go-admin server -c config/settings.yml -a true
```
#### 使用 docker 編譯啟動
```shell
# 編譯映像檔
docker build -t go-admin .
# 啟動容器,第一個 go-admin 是容器名稱,第二個 go-admin 是映像檔名稱
# -v 映射設定檔 本機路徑:容器路徑
docker run --name go-admin -p 8000:8000 -v /config/settings.yml:/config/settings.yml -d go-admin-server
```
#### 文件產生
```bash
go generate
```
#### 交叉編譯
```bash
# windows
env GOOS=windows GOARCH=amd64 go build main.go
# or
# linux
env GOOS=linux GOARCH=amd64 go build main.go
```
### UI 互動端啟動說明
```bash
# 安裝 pnpm(若未安裝)
npm install -g pnpm
# 安裝相依套件
pnpm install
# 中國大陸網路可指定鏡像來源加速
pnpm install --registry=https://registry.npmmirror.com
# 啟動服務
pnpm dev
```
## 📨 互動
<table>
<tr>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
<td><img src="https://doc-image.zhangwj.com/img/qrcode_for_gh_b798dc7db30c_258.jpg" width="180px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq2.png" width="200px"></td>
<td><a href="https://space.bilibili.com/565616721">wenjianzhang</a></td>
</tr>
<tr>
<td>微信</td>
<td>公众号🔥🔥🔥</td>
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=0f2bf59f5f2edec6a4550c364242c0641f870aa328e468c4ee4b7dbfb392627b"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流乙号" title="go-admin技术交流乙号"></a></td>
<td>哔哩哔哩🔥🔥🔥</td>
</tr>
</table>
## 💎 貢獻者
<span style="margin: 0 5px;" ><a href="https://github.com/wenjianzhang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3890175?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/G-Akiraka" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45746659?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/lwnmengjing" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/12806223?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bing127" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31166183?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/chengxiao" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1379545?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NightFire0307" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19854086?v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/appleboy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/21979?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/ninstein" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/580303?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/kikiyou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/17959053?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/horizonzy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/22524871?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Cassuis" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/48005724?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/hqcchina" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/5179057?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/nodece" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16235121?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stephenzhang0713" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/18169290?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhouxixi-dev" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/100399679?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Jalins" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31172582?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wkf928592" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6063351?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxxiong6" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6983441?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Silicon-He" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/52478309?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/GizmoOAO" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20385106?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bestgopher" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/36840497?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxb1207" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20775558?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/misakichan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16569274?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhuxuyang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19301024?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/mss-boot" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/109259065?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/AuroraV" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/37330199?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Vingurzhou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/57127283?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/haimait" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/40926384?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zyd" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3446278?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/infnan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/38274826?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/d1y" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45585937?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/qlijin" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/515900?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/logtous
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/88697234?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stepway
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/9927079?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NaturalGao
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/43291304?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/DemoLiang
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/23476007?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/jfcg
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1410597?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Nicole0724
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/10487328?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
## JetBrains 開源證書支援
`go-admin` 專案一直以來都是在 JetBrains 公司旗下的 GoLand 整合開發環境中進行開發,基於 **free JetBrains Open Source license(s)** 正版免費授權,在此表達我的謝意。
<a href="https://www.jetbrains.com/?from=kubeadm-ha" target="_blank"><img src="https://raw.githubusercontent.com/panjf2000/illustrations/master/jetbrains/jetbrains-variant-4.png" width="250" align="middle"/></a>
## 🤝 特別感謝
1. [ant-design](https://github.com/ant-design/ant-design)
2. [ant-design-pro](https://github.com/ant-design/ant-design-pro)
2. [arco-design](https://github.com/arco-design/arco-design)
2. [arco-design-pro](https://github.com/arco-design/arco-design-pro)
4. [gin](https://github.com/gin-gonic/gin)
5. [casbin](https://github.com/casbin/casbin)
6. [spf13/viper](https://github.com/spf13/viper)
7. [gorm](https://github.com/go-gorm/gorm)
8. [gin-swagger](https://github.com/swaggo/gin-swagger)
9. [golang-jwt](https://github.com/golang-jwt/jwt)
10. [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)
11. [ruoyi-vue](https://gitee.com/y_project/RuoYi-Vue)
12. [form-generator](https://github.com/JakHuang/form-generator)
## 🤟 贊助
> 如果你覺得這個專案幫助到了你,可以幫作者買一杯果汁表示鼓勵 :tropical_drink:
<img class="no-margin" src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/pay.png" height="200px" >
## 🤝 連結
- [mss-boot-io](https://docs.mss-boot-io.top/)
## 🔑 License
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
Copyright (c) 2026 wenjianzhang
+40
View File
@@ -0,0 +1,40 @@
package apis
import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/v2/captcha"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
)
type System struct {
api.Api
}
// GenerateCaptchaHandler 获取验证码
// @Summary 获取验证码
// @Description 获取验证码
// @Tags 登陆
// @Success 200 {object} response.Response{data=string,id=string,msg=string} "{"code": 200, "data": [...]}"
// @Router /api/v1/captcha [get]
func (e System) GenerateCaptchaHandler(c *gin.Context) {
if err := e.MakeContext(c).Errors; err != nil {
e.Error(500, err, "服务初始化失败!")
return
}
// The answer is deliberately discarded rather than logged. It used to be
// written at info level, which put a currently valid captcha answer in the
// application log - anyone able to read the log could bypass the check the
// captcha exists to enforce.
id, b64s, _, err := captcha.DriverDigitFunc()
if err != nil {
e.Logger.Errorf("DriverDigitFunc error, %s", err.Error())
e.Error(500, err, "验证码获取失败")
return
}
e.Custom(gin.H{
"code": 200,
"data": b64s,
"id": id,
"msg": "success",
})
}
@@ -1,4 +1,4 @@
package system
package apis
import (
"github.com/gin-gonic/gin"
@@ -11,13 +11,14 @@ const INDEX = `
<meta charset="utf-8">
<title>GO-ADMIN欢迎您</title>
<style>
body{
margin:0;
padding:0;
overflow-y:hidden
html,body{
margin:0;
padding:0;
height:100%;
overflow-y:hidden;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script src="https://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
window.onerror=function(){return true;}
$(function(){
@@ -28,12 +29,12 @@ $(function(){
</script>
</head>
<body>
<iframe id="iframe" frameborder="0" src="https://doc.go-admin.dev" style="width:100%;"></iframe>
<iframe id="iframe" frameborder="0" src="https://www.go-admin.pro" style="width:100%;height:100%;"></iframe>
</body>
</html>
`
func HelloWorld(c *gin.Context) {
func GoAdmin(c *gin.Context) {
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(200, INDEX)
}
-76
View File
@@ -1,76 +0,0 @@
package monitor
import (
"runtime"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
"go-admin/common/apis"
)
const (
B = 1
KB = 1024 * B
MB = 1024 * KB
GB = 1024 * MB
)
type Monitor struct {
apis.Api
}
// @Summary 系统信息
// @Description 获取JSON
// @Tags 系统信息
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/settings/serverInfo [get]
func (e Monitor) ServerInfo(c *gin.Context) {
e.Context = c
osDic := make(map[string]interface{}, 0)
osDic["goOs"] = runtime.GOOS
osDic["arch"] = runtime.GOARCH
osDic["mem"] = runtime.MemProfileRate
osDic["compiler"] = runtime.Compiler
osDic["version"] = runtime.Version()
osDic["numGoroutine"] = runtime.NumGoroutine()
osDic["ip"] = pkg.GetLocaHonst()
osDic["projectDir"] = pkg.GetCurrentPath()
dis, _ := disk.Usage("/")
diskTotalGB := int(dis.Total) / GB
diskFreeGB := int(dis.Free) / GB
diskDic := make(map[string]interface{}, 0)
diskDic["total"] = diskTotalGB
diskDic["free"] = diskFreeGB
mem, _ := mem.VirtualMemory()
memUsedMB := int(mem.Used) / GB
memTotalMB := int(mem.Total) / GB
memFreeMB := int(mem.Free) / GB
memUsedPercent := int(mem.UsedPercent)
memDic := make(map[string]interface{}, 0)
memDic["total"] = memTotalMB
memDic["used"] = memUsedMB
memDic["free"] = memFreeMB
memDic["usage"] = memUsedPercent
cpuDic := make(map[string]interface{}, 0)
cpuDic["cpuInfo"], _ = cpu.Info()
percent, _ := cpu.Percent(0, false)
cpuDic["Percent"] = pkg.Round(percent[0], 2)
cpuDic["cpuNum"], _ = cpu.Counts(false)
e.Custom(gin.H{
"code": 200,
"os": osDic,
"mem": memDic,
"cpu": cpuDic,
"disk": diskDic,
})
}
-199
View File
@@ -1,199 +0,0 @@
package public
import (
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"strings"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/utils"
"github.com/google/uuid"
"go-admin/common/apis"
"go-admin/common/file_store"
)
type FileResponse struct {
Size int64 `json:"size"`
Path string `json:"path"`
FullPath string `json:"full_path"`
Name string `json:"name"`
Type string `json:"type"`
}
const path = "static/uploadfile/"
type File struct {
apis.Api
}
// @Summary 上传图片
// @Description 获取JSON
// @Tags 公共接口
// @Accept multipart/form-data
// @Param type query string true "type" (1:单图,2:多图, 3:base64图片)
// @Param file formData file true "file"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/public/uploadFile [post]
func (e File) UploadFile(c *gin.Context) {
e.Context = c
tag, _ := c.GetPostForm("type")
urlPerfix := fmt.Sprintf("http://%s/", c.Request.Host)
var fileResponse FileResponse
if tag == "" {
e.Error(500, nil, "缺少标识")
//app.Error(c, 200, errors.New(""), "缺少标识")
return
} else {
switch tag {
case "1": // 单图
var done bool
fileResponse, done = e.singleFile(c, fileResponse, urlPerfix)
if done {
return
}
e.OK(fileResponse, "上传成功")
return
case "2": // 多图
multipartFile := e.multipleFile(c, urlPerfix)
e.OK(multipartFile, "上传成功")
return
case "3": // base64
fileResponse = e.baseImg(c, fileResponse, urlPerfix)
e.OK(fileResponse, "上传成功")
}
}
}
func (e File) baseImg(c *gin.Context, fileResponse FileResponse, urlPerfix string) FileResponse {
files, _ := c.GetPostForm("file")
file2list := strings.Split(files, ",")
ddd, _ := base64.StdEncoding.DecodeString(file2list[1])
guid := uuid.New().String()
fileName := guid + ".jpg"
err := utils.IsNotExistMkDir(path)
if err != nil {
e.Error(500, errors.New(""), "初始化文件路径失败")
}
base64File := path + fileName
_ = ioutil.WriteFile(base64File, ddd, 0666)
typeStr := strings.Replace(strings.Replace(file2list[0], "data:", "", -1), ";base64", "", -1)
fileResponse = FileResponse{
Size: pkg.GetFileSize(base64File),
Path: base64File,
FullPath: urlPerfix + base64File,
Name: "",
Type: typeStr,
}
source, _ := c.GetPostForm("source")
err = thirdUpload(source, fileName, base64File)
if err != nil {
e.Error(200, errors.New(""), "上传第三方失败")
return fileResponse
}
if source != "1" {
fileResponse.Path = "https://youshikeji.oss-cn-shanghai.aliyuncs.com/img/" + fileName
fileResponse.FullPath = "https://youshikeji.oss-cn-shanghai.aliyuncs.com/img/" + fileName
}
return fileResponse
}
func (e File) multipleFile(c *gin.Context, urlPerfix string) []FileResponse {
files := c.Request.MultipartForm.File["file"]
source, _ := c.GetPostForm("source")
var multipartFile []FileResponse
for _, f := range files {
guid := uuid.New().String()
fileName := guid + utils.GetExt(f.Filename)
err := utils.IsNotExistMkDir(path)
if err != nil {
e.Error(500, errors.New(""), "初始化文件路径失败")
}
multipartFileName := path + fileName
err1 := c.SaveUploadedFile(f, multipartFileName)
fileType, _ := utils.GetType(multipartFileName)
if err1 == nil {
err := thirdUpload(source, fileName, multipartFileName)
if err != nil {
e.Error(500, errors.New(""), "上传第三方失败")
} else {
fileResponse := FileResponse{
Size: pkg.GetFileSize(multipartFileName),
Path: multipartFileName,
FullPath: urlPerfix + multipartFileName,
Name: f.Filename,
Type: fileType,
}
if source != "1" {
fileResponse.Path = "https://youshikeji.oss-cn-shanghai.aliyuncs.com/img/" + fileName
fileResponse.FullPath = "https://youshikeji.oss-cn-shanghai.aliyuncs.com/img/" + fileName
}
multipartFile = append(multipartFile, fileResponse)
}
}
}
return multipartFile
}
func (e File) singleFile(c *gin.Context, fileResponse FileResponse, urlPerfix string) (FileResponse, bool) {
files, err := c.FormFile("file")
if err != nil {
e.Error(200, errors.New(""), "图片不能为空")
return FileResponse{}, true
}
// 上传文件至指定目录
guid := uuid.New().String()
fileName := guid + utils.GetExt(files.Filename)
err = utils.IsNotExistMkDir(path)
if err != nil {
e.Error(500, errors.New(""), "初始化文件路径失败")
}
singleFile := path + fileName
_ = c.SaveUploadedFile(files, singleFile)
fileType, _ := utils.GetType(singleFile)
fileResponse = FileResponse{
Size: pkg.GetFileSize(singleFile),
Path: singleFile,
FullPath: urlPerfix + singleFile,
Name: files.Filename,
Type: fileType,
}
source, _ := c.GetPostForm("source")
err = thirdUpload(source, fileName, singleFile)
if err != nil {
e.Error(200, errors.New(""), "上传第三方失败")
return FileResponse{}, true
}
fileResponse.Path = "https://youshikeji.oss-cn-shanghai.aliyuncs.com/img/" + fileName
fileResponse.FullPath = "https://youshikeji.oss-cn-shanghai.aliyuncs.com/img/" + fileName
return fileResponse, false
}
func thirdUpload(source string, name string, path string) error {
switch source {
case "2":
return ossUpload("img/"+name, path)
case "3":
return qiniuUpload("img/"+name, path)
}
return nil
}
func ossUpload(name string, path string) error {
oss := file_store.ALiYunOSS{}
return oss.UpLoad(name, path)
}
func qiniuUpload(name string, path string) error {
oss := file_store.ALiYunOSS{}
return oss.UpLoad(name, path)
}
+148
View File
@@ -0,0 +1,148 @@
package apis
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/v2/response"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
)
type SysApi struct {
api.Api
}
// GetPage 获取接口管理列表
// @Summary 获取接口管理列表
// @Description 获取接口管理列表
// @Tags 接口管理
// @Param name query string false "名称"
// @Param title query string false "标题"
// @Param path query string false "地址"
// @Param action query string false "类型"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]models.SysApi}} "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-api [get]
// @Security Bearer
func (e SysApi) GetPage(c *gin.Context) {
s := service.SysApi{}
req := dto.SysApiGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
//数据权限检查
p := actions.GetPermissionFromContext(c)
list := make([]models.SysApi, 0)
var count int64
err = s.GetPage(&req, p, &list, &count)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// Get 获取接口管理
// @Summary 获取接口管理
// @Description 获取接口管理
// @Tags 接口管理
// @Param id path string false "id"
// @Success 200 {object} response.Response{data=models.SysApi} "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-api/{id} [get]
// @Security Bearer
func (e SysApi) Get(c *gin.Context) {
req := dto.SysApiGetReq{}
s := service.SysApi{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
p := actions.GetPermissionFromContext(c)
var object models.SysApi
err = s.Get(&req, p, &object).Error
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(object, "查询成功")
}
// Update 修改接口管理
// @Summary 修改接口管理
// @Description 修改接口管理
// @Tags 接口管理
// @Accept application/json
// @Product application/json
// @Param data body dto.SysApiUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}"
// @Router /api/v1/sys-api/{id} [put]
// @Security Bearer
func (e SysApi) Update(c *gin.Context) {
req := dto.SysApiUpdateReq{}
s := service.SysApi{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
return
}
req.SetUpdateBy(user.GetUserId(c))
p := actions.GetPermissionFromContext(c)
err = s.Update(&req, p)
if err != nil {
e.Error(500, err, "更新失败")
return
}
e.OK(req.GetId(), "更新成功")
}
// DeleteSysApi 删除接口管理
// @Summary 删除接口管理
// @Description 删除接口管理
// @Tags 接口管理
// @Param data body dto.SysApiDeleteReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "message": "删除成功"}"
// @Router /api/v1/sys-api [delete]
// @Security Bearer
func (e SysApi) DeleteSysApi(c *gin.Context) {
req := dto.SysApiDeleteReq{}
s := service.SysApi{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
return
}
p := actions.GetPermissionFromContext(c)
err = s.Remove(&req, p)
if err != nil {
e.Error(500, err, "删除失败")
return
}
e.OK(req.GetId(), "删除成功")
}
@@ -1,195 +0,0 @@
package sys_china_area_data
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
"go-admin/common/apis"
)
type SysChinaAreaData struct {
apis.Api
}
func (e SysChinaAreaData) GetSysChinaAreaDataList(c *gin.Context) {
e.SetContext(c)
log := e.GetLogger()
d := new(dto.SysChinaAreaDataSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查询列表
err = d.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
//数据权限检查
p := actions.GetPermissionFromContext(c)
list := make([]models.SysChinaAreaData, 0)
var count int64
serviceStudent := service.SysChinaAreaData{}
serviceStudent.Log = log
serviceStudent.Orm = db
err = serviceStudent.GetSysChinaAreaDataPage(d, p, &list, &count)
if err != nil {
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.PageOK(list, int(count), d.GetPageIndex(), d.GetPageSize(), "查询成功")
}
func (e SysChinaAreaData) GetSysChinaAreaData(c *gin.Context) {
e.SetContext(c)
log := e.GetLogger()
control := new(dto.SysChinaAreaDataById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object models.SysChinaAreaData
//数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysChinaAreaData := service.SysChinaAreaData{}
serviceSysChinaAreaData.Log = log
serviceSysChinaAreaData.Orm = db
err = serviceSysChinaAreaData.GetSysChinaAreaData(control, p, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
func (e SysChinaAreaData) InsertSysChinaAreaData(c *gin.Context) {
e.SetContext(c)
log := e.GetLogger()
control := new(dto.SysChinaAreaDataControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
serviceSysChinaAreaData := service.SysChinaAreaData{}
serviceSysChinaAreaData.Orm = db
serviceSysChinaAreaData.Log = log
err = serviceSysChinaAreaData.InsertSysChinaAreaData(object)
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(object.GetId(), "创建成功")
}
func (e SysChinaAreaData) UpdateSysChinaAreaData(c *gin.Context) {
e.SetContext(c)
log := e.GetLogger()
control := new(dto.SysChinaAreaDataControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
//数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysChinaAreaData := service.SysChinaAreaData{}
serviceSysChinaAreaData.Orm = db
serviceSysChinaAreaData.Log = log
err = serviceSysChinaAreaData.UpdateSysChinaAreaData(object, p)
if err != nil {
log.Error(err)
return
}
e.OK(object.GetId(), "更新成功")
}
func (e SysChinaAreaData) DeleteSysChinaAreaData(c *gin.Context) {
e.SetContext(c)
log := e.GetLogger()
control := new(dto.SysChinaAreaDataById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
err = control.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
// 设置编辑人
control.SetUpdateBy(user.GetUserId(c))
// 数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysChinaAreaData := service.SysChinaAreaData{}
serviceSysChinaAreaData.Orm = db
serviceSysChinaAreaData.Log = log
err = serviceSysChinaAreaData.RemoveSysChinaAreaData(control, p)
if err != nil {
log.Errorf("RemoveSysChinaAreaData error, %s", err)
e.Error(http.StatusInternalServerError, err, "删除失败")
return
}
e.OK(control.GetId(), "删除成功")
}
+313
View File
@@ -0,0 +1,313 @@
package apis
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
)
type SysConfig struct {
api.Api
}
// GetPage 获取配置管理列表
// @Summary 获取配置管理列表
// @Description 获取配置管理列表
// @Tags 配置管理
// @Param configName query string false "名称"
// @Param configKey query string false "key"
// @Param configType query string false "类型"
// @Param isFrontend query int false "是否前端"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]models.SysApi}} "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-config [get]
// @Security Bearer
func (e SysConfig) GetPage(c *gin.Context) {
s := service.SysConfig{}
req := dto.SysConfigGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
return
}
list := make([]models.SysConfig, 0)
var count int64
err = s.GetPage(&req, &list, &count)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// Get 获取配置管理
// @Summary 获取配置管理
// @Description 获取配置管理
// @Tags 配置管理
// @Param id path string false "id"
// @Success 200 {object} response.Response{data=models.SysConfig} "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-config/{id} [get]
// @Security Bearer
func (e SysConfig) Get(c *gin.Context) {
req := dto.SysConfigGetReq{}
s := service.SysConfig{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var object models.SysConfig
err = s.Get(&req, &object)
if err != nil {
e.Error(500, err, err.Error())
return
}
e.OK(object, "查询成功")
}
// Insert 创建配置管理
// @Summary 创建配置管理
// @Description 创建配置管理
// @Tags 配置管理
// @Accept application/json
// @Product application/json
// @Param data body dto.SysConfigControl true "body"
// @Success 200 {object} response.Response "{"code": 200, "message": "创建成功"}"
// @Router /api/v1/sys-config [post]
// @Security Bearer
func (e SysConfig) Insert(c *gin.Context) {
s := service.SysConfig{}
req := dto.SysConfigControl{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetCreateBy(user.GetUserId(c))
err = s.Insert(&req)
if err != nil {
e.Error(500, err, "创建失败")
return
}
e.OK(req.GetId(), "创建成功")
}
// Update 修改配置管理
// @Summary 修改配置管理
// @Description 修改配置管理
// @Tags 配置管理
// @Accept application/json
// @Product application/json
// @Param data body dto.SysConfigControl true "body"
// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}"
// @Router /api/v1/sys-config/{id} [put]
// @Security Bearer
func (e SysConfig) Update(c *gin.Context) {
s := service.SysConfig{}
req := dto.SysConfigControl{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Update(&req)
if err != nil {
e.Error(500, err, "更新失败")
return
}
e.OK(req.GetId(), "更新成功")
}
// Delete 删除配置管理
// @Summary 删除配置管理
// @Description 删除配置管理
// @Tags 配置管理
// @Param ids body []int false "ids"
// @Success 200 {object} response.Response "{"code": 200, "message": "删除成功"}"
// @Router /api/v1/sys-config [delete]
// @Security Bearer
func (e SysConfig) Delete(c *gin.Context) {
s := service.SysConfig{}
req := dto.SysConfigDeleteReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Remove(&req)
if err != nil {
e.Error(500, err, "删除失败")
return
}
e.OK(req.GetId(), "删除成功")
}
// Get2SysApp 获取系统配置信息
// @Summary 获取系统前台配置信息,主要注意这里不在验证权限
// @Description 获取系统配置信息,主要注意这里不在验证权限
// @Tags 配置管理
// @Success 200 {object} response.Response{data=map[string]string} "{"code": 200, "data": [...]}"
// @Router /api/v1/app-config [get]
func (e SysConfig) Get2SysApp(c *gin.Context) {
req := dto.SysConfigGetToSysAppReq{}
s := service.SysConfig{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
return
}
// 控制只读前台的数据
req.IsFrontend = "1"
list := make([]models.SysConfig, 0)
err = s.GetWithKeyList(&req, &list)
if err != nil {
e.Error(500, err, "查询失败")
return
}
mp := make(map[string]string)
for i := 0; i < len(list); i++ {
key := list[i].ConfigKey
if key != "" {
mp[key] = list[i].ConfigValue
}
}
e.OK(mp, "查询成功")
}
// Get2Set 获取配置
// @Summary 获取配置
// @Description 界面操作设置配置值的获取
// @Tags 配置管理
// @Accept application/json
// @Product application/json
// @Success 200 {object} response.Response{data=map[string]interface{}} "{"code": 200, "message": "修改成功"}"
// @Router /api/v1/set-config [get]
// @Security Bearer
func (e SysConfig) Get2Set(c *gin.Context) {
s := service.SysConfig{}
req := make([]dto.GetSetSysConfigReq, 0)
err := e.MakeContext(c).
MakeOrm().
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
err = s.GetForSet(&req)
if err != nil {
e.Error(500, err, "查询失败")
return
}
m := make(map[string]interface{}, 0)
for _, v := range req {
m[v.ConfigKey] = v.ConfigValue
}
e.OK(m, "查询成功")
}
// Update2Set 设置配置
// @Summary 设置配置
// @Description 界面操作设置配置值
// @Tags 配置管理
// @Accept application/json
// @Product application/json
// @Param data body []dto.GetSetSysConfigReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}"
// @Router /api/v1/set-config [put]
// @Security Bearer
func (e SysConfig) Update2Set(c *gin.Context) {
s := service.SysConfig{}
req := make([]dto.GetSetSysConfigReq, 0)
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
err = s.UpdateForSet(&req)
if err != nil {
e.Error(500, err, err.Error())
return
}
e.OK("", "更新成功")
}
// GetSysConfigByKEYForService 根据Key获取SysConfig的Service
// @Summary 根据Key获取SysConfig的Service
// @Description 根据Key获取SysConfig的Service
// @Tags 配置管理
// @Param configKey path string false "configKey"
// @Success 200 {object} response.Response{data=dto.SysConfigByKeyReq} "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-config/{id} [get]
// @Security Bearer
func (e SysConfig) GetSysConfigByKEYForService(c *gin.Context) {
var s = new(service.SysConfig)
var req = new(dto.SysConfigByKeyReq)
var resp = new(dto.GetSysConfigByKEYForServiceResp)
err := e.MakeContext(c).
MakeOrm().
Bind(req, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
err = s.GetWithKey(req, resp)
if err != nil {
e.Error(500, err, err.Error())
return
}
e.OK(resp, s.Msg)
}
+238
View File
@@ -0,0 +1,238 @@
package apis
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/v2/response"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"github.com/go-admin-team/go-admin-core/v2/sdk/pkg"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
)
type SysDept struct {
api.Api
}
// GetPage
// @Summary 分页部门列表数据
// @Description 分页列表
// @Tags 部门
// @Param deptName query string false "deptName"
// @Param deptId query string false "deptId"
// @Param position query string false "position"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dept [get]
// @Security Bearer
func (e SysDept) GetPage(c *gin.Context) {
s := service.SysDept{}
req := dto.SysDeptGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]models.SysDept, 0)
list, err = s.SetDeptPage(&req)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(list, "查询成功")
}
// Get
// @Summary 获取部门数据
// @Description 获取JSON
// @Tags 部门
// @Param deptId path string false "deptId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dept/{deptId} [get]
// @Security Bearer
func (e SysDept) Get(c *gin.Context) {
s := service.SysDept{}
req := dto.SysDeptGetReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var object models.SysDept
err = s.Get(&req, &object)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(object, "查询成功")
}
// Insert 添加部门
// @Summary 添加部门
// @Description 获取JSON
// @Tags 部门
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDeptInsertReq true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dept [post]
// @Security Bearer
func (e SysDept) Insert(c *gin.Context) {
s := service.SysDept{}
req := dto.SysDeptInsertReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
// 设置创建人
req.SetCreateBy(user.GetUserId(c))
err = s.Insert(&req)
if err != nil {
e.Error(500, err, "创建失败")
return
}
e.OK(req.GetId(), "创建成功")
}
// Update
// @Summary 修改部门
// @Description 获取JSON
// @Tags 部门
// @Accept application/json
// @Product application/json
// @Param id path int true "id"
// @Param data body dto.SysDeptUpdateReq true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dept/{deptId} [put]
// @Security Bearer
func (e SysDept) Update(c *gin.Context) {
s := service.SysDept{}
req := dto.SysDeptUpdateReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Update(&req)
if err != nil {
e.Error(500, err, err.Error())
return
}
e.OK(req.GetId(), "更新成功")
}
// Delete
// @Summary 删除部门
// @Description 删除数据
// @Tags 部门
// @Param data body dto.SysDeptDeleteReq true "body"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/dept [delete]
// @Security Bearer
func (e SysDept) Delete(c *gin.Context) {
s := service.SysDept{}
req := dto.SysDeptDeleteReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
err = s.Remove(&req)
if err != nil {
e.Error(500, err, "删除失败")
return
}
e.OK(req.GetId(), "删除成功")
}
// Get2Tree 用户管理 左侧部门树
func (e SysDept) Get2Tree(c *gin.Context) {
s := service.SysDept{}
req := dto.SysDeptGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]dto.DeptLabel, 0)
list, err = s.SetDeptTree(&req)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(list, "")
}
// GetDeptTreeRoleSelect TODO: 此接口需要调整不应该将list和选中放在一起
func (e SysDept) GetDeptTreeRoleSelect(c *gin.Context) {
s := service.SysDept{}
err := e.MakeContext(c).
MakeOrm().
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
id, err := pkg.StringToInt(c.Param("roleId"))
result, err := s.SetDeptLabel()
if err != nil {
e.Error(500, err, err.Error())
return
}
menuIds := make([]int, 0)
if id != 0 {
menuIds, err = s.GetWithRoleId(id)
if err != nil {
e.Error(500, err, err.Error())
return
}
}
e.OK(gin.H{
"depts": result,
"checkedKeys": menuIds,
}, "")
}
+220
View File
@@ -0,0 +1,220 @@
package apis
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/v2/response"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
)
type SysDictData struct {
api.Api
}
// GetPage
// @Summary 字典数据列表
// @Description 获取JSON
// @Tags 字典数据
// @Param status query string false "status"
// @Param dictCode query string false "dictCode"
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/data [get]
// @Security Bearer
func (e SysDictData) GetPage(c *gin.Context) {
s := service.SysDictData{}
req := dto.SysDictDataGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]models.SysDictData, 0)
var count int64
err = s.GetPage(&req, &list, &count)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// Get
// @Summary 通过编码获取字典数据
// @Description 获取JSON
// @Tags 字典数据
// @Param dictCode path int true "字典编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/data/{dictCode} [get]
// @Security Bearer
func (e SysDictData) Get(c *gin.Context) {
s := service.SysDictData{}
req := dto.SysDictDataGetReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var object models.SysDictData
err = s.Get(&req, &object)
if err != nil {
e.Logger.Warnf("Get error: %s", err.Error())
e.Error(500, err, "查询失败")
return
}
e.OK(object, "查询成功")
}
// Insert
// @Summary 添加字典数据
// @Description 获取JSON
// @Tags 字典数据
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDictDataInsertReq true "data"
// @Success 200 {object} response.Response "{"code": 200, "message": "添加成功"}"
// @Router /api/v1/dict/data [post]
// @Security Bearer
func (e SysDictData) Insert(c *gin.Context) {
s := service.SysDictData{}
req := dto.SysDictDataInsertReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetCreateBy(user.GetUserId(c))
err = s.Insert(&req)
if err != nil {
e.Error(500, err, "创建失败")
return
}
e.OK(req.GetId(), "创建成功")
}
// Update
// @Summary 修改字典数据
// @Description 获取JSON
// @Tags 字典数据
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDictDataUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}"
// @Router /api/v1/dict/data/{dictCode} [put]
// @Security Bearer
func (e SysDictData) Update(c *gin.Context) {
s := service.SysDictData{}
req := dto.SysDictDataUpdateReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Update(&req)
if err != nil {
e.Error(500, err, "更新失败")
return
}
e.OK(req.GetId(), "更新成功")
}
// Delete
// @Summary 删除字典数据
// @Description 删除数据
// @Tags 字典数据
// @Param dictCode body dto.SysDictDataDeleteReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "message": "删除成功"}"
// @Router /api/v1/dict/data [delete]
// @Security Bearer
func (e SysDictData) Delete(c *gin.Context) {
s := service.SysDictData{}
req := dto.SysDictDataDeleteReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Remove(&req)
if err != nil {
e.Error(500, err, "删除失败")
return
}
e.OK(req.GetId(), "删除成功")
}
// GetAll 数据字典根据key获取 业务页面使用
// @Summary 数据字典根据key获取
// @Description 数据字典根据key获取
// @Tags 字典数据
// @Param dictType query int true "dictType"
// @Success 200 {object} response.Response{data=[]dto.SysDictDataGetAllResp} "{"code": 200, "data": [...]}"
// @Router /api/v1/dict-data/option-select [get]
// @Security Bearer
func (e SysDictData) GetAll(c *gin.Context) {
s := service.SysDictData{}
req := dto.SysDictDataGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]models.SysDictData, 0)
err = s.GetAll(&req, &list)
if err != nil {
e.Error(500, err, "查询失败")
return
}
l := make([]dto.SysDictDataGetAllResp, 0)
for _, i := range list {
d := dto.SysDictDataGetAllResp{}
e.Translate(i, &d)
l = append(l, d)
}
e.OK(l,"查询成功")
}
+210
View File
@@ -0,0 +1,210 @@
package apis
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/v2/response"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
)
type SysDictType struct {
api.Api
}
// GetPage 字典类型列表数据
// @Summary 字典类型列表数据
// @Description 获取JSON
// @Tags 字典类型
// @Param dictName query string false "dictName"
// @Param dictId query string false "dictId"
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type [get]
// @Security Bearer
func (e SysDictType) GetPage(c *gin.Context) {
s := service.SysDictType{}
req :=dto.SysDictTypeGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]models.SysDictType, 0)
var count int64
err = s.GetPage(&req, &list, &count)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// Get 字典类型通过字典id获取
// @Summary 字典类型通过字典id获取
// @Description 获取JSON
// @Tags 字典类型
// @Param dictId path int true "字典类型编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type/{dictId} [get]
// @Security Bearer
func (e SysDictType) Get(c *gin.Context) {
s := service.SysDictType{}
req :=dto.SysDictTypeGetReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var object models.SysDictType
err = s.Get(&req, &object)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(object, "查询成功")
}
//Insert 字典类型创建
// @Summary 添加字典类型
// @Description 获取JSON
// @Tags 字典类型
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDictTypeInsertReq true "data"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type [post]
// @Security Bearer
func (e SysDictType) Insert(c *gin.Context) {
s := service.SysDictType{}
req :=dto.SysDictTypeInsertReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetCreateBy(user.GetUserId(c))
err = s.Insert(&req)
if err != nil {
e.Logger.Error(err)
e.Error(500, err,fmt.Sprintf(" 创建字典类型失败,详情:%s", err.Error()))
return
}
e.OK(req.GetId(), "创建成功")
}
// Update
// @Summary 修改字典类型
// @Description 获取JSON
// @Tags 字典类型
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDictTypeUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type/{dictId} [put]
// @Security Bearer
func (e SysDictType) Update(c *gin.Context) {
s := service.SysDictType{}
req :=dto.SysDictTypeUpdateReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Error(500, err, err.Error())
e.Logger.Error(err)
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Update(&req)
if err != nil {
e.Logger.Error(err)
return
}
e.OK(req.GetId(), "更新成功")
}
// Delete
// @Summary 删除字典类型
// @Description 删除数据
// @Tags 字典类型
// @Param dictCode body dto.SysDictTypeDeleteReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type [delete]
// @Security Bearer
func (e SysDictType) Delete(c *gin.Context) {
s := service.SysDictType{}
req :=dto.SysDictTypeDeleteReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Remove(&req)
if err != nil {
e.Error(500, err, err.Error())
return
}
e.OK(req.GetId(), "删除成功")
}
// GetAll
// @Summary 字典类型全部数据 代码生成使用接口
// @Description 获取JSON
// @Tags 字典类型
// @Param dictName query string false "dictName"
// @Param dictId query string false "dictId"
// @Param dictType query string false "dictType"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type-option-select [get]
// @Security Bearer
func (e SysDictType) GetAll(c *gin.Context) {
s := service.SysDictType{}
req :=dto.SysDictTypeGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]models.SysDictType, 0)
err = s.GetAll(&req, &list)
if err != nil {
e.Error(500, err, err.Error())
return
}
e.OK(list, "查询成功")
}
-198
View File
@@ -1,198 +0,0 @@
package sys_file
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
"go-admin/common/apis"
)
type SysFileDir struct {
apis.Api
}
func (e SysFileDir) GetSysFileDirList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
search := new(dto.SysFileDirSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
err = c.ShouldBind(search)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
}
var list *[]models.SysFileDirL
serviceStudent := service.SysFileDir{}
serviceStudent.Log = log
serviceStudent.Orm = db
list, err = serviceStudent.SetSysFileDir(search)
if err != nil {
log.Errorf("SetSysFileDir error, %s", err)
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(list, "查询成功")
}
func (e SysFileDir) GetSysFileDir(c *gin.Context) {
control := new(dto.SysFileDirById)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = c.ShouldBindUri(control)
if err != nil {
log.Warnf("ShouldBindUri error: %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
}
var object models.SysFileDir
serviceSysFileDir := service.SysFileDir{}
serviceSysFileDir.Log = log
serviceSysFileDir.Orm = db
err = serviceSysFileDir.GetSysFileDir(control, &object)
if err != nil {
log.Errorf("GetSysFileDir error, %s", err)
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
func (e SysFileDir) InsertSysFileDir(c *gin.Context) {
control := new(dto.SysFileDirControl)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = c.ShouldBindUri(control)
if err != nil {
log.Warnf("ShouldBindUri error: %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
err = c.ShouldBind(control)
if err != nil {
log.Warnf("ShouldBind error: %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
// 设置创建人
control.CreateBy = user.GetUserId(c)
serviceSysFileDir := service.SysFileDir{}
serviceSysFileDir.Orm = db
serviceSysFileDir.Log = log
err = serviceSysFileDir.InsertSysFileDir(control)
if err != nil {
log.Errorf("InsertSysFileDir error, %s", err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(control.ID, "创建成功")
}
func (e SysFileDir) UpdateSysFileDir(c *gin.Context) {
control := new(dto.SysFileDirControl)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
err = c.ShouldBindUri(control)
if err != nil {
log.Warnf("ShouldBindUri error: %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
}
err = c.ShouldBind(control)
if err != nil {
log.Warnf("ShouldBind error: %#v", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
}
// 设置创建人
control.UpdateBy = user.GetUserId(c)
//数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysFileDir := service.SysFileDir{}
serviceSysFileDir.Orm = db
serviceSysFileDir.Log = log
err = serviceSysFileDir.UpdateSysFileDir(control, p)
if err != nil {
log.Errorf("UpdateSysFileDir error, %s", err)
e.Error(http.StatusInternalServerError, err, "更新失败")
return
}
e.OK(control.ID, "更新成功")
}
func (e SysFileDir) DeleteSysFileDir(c *gin.Context) {
control := new(dto.SysFileDirById)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
msgID := pkg.GenerateMsgIDFromContext(c)
//删除操作
err = c.ShouldBindUri(control)
if err != nil {
log.Warnf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
}
err = c.ShouldBind(control)
if err != nil {
log.Warnf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
}
// 设置编辑人
control.UpdateBy = user.GetUserId(c)
// 数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysFileDir := service.SysFileDir{}
serviceSysFileDir.Orm = db
serviceSysFileDir.MsgID = msgID
err = serviceSysFileDir.RemoveSysFileDir(control, p)
if err != nil {
log.Errorf("RemoveSysFileDir error, %s", err)
e.Error(http.StatusInternalServerError, err, "删除失败")
return
}
e.OK(control.Id, "删除成功")
}
-209
View File
@@ -1,209 +0,0 @@
package sys_file
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
"go-admin/common/apis"
)
type SysFileInfo struct {
apis.Api
}
func (e SysFileInfo) GetSysFileInfoList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
search := new(dto.SysFileInfoSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
err = c.ShouldBind(search)
if err != nil {
log.Warnf("参数验证错误, error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
//数据权限检查
p := actions.GetPermissionFromContext(c)
list := make([]models.SysFileInfo, 0)
var count int64
serviceStudent := service.SysFileInfo{}
serviceStudent.Log = log
serviceStudent.Orm = db
err = serviceStudent.GetSysFileInfoPage(search, p, &list, &count)
if err != nil {
log.Errorf("GetSysFileInfoPage error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.PageOK(list, int(count), search.PageIndex, search.PageSize, "查询成功")
}
func (e SysFileInfo) GetSysFileInfo(c *gin.Context) {
control := new(dto.SysFileInfoById)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = c.ShouldBindUri(control)
if err != nil {
log.Warnf("参数验证错误, error:%s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object models.SysFileInfo
//数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysFileInfo := service.SysFileInfo{}
serviceSysFileInfo.Log = log
serviceSysFileInfo.Orm = db
err = serviceSysFileInfo.GetSysFileInfo(control, p, &object)
if err != nil {
log.Errorf("GetSysFileInfo error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
func (e SysFileInfo) InsertSysFileInfo(c *gin.Context) {
control := new(dto.SysFileInfoControl)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = c.ShouldBindUri(control)
if err != nil {
log.Warnf("参数验证错误, error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
err = c.ShouldBind(control)
if err != nil {
log.Warnf("参数验证错误, error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
// 设置创建人
control.CreateBy = user.GetUserId(c)
serviceSysFileInfo := service.SysFileInfo{}
serviceSysFileInfo.Orm = db
serviceSysFileInfo.Log = log
err = serviceSysFileInfo.InsertSysFileInfo(control)
if err != nil {
log.Errorf("InsertSysFileInfo error: %s", err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(control.ID, "创建成功")
}
func (e SysFileInfo) UpdateSysFileInfo(c *gin.Context) {
control := new(dto.SysFileInfoControl)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
err = c.ShouldBindUri(control)
if err != nil {
log.Warnf("参数验证错误, error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
err = c.ShouldBind(control)
if err != nil {
log.Warnf("参数验证错误, error:%s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
// 设置创建人
control.UpdateBy = user.GetUserId(c)
//数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysFileInfo := service.SysFileInfo{}
serviceSysFileInfo.Orm = db
serviceSysFileInfo.Log = log
err = serviceSysFileInfo.UpdateSysFileInfo(control, p)
if err != nil {
log.Errorf("UpdateSysFileInfo error: %s", err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(control.ID, "更新成功")
}
func (e SysFileInfo) DeleteSysFileInfo(c *gin.Context) {
control := new(dto.SysFileInfoById)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
err = c.ShouldBindUri(control)
if err != nil {
log.Warnf("参数验证错误, error: %s", err)
e.Error(422, err, "参数验证失败")
return
}
err = c.ShouldBind(control)
if err != nil {
log.Warnf("参数验证错误, error: %s", err)
e.Error(422, err, "参数验证失败")
return
}
// 设置编辑人
control.UpdateBy = user.GetUserId(c)
// 数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysFileInfo := service.SysFileInfo{}
serviceSysFileInfo.Orm = db
serviceSysFileInfo.Log = log
err = serviceSysFileInfo.RemoveSysFileInfo(control, p)
if err != nil {
log.Errorf("RemoveSysFileInfo error: %s", err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(control.Id, "删除成功")
}
+110
View File
@@ -0,0 +1,110 @@
package apis
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
)
type SysLoginLog struct {
api.Api
}
// GetPage 登录日志列表
// @Summary 登录日志列表
// @Description 获取JSON
// @Tags 登录日志
// @Param username query string false "用户名"
// @Param ipaddr query string false "ip地址"
// @Param loginLocation query string false "归属地"
// @Param status query string false "状态"
// @Param beginTime query string false "开始时间"
// @Param endTime query string false "结束时间"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-login-log [get]
// @Security Bearer
func (e SysLoginLog) GetPage(c *gin.Context) {
s := service.SysLoginLog{}
req :=dto.SysLoginLogGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]models.SysLoginLog, 0)
var count int64
err = s.GetPage(&req, &list, &count)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// Get 登录日志通过id获取
// @Summary 登录日志通过id获取
// @Description 获取JSON
// @Tags 登录日志
// @Param id path string false "id"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-login-log/{id} [get]
// @Security Bearer
func (e SysLoginLog) Get(c *gin.Context) {
s := service.SysLoginLog{}
req :=dto.SysLoginLogGetReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var object models.SysLoginLog
err = s.Get(&req, &object)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(object, "查询成功")
}
// Delete 登录日志删除
// @Summary 登录日志删除
// @Description 登录日志删除
// @Tags 登录日志
// @Param data body dto.SysLoginLogDeleteReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-login-log [delete]
// @Security Bearer
func (e SysLoginLog) Delete(c *gin.Context) {
s := service.SysLoginLog{}
req :=dto.SysLoginLogDeleteReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
err = s.Remove(&req)
if err != nil {
e.Error(500, err, "删除失败")
return
}
e.OK(req.GetId(), "删除成功")
}
+249
View File
@@ -0,0 +1,249 @@
package apis
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
)
type SysMenu struct {
api.Api
}
// GetPage Menu列表数据
// @Summary Menu列表数据
// @Description 获取JSON
// @Tags 菜单
// @Param menuName query string false "menuName"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/menu [get]
// @Security Bearer
func (e SysMenu) GetPage(c *gin.Context) {
s := service.SysMenu{}
req := dto.SysMenuGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var list = make([]models.SysMenu, 0)
err = s.GetPage(&req, &list).Error
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(list, "查询成功")
}
// Get 获取菜单详情
// @Summary Menu详情数据
// @Description 获取JSON
// @Tags 菜单
// @Param id path string false "id"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/menu/{id} [get]
// @Security Bearer
func (e SysMenu) Get(c *gin.Context) {
req := dto.SysMenuGetReq{}
s := new(service.SysMenu)
err := e.MakeContext(c).
MakeOrm().
Bind(&req, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var object = models.SysMenu{}
err = s.Get(&req, &object).Error
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(object, "查询成功")
}
// Insert 创建菜单
// @Summary 创建菜单
// @Description 获取JSON
// @Tags 菜单
// @Accept application/json
// @Product application/json
// @Param data body dto.SysMenuInsertReq true "data"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/menu [post]
// @Security Bearer
func (e SysMenu) Insert(c *gin.Context) {
req := dto.SysMenuInsertReq{}
s := new(service.SysMenu)
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
// 设置创建人
req.SetCreateBy(user.GetUserId(c))
err = s.Insert(&req).Error
if err != nil {
e.Error(500, err, "创建失败")
return
}
e.OK(req.GetId(), "创建成功")
}
// Update 修改菜单
// @Summary 修改菜单
// @Description 获取JSON
// @Tags 菜单
// @Accept application/json
// @Product application/json
// @Param id path int true "id"
// @Param data body dto.SysMenuUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/menu/{id} [put]
// @Security Bearer
func (e SysMenu) Update(c *gin.Context) {
req := dto.SysMenuUpdateReq{}
s := new(service.SysMenu)
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Update(&req).Error
if err != nil {
e.Error(500, err, "更新失败")
return
}
e.OK(req.GetId(), "更新成功")
}
// Delete 删除菜单
// @Summary 删除菜单
// @Description 删除数据
// @Tags 菜单
// @Param data body dto.SysMenuDeleteReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/menu [delete]
// @Security Bearer
func (e SysMenu) Delete(c *gin.Context) {
control := new(dto.SysMenuDeleteReq)
s := new(service.SysMenu)
err := e.MakeContext(c).
MakeOrm().
Bind(control, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
err = s.Remove(control).Error
if err != nil {
e.Logger.Errorf("RemoveSysMenu error, %s", err)
e.Error(500, err, "删除失败")
return
}
e.OK(control.GetId(), "删除成功")
}
// GetMenuRole 根据登录角色名称获取菜单列表数据(左菜单使用)
// @Summary 根据登录角色名称获取菜单列表数据(左菜单使用)
// @Description 获取JSON
// @Tags 菜单
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/menurole [get]
// @Security Bearer
func (e SysMenu) GetMenuRole(c *gin.Context) {
s := new(service.SysMenu)
err := e.MakeContext(c).
MakeOrm().
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
result, err := s.SetMenuRole(user.GetRoleName(c))
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(result, "")
}
// GetMenuTreeSelect 根据角色ID查询菜单下拉树结构
// @Summary 角色修改使用的菜单列表
// @Description 获取JSON
// @Tags 菜单
// @Accept application/json
// @Product application/json
// @Param roleId path int true "roleId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/menuTreeselect/{roleId} [get]
// @Security Bearer
func (e SysMenu) GetMenuTreeSelect(c *gin.Context) {
m := service.SysMenu{}
r := service.SysRole{}
req := dto.SelectRole{}
err := e.MakeContext(c).
MakeOrm().
MakeService(&m.Service).
MakeService(&r.Service).
Bind(&req, nil).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
result, err := m.SetLabel()
if err != nil {
e.Error(500, err, "查询失败")
return
}
menuIds := make([]int, 0)
if req.RoleId != 0 {
menuIds, err = r.GetRoleMenuId(req.RoleId)
if err != nil {
e.Error(500, err, "")
return
}
}
e.OK(gin.H{
"menus": result,
"checkedKeys": menuIds,
}, "获取成功")
}
+118
View File
@@ -0,0 +1,118 @@
package apis
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
)
type SysOperaLog struct {
api.Api
}
// GetPage 操作日志列表
// @Summary 操作日志列表
// @Description 获取JSON
// @Tags 操作日志
// @Param title query string false "title"
// @Param method query string false "method"
// @Param requestMethod query string false "requestMethod"
// @Param operUrl query string false "operUrl"
// @Param operIp query string false "operIp"
// @Param status query string false "status"
// @Param beginTime query string false "beginTime"
// @Param endTime query string false "endTime"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-opera-log [get]
// @Security Bearer
func (e SysOperaLog) GetPage(c *gin.Context) {
s := service.SysOperaLog{}
req := new(dto.SysOperaLogGetPageReq)
err := e.MakeContext(c).
MakeOrm().
Bind(req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]models.SysOperaLog, 0)
var count int64
err = s.GetPage(req, &list, &count)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// Get 操作日志通过id获取
// @Summary 操作日志通过id获取
// @Description 获取JSON
// @Tags 操作日志
// @Param id path string false "id"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-opera-log/{id} [get]
// @Security Bearer
func (e SysOperaLog) Get(c *gin.Context) {
s := new(service.SysOperaLog)
req :=dto.SysOperaLogGetReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var object models.SysOperaLog
err = s.Get(&req, &object)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.OK(object, "查询成功")
}
// Delete 操作日志删除
// DeleteSysMenu 操作日志删除
// @Summary 删除操作日志
// @Description 删除数据
// @Tags 操作日志
// @Param data body dto.SysOperaLogDeleteReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-opera-log [delete]
// @Security Bearer
func (e SysOperaLog) Delete(c *gin.Context) {
s := new(service.SysOperaLog)
req :=dto.SysOperaLogDeleteReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
err = s.Remove(&req)
if err != nil {
e.Logger.Error(err)
e.Error(500,err, fmt.Sprintf("删除失败!错误详情:%s", err.Error()))
return
}
e.OK(req.GetId(), "删除成功")
}
+184
View File
@@ -0,0 +1,184 @@
package apis
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/v2/response"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
)
type SysPost struct {
api.Api
}
// GetPage
// @Summary 岗位列表数据
// @Description 获取JSON
// @Tags 岗位
// @Param postName query string false "postName"
// @Param postCode query string false "postCode"
// @Param postId query string false "postId"
// @Param status query string false "status"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post [get]
// @Security Bearer
func (e SysPost) GetPage(c *gin.Context) {
s := service.SysPost{}
req :=dto.SysPostPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]models.SysPost, 0)
var count int64
err = s.GetPage(&req, &list, &count)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// Get
// @Summary 获取岗位信息
// @Description 获取JSON
// @Tags 岗位
// @Param id path int true "编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post/{postId} [get]
// @Security Bearer
func (e SysPost) Get(c *gin.Context) {
s := service.SysPost{}
req :=dto.SysPostGetReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var object models.SysPost
err = s.Get(&req, &object)
if err != nil {
e.Error(500, err, fmt.Sprintf("岗位信息获取失败!错误详情:%s", err.Error()))
return
}
e.OK(object, "查询成功")
}
// Insert
// @Summary 添加岗位
// @Description 获取JSON
// @Tags 岗位
// @Accept application/json
// @Product application/json
// @Param data body dto.SysPostInsertReq true "data"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post [post]
// @Security Bearer
func (e SysPost) Insert(c *gin.Context) {
s := service.SysPost{}
req :=dto.SysPostInsertReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetCreateBy(user.GetUserId(c))
err = s.Insert(&req)
if err != nil {
e.Error(500, err, fmt.Sprintf("新建岗位失败!错误详情:%s", err.Error()))
return
}
e.OK(req.GetId(), "创建成功")
}
// Update
// @Summary 修改岗位
// @Description 获取JSON
// @Tags 岗位
// @Accept application/json
// @Product application/json
// @Param data body dto.SysPostUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post/{id} [put]
// @Security Bearer
func (e SysPost) Update(c *gin.Context) {
s := service.SysPost{}
req :=dto.SysPostUpdateReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Update(&req)
if err != nil {
e.Error(500, err, fmt.Sprintf("岗位更新失败!错误详情:%s", err.Error()))
return
}
e.OK(req.GetId(), "更新成功")
}
// Delete
// @Summary 删除岗位
// @Description 删除数据
// @Tags 岗位
// @Param id body dto.SysPostDeleteReq true "请求参数"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post [delete]
// @Security Bearer
func (e SysPost) Delete(c *gin.Context) {
s := service.SysPost{}
req :=dto.SysPostDeleteReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.Remove(&req)
if err != nil {
e.Error(500, err, fmt.Sprintf("岗位删除失败!错误详情:%s", err.Error()))
return
}
e.OK(req.GetId(), "删除成功")
}
+284
View File
@@ -0,0 +1,284 @@
package apis
import (
"fmt"
"go-admin/common/global"
"net/http"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/v2/sdk"
"go-admin/app/admin/models"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/v2/response"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
)
type SysRole struct {
api.Api
}
// GetPage
// @Summary 角色列表数据
// @Description Get JSON
// @Tags 角色/Role
// @Param roleName query string false "roleName"
// @Param status query string false "status"
// @Param roleKey query string false "roleKey"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role [get]
// @Security Bearer
func (e SysRole) GetPage(c *gin.Context) {
s := service.SysRole{}
req := dto.SysRoleGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
list := make([]models.SysRole, 0)
var count int64
err = s.GetPage(&req, &list, &count)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// Get
// @Summary 获取Role数据
// @Description 获取JSON
// @Tags 角色/Role
// @Param roleId path string false "roleId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role/{id} [get]
// @Security Bearer
func (e SysRole) Get(c *gin.Context) {
s := service.SysRole{}
req := dto.SysRoleGetReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, fmt.Sprintf(" %s ", err.Error()))
return
}
var object models.SysRole
err = s.Get(&req, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查询成功")
}
// Insert
// @Summary 创建角色
// @Description 获取JSON
// @Tags 角色/Role
// @Accept application/json
// @Product application/json
// @Param data body dto.SysRoleInsertReq true "data"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role [post]
// @Security Bearer
func (e SysRole) Insert(c *gin.Context) {
s := service.SysRole{}
req := dto.SysRoleInsertReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
// 设置创建人
req.CreateBy = user.GetUserId(c)
if req.Status == "" {
req.Status = "2"
}
cb := sdk.Runtime.GetCasbinByTenant(c.Request.Host)
err = s.Insert(&req, cb)
if err != nil {
e.Logger.Error(err)
e.Error(500, err, "创建失败,"+err.Error())
return
}
_, err = global.LoadPolicy(c)
if err != nil {
e.Logger.Error(err)
e.Error(500, err, "创建失败,"+err.Error())
return
}
e.OK(req.GetId(), "创建成功")
}
// Update 修改用户角色
// @Summary 修改用户角色
// @Description 获取JSON
// @Tags 角色/Role
// @Accept application/json
// @Product application/json
// @Param data body dto.SysRoleUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role/{id} [put]
// @Security Bearer
func (e SysRole) Update(c *gin.Context) {
s := service.SysRole{}
req := dto.SysRoleUpdateReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, nil, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
cb := sdk.Runtime.GetCasbinByTenant(c.Request.Host)
req.SetUpdateBy(user.GetUserId(c))
err = s.Update(&req, cb)
if err != nil {
e.Logger.Error(err)
return
}
_, err = global.LoadPolicy(c)
if err != nil {
e.Logger.Error(err)
e.Error(500, err, "更新失败,"+err.Error())
return
}
e.OK(req.GetId(), "更新成功")
}
// Delete
// @Summary 删除用户角色
// @Description 删除数据
// @Tags 角色/Role
// @Param data body dto.SysRoleDeleteReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role [delete]
// @Security Bearer
func (e SysRole) Delete(c *gin.Context) {
s := new(service.SysRole)
req := dto.SysRoleDeleteReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, fmt.Sprintf("删除角色 %v 失败,\r\n失败信息 %s", req.Ids, err.Error()))
return
}
cb := sdk.Runtime.GetCasbinByTenant(c.Request.Host)
err = s.Remove(&req, cb)
if err != nil {
e.Logger.Error(err)
e.Error(500, err, "")
return
}
e.OK(req.GetId(), fmt.Sprintf("删除角色角色 %v 状态成功!", req.GetId()))
}
// Update2Status 修改用户角色状态
// @Summary 修改用户角色
// @Description 获取JSON
// @Tags 角色/Role
// @Accept application/json
// @Product application/json
// @Param data body dto.UpdateStatusReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role-status/{id} [put]
// @Security Bearer
func (e SysRole) Update2Status(c *gin.Context) {
s := service.SysRole{}
req := dto.UpdateStatusReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, fmt.Sprintf("更新角色状态失败,失败原因:%s ", err.Error()))
return
}
req.SetUpdateBy(user.GetUserId(c))
err = s.UpdateStatus(&req)
if err != nil {
e.Error(500, err, fmt.Sprintf("更新角色状态失败,失败原因:%s ", err.Error()))
return
}
e.OK(req.GetId(), fmt.Sprintf("更新角色 %v 状态成功!", req.GetId()))
}
// Update2DataScope 更新角色数据权限
// @Summary 更新角色数据权限
// @Description 获取JSON
// @Tags 角色/Role
// @Accept application/json
// @Product application/json
// @Param data body dto.RoleDataScopeReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role-status/{id} [put]
// @Security Bearer
func (e SysRole) Update2DataScope(c *gin.Context) {
s := service.SysRole{}
req := dto.RoleDataScopeReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
data := &models.SysRole{
RoleId: req.RoleId,
DataScope: req.DataScope,
DeptIds: req.DeptIds,
}
data.UpdateBy = user.GetUserId(c)
err = s.UpdateDataScope(&req).Error
if err != nil {
e.Error(500, err, fmt.Sprintf("更新角色数据权限失败!错误详情:%s", err.Error()))
return
}
e.OK(nil, "操作成功")
}
+459
View File
@@ -0,0 +1,459 @@
package apis
import (
"github.com/gin-gonic/gin/binding"
"go-admin/app/admin/models"
"golang.org/x/crypto/bcrypt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/v2/response"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"github.com/google/uuid"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
)
type SysUser struct {
api.Api
}
// GetPage
// @Summary 列表用户信息数据
// @Description 获取JSON
// @Tags 用户
// @Param username query string false "username"
// @Success 200 {string} {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-user [get]
// @Security Bearer
func (e SysUser) GetPage(c *gin.Context) {
s := service.SysUser{}
req := dto.SysUserGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
//数据权限检查
p := actions.GetPermissionFromContext(c)
list := make([]models.SysUser, 0)
var count int64
err = s.GetPage(&req, p, &list, &count)
if err != nil {
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// Get
// @Summary 获取用户
// @Description 获取JSON
// @Tags 用户
// @Param userId path int true "用户编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-user/{userId} [get]
// @Security Bearer
func (e SysUser) Get(c *gin.Context) {
s := service.SysUser{}
req := dto.SysUserById{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
var object models.SysUser
//数据权限检查
p := actions.GetPermissionFromContext(c)
err = s.Get(&req, p, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查询成功")
}
// Insert
// @Summary 创建用户
// @Description 获取JSON
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body dto.SysUserInsertReq true "用户数据"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-user [post]
// @Security Bearer
func (e SysUser) Insert(c *gin.Context) {
s := service.SysUser{}
req := dto.SysUserInsertReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
// 设置创建人
req.SetCreateBy(user.GetUserId(c))
err = s.Insert(&req)
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
e.OK(req.GetId(), "创建成功")
}
// Update
// @Summary 修改用户数据
// @Description 获取JSON
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body dto.SysUserUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-user/{userId} [put]
// @Security Bearer
func (e SysUser) Update(c *gin.Context) {
s := service.SysUser{}
req := dto.SysUserUpdateReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
//数据权限检查
p := actions.GetPermissionFromContext(c)
err = s.Update(&req, p)
if err != nil {
e.Logger.Error(err)
return
}
e.OK(req.GetId(), "更新成功")
}
// Delete
// @Summary 删除用户数据
// @Description 删除数据
// @Tags 用户
// @Param userId path int true "userId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-user/{userId} [delete]
// @Security Bearer
func (e SysUser) Delete(c *gin.Context) {
s := service.SysUser{}
req := dto.SysUserById{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
// 设置编辑人
req.SetUpdateBy(user.GetUserId(c))
// 数据权限检查
p := actions.GetPermissionFromContext(c)
err = s.Remove(&req, p)
if err != nil {
e.Logger.Error(err)
return
}
e.OK(req.GetId(), "删除成功")
}
// InsetAvatar
// @Summary 修改头像
// @Description 获取JSON
// @Tags 个人中心
// @Accept multipart/form-data
// @Param file formData file true "file"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/avatar [post]
// @Security Bearer
func (e SysUser) InsetAvatar(c *gin.Context) {
s := service.SysUser{}
req := dto.UpdateSysUserAvatarReq{}
err := e.MakeContext(c).
MakeOrm().
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
// 数据权限检查
p := actions.GetPermissionFromContext(c)
form, _ := c.MultipartForm()
files := form.File["upload[]"]
guid := uuid.New().String()
filPath := "static/uploadfile/" + guid + ".jpg"
for _, file := range files {
e.Logger.Debugf("upload avatar file: %s", file.Filename)
// 上传文件至指定目录
err = c.SaveUploadedFile(file, filPath)
if err != nil {
e.Logger.Errorf("save file error, %s", err.Error())
e.Error(500, err, "")
return
}
}
req.UserId = p.UserId
req.Avatar = "/" + filPath
err = s.UpdateAvatar(&req, p)
if err != nil {
e.Logger.Error(err)
return
}
e.OK(filPath, "修改成功")
}
// UpdateStatus 修改用户状态
// @Summary 修改用户状态
// @Description 获取JSON
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body dto.UpdateSysUserStatusReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/status [put]
// @Security Bearer
func (e SysUser) UpdateStatus(c *gin.Context) {
s := service.SysUser{}
req := dto.UpdateSysUserStatusReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON, nil).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
//数据权限检查
p := actions.GetPermissionFromContext(c)
err = s.UpdateStatus(&req, p)
if err != nil {
e.Logger.Error(err)
return
}
e.OK(req.GetId(), "更新成功")
}
// ResetPwd 重置用户密码
// @Summary 重置用户密码
// @Description 获取JSON
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body dto.ResetSysUserPwdReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/pwd/reset [put]
// @Security Bearer
func (e SysUser) ResetPwd(c *gin.Context) {
s := service.SysUser{}
req := dto.ResetSysUserPwdReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.JSON).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.SetUpdateBy(user.GetUserId(c))
//数据权限检查
p := actions.GetPermissionFromContext(c)
err = s.ResetPwd(&req, p)
if err != nil {
e.Logger.Error(err)
return
}
e.OK(req.GetId(), "更新成功")
}
// UpdatePwd
// @Summary 修改密码
// @Description 获取JSON
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body dto.PassWord true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/pwd/set [put]
// @Security Bearer
func (e SysUser) UpdatePwd(c *gin.Context) {
s := service.SysUser{}
req := dto.PassWord{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
// 数据权限检查
p := actions.GetPermissionFromContext(c)
var hash []byte
if hash, err = bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost); err != nil {
req.NewPassword = string(hash)
}
err = s.UpdatePwd(user.GetUserId(c), req.OldPassword, req.NewPassword, p)
if err != nil {
e.Logger.Error(err)
e.Error(http.StatusForbidden, err, "密码修改失败")
return
}
e.OK(nil, "密码修改成功")
}
// GetProfile
// @Summary 获取个人中心用户
// @Description 获取JSON
// @Tags 个人中心
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/profile [get]
// @Security Bearer
func (e SysUser) GetProfile(c *gin.Context) {
s := service.SysUser{}
req := dto.SysUserById{}
err := e.MakeContext(c).
MakeOrm().
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
req.Id = user.GetUserId(c)
sysUser := models.SysUser{}
roles := make([]models.SysRole, 0)
posts := make([]models.SysPost, 0)
err = s.GetProfile(&req, &sysUser, &roles, &posts)
if err != nil {
e.Logger.Errorf("get user profile error, %s", err.Error())
e.Error(500, err, "获取用户信息失败")
return
}
e.OK(gin.H{
"user": sysUser,
"roles": roles,
"posts": posts,
}, "查询成功")
}
// GetInfo
// @Summary 获取个人信息
// @Description 获取JSON
// @Tags 个人中心
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/getinfo [get]
// @Security Bearer
func (e SysUser) GetInfo(c *gin.Context) {
req := dto.SysUserById{}
s := service.SysUser{}
r := service.SysRole{}
err := e.MakeContext(c).
MakeOrm().
MakeService(&r.Service).
MakeService(&s.Service).
Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
p := actions.GetPermissionFromContext(c)
var roles = make([]string, 1)
roles[0] = user.GetRoleName(c)
var permissions = make([]string, 1)
permissions[0] = "*:*:*"
var buttons = make([]string, 1)
buttons[0] = "*:*:*"
var mp = make(map[string]interface{})
mp["roles"] = roles
if user.GetRoleName(c) == "admin" || user.GetRoleName(c) == "系统管理员" {
mp["permissions"] = permissions
mp["buttons"] = buttons
} else {
list, _ := r.GetById(user.GetRoleId(c))
mp["permissions"] = list
mp["buttons"] = list
}
sysUser := models.SysUser{}
req.Id = user.GetUserId(c)
err = s.Get(&req, p, &sysUser)
if err != nil {
e.Error(http.StatusUnauthorized, err, "登录失败")
return
}
mp["introduction"] = " am a super administrator"
mp["avatar"] = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"
if sysUser.Avatar != "" {
mp["avatar"] = sysUser.Avatar
}
mp["userName"] = sysUser.Username
mp["userId"] = sysUser.UserId
mp["deptId"] = sysUser.DeptId
mp["name"] = sysUser.NickName
mp["code"] = 200
e.OK(mp, "")
}
-472
View File
@@ -1,472 +0,0 @@
package sys_user
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"github.com/google/uuid"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
"go-admin/common/apis"
common "go-admin/common/models"
)
type SysUser struct {
apis.Api
}
// @Summary 列表用户信息数据
// @Description 获取JSON
// @Tags 用户
// @Param username query string false "username"
// @Success 200 {string} string "{"code": 200, "data": [...]}"
// @Success 200 {string} string "{"code": -1, "message": "抱歉未找到相关信息"}"
// @Router /api/v1/sysUser [get]
// @Security Bearer
func (e SysUser) GetSysUserList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysUserSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
req := d.Generate()
//查询列表
err = req.Bind(c)
if err != nil {
log.Warnf("Bind error: %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
//数据权限检查
p := actions.GetPermissionFromContext(c)
list := make([]system.SysUser, 0)
var count int64
serviceStudent := service.SysUser{}
serviceStudent.Log = log
serviceStudent.Orm = db
err = serviceStudent.GetSysUserPage(req, p, &list, &count)
if err != nil {
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// @Summary 获取用户
// @Description 获取JSON
// @Tags 用户
// @Param userId path int true "用户编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sysUser/{userId} [get]
// @Security Bearer
func (e SysUser) GetSysUser(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysUserById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
req := control.Generate()
err = req.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object system.SysUser
//数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysUser := service.SysUser{}
serviceSysUser.Log = log
serviceSysUser.Orm = db
err = serviceSysUser.GetSysUser(req, p, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
// @Summary 创建用户
// @Description 获取JSON
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body dto.SysUserControl true "用户数据"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/sysUser [post]
func (e SysUser) InsertSysUser(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysUserControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
req := control.Generate()
err = req.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object common.ActiveRecord
object, err = req.GenerateM()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
serviceSysUser := service.SysUser{}
serviceSysUser.Orm = db
serviceSysUser.Log = log
err = serviceSysUser.InsertSysUser(object)
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(object.GetId(), "创建成功")
}
// @Summary 修改用户数据
// @Description 获取JSON
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body dto.SysUserControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string "{"code": -1, "message": "修改失败"}"
// @Router /api/v1/sysuser/{userId} [put]
func (e SysUser) UpdateSysUser(c *gin.Context) {
control := new(dto.SysUserControl)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
req := control.Generate()
//更新操作
err = req.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object common.ActiveRecord
object, err = req.GenerateM()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
//数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysUser := service.SysUser{}
serviceSysUser.Orm = db
serviceSysUser.Log = log
err = serviceSysUser.UpdateSysUser(object, p)
if err != nil {
log.Error(err)
return
}
e.OK(object.GetId(), "更新成功")
}
// @Summary 删除用户数据
// @Description 删除数据
// @Tags 用户
// @Param userId path int true "userId"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/sysuser/{userId} [delete]
func (e SysUser) DeleteSysUser(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysUserById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
req := control.Generate()
err = req.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object common.ActiveRecord
object, err = req.GenerateM()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置编辑人
object.SetUpdateBy(user.GetUserId(c))
// 数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysUser := service.SysUser{}
serviceSysUser.Orm = db
serviceSysUser.Log = log
err = serviceSysUser.RemoveSysUser(req, object, p)
if err != nil {
log.Error(err)
return
}
e.OK(object.GetId(), "删除成功")
}
// @Summary 修改头像
// @Description 获取JSON
// @Tags 用户
// @Accept multipart/form-data
// @Param file formData file true "file"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/user/avatar [post]
func (e SysUser) InsetSysUserAvatar(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
// 数据权限检查
p := actions.GetPermissionFromContext(c)
form, _ := c.MultipartForm()
files := form.File["upload[]"]
guid := uuid.New().String()
filPath := "static/uploadfile/" + guid + ".jpg"
for _, file := range files {
log.Debugf("upload avatar file: %s", file.Filename)
// 上传文件至指定目录
err = c.SaveUploadedFile(file, filPath)
if err != nil {
log.Errorf("save file error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "")
return
}
}
object := &system.SysUser{
UserId: p.UserId,
Avatar: "/" + filPath,
}
serviceSysUser := service.SysUser{}
serviceSysUser.Orm = db
serviceSysUser.Log = log
err = serviceSysUser.UpdateSysUser(object, p)
if err != nil {
log.Error(err)
return
}
e.OK(filPath, "修改成功")
}
// @Summary 重置密码
// @Description 获取JSON
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body dto.PassWord true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/pwd [post]
// @Security Bearer
func (e SysUser) SysUserUpdatePwd(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
var pwd dto.PassWord
err = c.Bind(&pwd)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
// 数据权限检查
p := actions.GetPermissionFromContext(c)
serviceSysUser := service.SysUser{}
serviceSysUser.Orm = db
serviceSysUser.Log = log
err = serviceSysUser.UpdateSysUserPwd(user.GetUserId(c), pwd.OldPassword, pwd.NewPassword, p)
if err != nil {
log.Error(err)
e.Error(http.StatusForbidden, err, "密码修改失败")
return
}
e.OK(nil, "密码修改成功")
}
// @Summary 获取个人中心用户
// @Description 获取JSON
// @Tags 个人中心
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/profile [get]
// @Security Bearer
func (e SysUser) GetSysUserProfile(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
id := user.GetUserId(c)
serviceSysUser := service.SysUser{}
serviceSysUser.Log = log
serviceSysUser.Orm = db
user := new(system.SysUser)
roles := make([]system.SysRole, 0)
posts := make([]system.SysPost, 0)
err = serviceSysUser.GetSysUserProfile(id, user, &roles, &posts)
if err != nil {
log.Errorf("get user profile error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "获取用户信息失败")
return
}
e.OK(gin.H{
"user": user,
"roles": roles,
"posts": posts,
}, "查询成功")
//var SysUser models.SysUser
//userId := tools.GetUserIdStr(c)
//SysUser.UserId, _ = tools.StringToInt(userId)
//result, err := SysUser.Get()
//tools.HasError(err, "抱歉未找到相关信息", -1)
//var SysRole models.SysRole
//var Post models.Post
//var Dept models.SysDepts
////获取角色列表
//roles, err := SysRole.GetList()
////获取职位列表
//posts, err := Post.GetList()
////获取部门列表
//Dept.DeptId = result.DeptId
//dept, err := Dept.Get()
//
//postIds := make([]int, 0)
//postIds = append(postIds, result.PostId)
//
//roleIds := make([]int, 0)
//roleIds = append(roleIds, result.RoleId)
//
//app.Custum(c, gin.H{
// "code": 200,
// "data": result,
// "postIds": postIds,
// "roleIds": roleIds,
// "roles": roles,
// "posts": posts,
// "dept": dept,
//})
}
func (e SysUser) GetInfo(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//数据权限检查
p := actions.GetPermissionFromContext(c)
var roles = make([]string, 1)
roles[0] = user.GetRoleName(c)
var permissions = make([]string, 1)
permissions[0] = "*:*:*"
var buttons = make([]string, 1)
buttons[0] = "*:*:*"
RoleMenu := system.RoleMenu{}
RoleMenu.RoleId = user.GetRoleId(c)
var mp = make(map[string]interface{})
mp["roles"] = roles
if user.GetRoleName(c) == "admin" || user.GetRoleName(c) == "系统管理员" {
mp["permissions"] = permissions
mp["buttons"] = buttons
} else {
list, _ := RoleMenu.GetPermis(db)
mp["permissions"] = list
mp["buttons"] = list
}
var sysUser system.SysUser
req := new(dto.SysUserById)
req.Id = user.GetUserId(c)
serviceSysUser := service.SysUser{}
serviceSysUser.Log = log
serviceSysUser.Orm = db
err = serviceSysUser.GetSysUser(req, p, &sysUser)
if err != nil {
e.Error(http.StatusUnauthorized, err, "登录失败")
return
}
mp["introduction"] = " am a super administrator"
mp["avatar"] = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"
if sysUser.Avatar != "" {
mp["avatar"] = sysUser.Avatar
}
mp["userName"] = sysUser.NickName
mp["userId"] = sysUser.UserId
mp["deptId"] = sysUser.DeptId
mp["name"] = sysUser.NickName
e.OK(mp, "")
}
-28
View File
@@ -1,28 +0,0 @@
package system
import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/captcha"
"go-admin/common/apis"
)
type System struct {
apis.Api
}
func (e System) GenerateCaptchaHandler(c *gin.Context) {
e.Context = c
log := e.GetLogger()
id, b64s, err := captcha.DriverDigitFunc()
if err != nil {
log.Errorf("DriverDigitFunc error, %s", err.Error())
e.Error(500, err, "验证码获取失败")
return
}
e.Custom(gin.H{
"code": 200,
"data": b64s,
"id": id,
"msg": "success",
})
}
-269
View File
@@ -1,269 +0,0 @@
package dict
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
common "go-admin/common/models"
)
type SysDictData struct {
apis.Api
}
// @Summary 字典数据列表
// @Description 获取JSON
// @Tags 字典数据
// @Param status query string false "status"
// @Param dictCode query string false "dictCode"
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/data [get]
// @Security Bearer
func (e SysDictData) GetSysDictDataList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
req := &dto.SysDictDataSearch{}
//查询列表
err = req.Bind(c)
if err != nil {
log.Warnf("Bind error: %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]system.SysDictData, 0)
var count int64
s := service.SysDictData{}
s.Log = log
s.Orm = db.Debug()
err = s.GetPage(req, &list, &count)
if err != nil {
log.Errorf("GetPage error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// @Summary 通过编码获取字典数据
// @Description 获取JSON
// @Tags 字典数据
// @Param dictCode path int true "字典编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/data/{dictCode} [get]
// @Security Bearer
func (e SysDictData) GetSysDictData(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
req := &dto.SysDictDataById{}
err = req.Bind(c)
if err != nil {
log.Warnf("Bind error: %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object system.SysDictData
s := service.SysDictData{}
s.Log = log
s.Orm = db
err = s.Get(req, &object)
if err != nil {
log.Warnf("Get error: %s", err.Error())
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
// @Summary 添加字典数据
// @Description 获取JSON
// @Tags 字典数据
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDictDataControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/data [post]
// @Security Bearer
func (e SysDictData) InsertSysDictData(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
req := &dto.SysDictDataControl{}
err = req.Bind(c)
if err != nil {
log.Warnf("Bind error: %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, _ := req.GenerateM()
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
s := service.SysDictData{}
s.Orm = db
s.Log = log
err = s.Insert(object.(*system.SysDictData))
if err != nil {
log.Errorf("Insert error, %s", err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(object.GetId(), "创建成功")
}
// @Summary 修改字典数据
// @Description 获取JSON
// @Tags 字典数据
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDictDataControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/data/{dictCode} [put]
// @Security Bearer
func (e SysDictData) UpdateSysDictData(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
req := &dto.SysDictDataControl{}
//更新操作
err = req.Bind(c)
if err != nil {
log.Warnf("request validate error, %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, _ := req.GenerateM()
object.SetUpdateBy(user.GetUserId(c))
s := service.SysDictData{}
s.Orm = db
s.Log = log
err = s.Update(object.(*system.SysDictData))
if err != nil {
log.Errorf("Update error, %s", err)
e.Error(http.StatusInternalServerError, err, "更新失败")
return
}
e.OK(object.GetId(), "更新成功")
}
// @Summary 删除字典数据
// @Description 删除数据
// @Tags 字典数据
// @Param dictCode path int true "dictCode"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/dict/data/{dictCode} [delete]
func (e SysDictData) DeleteSysDictData(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
req := new(dto.SysDictDataById)
err = req.Bind(c)
if err != nil {
log.Warnf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object common.ActiveRecord
object, err = req.GenerateM()
if err != nil {
log.Errorf("GenerateM error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置编辑人
object.SetUpdateBy(user.GetUserId(c))
s := service.SysDictData{}
s.Orm = db
s.Log = log
err = s.Remove(req, object.(*system.SysDictData))
if err != nil {
log.Errorf("Remove error, %s", err)
e.Error(http.StatusInternalServerError, err, "删除失败")
return
}
e.OK(object.GetId(), "删除成功")
}
func (e SysDictData) GetSysDictDataAll(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
req := &dto.SysDictDataSearch{}
//查询列表
err = req.Bind(c)
if err != nil {
log.Warnf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]system.SysDictData, 0)
s := service.SysDictData{}
s.Log = log
s.Orm = db
err = s.GetAll(req, &list)
if err != nil {
log.Errorf("GetAll error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.OK(list, "查询成功")
}
-267
View File
@@ -1,267 +0,0 @@
package dict
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
common "go-admin/common/models"
)
type SysDictType struct {
apis.Api
}
// @Summary 字典类型列表数据
// @Description 获取JSON
// @Tags 字典类型
// @Param dictName query string false "dictName"
// @Param dictId query string false "dictId"
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type [get]
// @Security Bearer
func (e SysDictType) GetSysDictTypeList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
req := &dto.SysDictTypeSearch{}
//查询列表
err = req.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]system.SysDictType, 0)
var count int64
s := service.SysDictType{}
s.Log = log
s.Orm = db.Debug()
err = s.GetPage(req, &list, &count)
if err != nil {
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
// @Summary 通过字典id获取字典类型
// @Description 获取JSON
// @Tags 字典类型
// @Param dictId path int true "字典类型编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type/{dictId} [get]
// @Security Bearer
func (e SysDictType) GetSysDictType(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
req := &dto.SysDictTypeById{}
err = req.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object system.SysDictType
s := service.SysDictType{}
s.Log = log
s.Orm = db
err = s.Get(req, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
// @Summary 添加字典类型
// @Description 获取JSON
// @Tags 字典类型
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDictTypeControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/type [post]
// @Security Bearer
func (e SysDictType) InsertSysDictType(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
req := &dto.SysDictTypeControl{}
err = req.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, _ := req.GenerateM()
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
s := service.SysDictType{}
s.Orm = db
s.Log = log
err = s.Insert(object.(*system.SysDictType))
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(object.GetId(), "创建成功")
}
// @Summary 修改字典类型
// @Description 获取JSON
// @Tags 字典类型
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDictTypeControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/type/{dictId} [put]
// @Security Bearer
func (e SysDictType) UpdateSysDictType(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
req := &dto.SysDictTypeControl{}
//更新操作
err = req.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, _ := req.GenerateM()
object.SetUpdateBy(user.GetUserId(c))
s := service.SysDictType{}
s.Orm = db
s.Log = log
err = s.Update(object.(*system.SysDictType))
if err != nil {
log.Error(err)
return
}
e.OK(object.GetId(), "更新成功")
}
// @Summary 删除字典类型
// @Description 删除数据
// @Tags 字典类型
// @Param dictId path int true "dictId"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/dict/type/{dictId} [delete]
func (e SysDictType) DeleteSysDictType(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
req := new(dto.SysDictTypeById)
err = req.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object common.ActiveRecord
object, err = req.GenerateM()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置编辑人
object.SetUpdateBy(user.GetUserId(c))
s := service.SysDictType{}
s.Orm = db
s.Log = log
err = s.Remove(req, object.(*system.SysDictType))
if err != nil {
log.Error(err)
return
}
e.OK(object.GetId(), "删除成功")
}
// @Summary 字典类型全部数据
// @Description 获取JSON
// @Tags 字典类型
// @Param dictName query string false "dictName"
// @Param dictId query string false "dictId"
// @Param dictType query string false "dictType"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type-option-select [get]
// @Security Bearer
func (e SysDictType) GetSysDictTypeAll(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
req := &dto.SysDictTypeSearch{}
//查询列表
err = req.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]system.SysDictType, 0)
s := service.SysDictType{}
s.Log = log
s.Orm = db
err = s.GetAll(req, &list)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(list, "查询成功")
}
-98
View File
@@ -1,98 +0,0 @@
package system
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
)
type SysSetting struct {
apis.Api
}
// @Summary 查询系统信息
// @Description 获取JSON
// @Tags 系统信息
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/setting [get]
func (e SysSetting) GetSetting(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
sysSettingService := service.SysSetting{}
sysSettingService.Log = log
sysSettingService.Orm = db
var model = models.SysSetting{}
err = sysSettingService.GetSysSetting(&model)
if err != nil {
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
if model.Logo != "" {
if !strings.HasPrefix(model.Logo, "http") {
model.Logo = fmt.Sprintf("http://%s/%s", c.Request.Host, model.Logo)
}
}
e.OK(model, "查询成功")
}
// @Summary 更新或提交系统信息
// @Description 获取JSON
// @Tags 系统信息
// @Param data body dto.SysSettingControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/system/setting [post]
func (e SysSetting) CreateOrUpdateSetting(c *gin.Context) {
control := new(dto.SysSettingControl)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
sysSettingService := service.SysSetting{}
sysSettingService.Log = log
sysSettingService.Orm = db
err = sysSettingService.UpdateSysSetting(object)
if err != nil {
e.Error(http.StatusInternalServerError, err, "更新失败")
return
}
if object.Logo != "" {
if !strings.HasPrefix(object.Logo, "http") {
object.Logo = fmt.Sprintf("http://%s/%s", c.Request.Host, object.Logo)
}
}
e.OK(object, "提交成功")
}
@@ -1,277 +0,0 @@
package sys_config
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
)
type SysConfig struct {
apis.Api
}
func (e SysConfig) GetSysConfigList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysConfigSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查询列表
err = d.Bind(c)
if err != nil {
log.Errorf("参数验证失败, error:%s", err)
e.Error(500, err, "参数验证失败")
return
}
list := make([]system.SysConfig, 0)
var count int64
s := service.SysConfig{}
s.Log = log
s.Orm = db
err = s.GetSysConfigPage(d, &list, &count)
if err != nil {
log.Errorf("GetSysConfigPage 查询失败, error:%s", err)
e.Error(500, err, "查询失败")
return
}
e.PageOK(list, int(count), d.GetPageIndex(), d.GetPageSize(), "查询成功")
}
// GetSysConfigBySysApp 获取系统配置信息,主要注意这里不在验证数据权限
func (e SysConfig) GetSysConfigBySysApp(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysConfigSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
err = d.Bind(c)
if err != nil {
log.Errorf("参数验证失败, error:%s", err)
e.Error(500, err, "参数验证失败")
return
}
// 控制只读前台的数据
d.IsFrontend = 1
list := make([]system.SysConfig, 0)
s := service.SysConfig{}
s.Log = log
s.Orm = db
err = s.GetSysConfigByKey(d, &list)
if err != nil {
log.Errorf("GetSysConfigPage 查询失败, error:%s", err)
e.Error(500, err, "查询失败")
return
}
mp := make(map[string]string)
for i := 0; i < len(list); i++ {
key := list[i].ConfigKey
if key != "" {
mp[key] = list[i].ConfigValue
}
}
e.OK(mp, "查询成功")
}
func (e SysConfig) GetSysConfig(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysConfigById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
var object system.SysConfig
serviceSysLoginLog := service.SysConfig{}
serviceSysLoginLog.Log = log
serviceSysLoginLog.Orm = db
err = serviceSysLoginLog.GetSysConfig(control, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
e.OK(object, "查看成功")
}
func (e SysConfig) InsertSysConfig(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysConfigControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
serviceSysLoginLog := service.SysConfig{}
serviceSysLoginLog.Orm = db
serviceSysLoginLog.Log = log
err = serviceSysLoginLog.InsertSysConfig(object)
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "创建失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
e.OK(object.GetId(), "创建成功")
}
func (e SysConfig) UpdateSysConfig(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysConfigControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
serviceSysLoginLog := service.SysConfig{}
serviceSysLoginLog.Orm = db
serviceSysLoginLog.Log = log
err = serviceSysLoginLog.UpdateSysConfig(object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "更新失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
e.OK(object.GetId(), "更新成功")
}
func (e SysConfig) DeleteSysConfig(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysConfigById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
err = control.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
object, err := control.GenerateM()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
// 设置编辑人
object.SetUpdateBy(user.GetUserId(c))
serviceSysLoginLog := service.SysConfig{}
serviceSysLoginLog.Orm = db
serviceSysLoginLog.Log = log
err = serviceSysLoginLog.RemoveSysConfig(control, object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "删除失败")
log.Errorf("Orm获取失败, error:%s", err)
e.Error(500, err, "Orm获取失败")
return
}
e.OK(object.GetId(), "删除成功")
}
// GetSysConfigByKEYForService 根据Key获取SysConfig的Service
func (e SysConfig) GetSysConfigByKEYForService(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
var v dto.SysConfigControl
err = v.Bind(c)
if err != nil {
log.Errorf("参数验证错误, error:%s", err)
e.Error(422, err, "参数验证失败")
return
}
s := service.SysConfig{}
s.Log = log
s.Orm = db
err = s.GetSysConfigByKEY(&v)
if err != nil {
log.Errorf("通过Key获取配置失败, error:%s", err)
e.Error(500, err, "")
return
}
e.OK(v, s.Msg)
}
-294
View File
@@ -1,294 +0,0 @@
package sys_dept
import (
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
)
type SysDept struct {
apis.Api
}
// @Summary 分页部门列表数据
// @Description 分页列表
// @Tags 部门
// @Param name query string false "name"
// @Param id query string false "id"
// @Param position query string false "position"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dept [get]
// @Security Bearer
func (e SysDept) GetSysDeptList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysDeptSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查询列表
err = d.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]system.SysDept, 0)
serviceStudent := service.SysDept{}
serviceStudent.Log = log
serviceStudent.Orm = db
list, err = serviceStudent.SetDeptPage(d)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(list, "查询成功")
}
// @Summary 部门列表数据
// @Description 获取JSON
// @Tags 部门
// @Param deptId path string false "deptId"
// @Param position query string false "position"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dept/{deptId} [get]
// @Security Bearer
func (e SysDept) GetSysDept(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysDeptById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object system.SysDept
serviceSysOperlog := service.SysDept{}
serviceSysOperlog.Log = log
serviceSysOperlog.Orm = db
err = serviceSysOperlog.GetSysDept(control, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
// @Summary 添加部门
// @Description 获取JSON
// @Tags 部门
// @Accept application/json
// @Product application/json
// @Param data body dto.SysDeptControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dept [post]
// @Security Bearer
func (e SysDept) InsertSysDept(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysDeptControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
serviceSysDept := service.SysDept{}
serviceSysDept.Orm = db
serviceSysDept.Log = log
err = serviceSysDept.InsertSysDept(object)
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(object.GetId(), "创建成功")
}
// @Summary 修改部门
// @Description 获取JSON
// @Tags 部门
// @Accept application/json
// @Product application/json
// @Param id path int true "id"
// @Param data body dto.SysDeptControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dept/{deptId} [put]
// @Security Bearer
func (e SysDept) UpdateSysDept(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysDeptControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
serviceSysDept := service.SysDept{}
serviceSysDept.Orm = db
serviceSysDept.Log = log
err = serviceSysDept.UpdateSysDept(object)
if err != nil {
log.Error(err)
return
}
e.OK(object.GetId(), "更新成功")
}
// @Summary 删除部门
// @Description 删除数据
// @Tags 部门
// @Param data body dto.SysDeptById true "body"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/dept [delete]
func (e SysDept) DeleteSysDept(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysDeptById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
err = control.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
serviceSysDept := service.SysDept{}
serviceSysDept.Orm = db
serviceSysDept.Log = log
err = serviceSysDept.RemoveSysDept(control)
if err != nil {
log.Errorf("RemoveSysDept error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "删除失败")
return
}
e.OK(control.GetId(), "删除成功")
}
// GetDeptTree 用户管理 左侧部门树
func (e SysDept) GetDeptTree(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysDeptSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查询列表
err = d.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]dto.DeptLabel, 0)
serviceStudent := service.SysDept{}
serviceStudent.Log = log
serviceStudent.Orm = db
list, err = serviceStudent.SetDeptTree(d)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
//var Dept models.SysDepts
//Dept.DeptName = c.Request.FormValue("deptName")
//Dept.Status = c.Request.FormValue("status")
//Dept.DeptId, _ = tools.StringToInt(c.Request.FormValue("deptId"))
//result, err := Dept.SetDept(false)
//tools.HasError(err, "抱歉未找到相关信息", -1)
e.OK(list, "")
}
func (e SysDept) GetDeptTreeRoleSelect(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
s := service.SysDept{}
s.Orm = db
s.Log = log
id, err := pkg.StringToInt(c.Param("roleId"))
result, err := s.SetDeptLabel()
if err != nil {
log.Errorf("SetDeptLabel error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "")
}
menuIds := make([]int, 0)
if id != 0 {
menuIds, err = s.GetRoleDeptId(id)
if err != nil {
log.Errorf("抱歉未找到相关信息, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "")
}
}
e.OK(gin.H{
"depts": result,
"checkedKeys": menuIds,
}, "")
}
@@ -1,188 +0,0 @@
package sys_login_log
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
)
type SysLoginLog struct {
apis.Api
}
func (e SysLoginLog) GetSysLoginLogList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysLoginLogSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查询列表
err = d.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]system.SysLoginLog, 0)
var count int64
serviceStudent := service.SysLoginLog{}
serviceStudent.Log = log
serviceStudent.Orm = db
err = serviceStudent.GetSysLoginLogPage(d, &list, &count)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.PageOK(list, int(count), d.GetPageIndex(), d.GetPageSize(), "查询成功")
}
func (e SysLoginLog) GetSysLoginLog(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysLoginLogById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object system.SysLoginLog
serviceSysLoginLog := service.SysLoginLog{}
serviceSysLoginLog.Log = log
serviceSysLoginLog.Orm = db
err = serviceSysLoginLog.GetSysLoginLog(control, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
func (e SysLoginLog) InsertSysLoginLog(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysLoginLogControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
serviceSysLoginLog := service.SysLoginLog{}
serviceSysLoginLog.Orm = db
serviceSysLoginLog.Log = log
err = serviceSysLoginLog.InsertSysLoginLog(object)
if err != nil {
log.Errorf("InsertSysLoginLog error, %s", err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(object.GetId(), "创建成功")
}
func (e SysLoginLog) UpdateSysLoginLog(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysLoginLogControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
serviceSysLoginLog := service.SysLoginLog{}
serviceSysLoginLog.Orm = db
serviceSysLoginLog.Log = log
err = serviceSysLoginLog.UpdateSysLoginLog(object)
if err != nil {
log.Errorf("UpdateSysLoginLog error, %s", err)
e.Error(http.StatusInternalServerError, err, "更新失败")
return
}
e.OK(object.GetId(), "更新成功")
}
func (e SysLoginLog) DeleteSysLoginLog(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysLoginLogById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
err = control.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.GenerateM()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置编辑人
object.SetUpdateBy(user.GetUserId(c))
serviceSysLoginLog := service.SysLoginLog{}
serviceSysLoginLog.Orm = db
serviceSysLoginLog.Log = log
err = serviceSysLoginLog.RemoveSysLoginLog(control, object)
if err != nil {
log.Errorf("RemoveSysLoginLog error, %s", err)
e.Error(http.StatusInternalServerError, err, "删除失败")
return
}
e.OK(object.GetId(), "删除成功")
}
-369
View File
@@ -1,369 +0,0 @@
package sys_menu
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
)
type SysMenu struct {
apis.Api
}
// @Summary Menu列表数据
// @Description 获取JSON
// @Tags 菜单
// @Param menuName query string false "menuName"
// @Success 200 {string} string "{"code": 200, "data": [...]}"
// @Success 200 {string} string "{"code": -1, "message": "抱歉未找到相关信息"}"
// @Router /api/v1/menulist [get]
// @Security Bearer
func (e SysMenu) GetSysMenuList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysMenuSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查询列表
err = d.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var list *[]system.SysMenu
serviceSysMenu := service.SysMenu{}
serviceSysMenu.Log = log
serviceSysMenu.Orm = db
list, err = serviceSysMenu.GetSysMenuPage(d)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(list, "查询成功")
}
// @Summary Menu详情数据
// @Description 获取JSON
// @Tags 菜单
// @Param menuName query string false "menuName"
// @Success 200 {string} string "{"code": 200, "data": [...]}"
// @Success 200 {string} string "{"code": -1, "message": "抱歉未找到相关信息"}"
// @Router /api/v1/menu/{id} [get]
// @Security Bearer
func (e SysMenu) GetSysMenu(c *gin.Context) {
control := new(dto.SysMenuById)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object system.SysMenu
serviceSysMenu := service.SysMenu{}
serviceSysMenu.Log = log
serviceSysMenu.Orm = db
err = serviceSysMenu.GetSysMenu(control, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
// @Summary 创建菜单
// @Description 获取JSON
// @Tags 菜单
// @Accept application/x-www-form-urlencoded
// @Product application/x-www-form-urlencoded
// @Param menuName formData string true "menuName"
// @Param Path formData string false "Path"
// @Param Action formData string true "Action"
// @Param Permission formData string true "Permission"
// @Param ParentId formData string true "ParentId"
// @Param IsDel formData string true "IsDel"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/menu [post]
// @Security Bearer
func (e SysMenu) InsertSysMenu(c *gin.Context) {
control := new(dto.SysMenuControl)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
serviceSysMenu := service.SysMenu{}
serviceSysMenu.Orm = db
serviceSysMenu.Log = log
err = serviceSysMenu.InsertSysMenu(object)
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(object.GetId(), "创建成功")
}
// @Summary 修改菜单
// @Description 获取JSON
// @Tags 菜单
// @Accept application/x-www-form-urlencoded
// @Product application/x-www-form-urlencoded
// @Param id path int true "id"
// @Param data body dto.SysMenuControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string "{"code": -1, "message": "修改失败"}"
// @Router /api/v1/menu/{id} [put]
// @Security Bearer
func (e SysMenu) UpdateSysMenu(c *gin.Context) {
control := new(dto.SysMenuControl)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
serviceSysMenu := service.SysMenu{}
serviceSysMenu.Orm = db
serviceSysMenu.Log = log
err = serviceSysMenu.UpdateSysMenu(object)
if err != nil {
log.Error(err)
return
}
e.OK(object.GetId(), "更新成功")
}
// @Summary 删除菜单
// @Description 删除数据
// @Tags 菜单
// @Param data body dto.SysMenuById true "body"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/menu/ [delete]
func (e SysMenu) DeleteSysMenu(c *gin.Context) {
control := new(dto.SysMenuById)
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
err = control.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
serviceSysMenu := service.SysMenu{}
serviceSysMenu.Orm = db
serviceSysMenu.Log = log
err = serviceSysMenu.RemoveSysMenu(control)
if err != nil {
log.Errorf("RemoveSysMenu error, %s", err)
e.Error(http.StatusInternalServerError, err, "删除失败")
return
}
e.OK(control.GetId(), "删除成功")
}
// @Summary 根据角色名称获取菜单列表数据(左菜单使用)
// @Description 获取JSON
// @Tags 菜单
// @Param id path int true "id"
// @Success 200 {string} string "{"code": 200, "data": [...]}"
// @Success 200 {string} string "{"code": -1, "message": "抱歉未找到相关信息"}"
// @Router /api/v1/menurole [get]
// @Security Bearer
func (e SysMenu) GetMenuRole(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
serviceSysMenu := service.SysMenu{}
serviceSysMenu.Log = log
serviceSysMenu.Orm = db
result, err := serviceSysMenu.SetMenuRole(user.GetRoleName(c))
if err != nil {
e.Error(http.StatusInternalServerError, err, "查询失败")
return
}
e.OK(result, "")
}
// @Summary 获取角色对应的菜单id数组
// @Description 获取JSON
// @Tags 菜单
// @Param id path int true "id"
// @Success 200 {string} string "{"code": 200, "data": [...]}"
// @Success 200 {string} string "{"code": -1, "message": "抱歉未找到相关信息"}"
// @Router /api/v1/menuids/{id} [get]
// @Security Bearer
func (e SysMenu) GetMenuIDS(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
var data system.RoleMenu
data.RoleName = c.GetString("role")
data.UpdateBy = user.GetUserId(c)
result, err := data.GetIDS(db)
if err != nil {
log.Errorf("GetIDS error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "获取失败")
return
}
e.OK(result, "")
}
//// GetMenuTreeRoleselect 角色修改中的菜单列表
//func (e SysMenu) GetMenuTreeRoleselect(c *gin.Context) {
// var Menu models.Menu
// var SysRole models.SysRole
//
// id, err := tools.StringToInt(c.Param("roleId"))
// SysRole.RoleId = id
// //var r *models.SysRole
// r, err := SysRole.Get()
//
// var result *[]models.MenuLable
// menuIds := make([]int, 0)
// if r.RoleKey != "admin" {
// result, err = Menu.SetMenuLabel()
// tools.HasError(err, "抱歉未找到相关信息", -1)
// if id != 0 {
// menuIds, err = SysRole.GetRoleMeunId()
// tools.HasError(err, "抱歉未找到相关信息", -1)
// }
// }
// app.Custum(c, gin.H{
// "code": 200,
// "menus": result,
// "checkedKeys": menuIds,
// })
//}
// @Summary 获取菜单树
// @Description 获取JSON
// @Tags 菜单
// @Accept application/x-www-form-urlencoded
// @Product application/x-www-form-urlencoded
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/menuTreeselect [get]
// @Security Bearer
func (e SysMenu) GetMenuTreeSelect(c *gin.Context) {
e.Context = c
log := e.GetLogger()
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
d := new(dto.SelectRole)
err = c.BindUri(d)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
serviceSysMenu := service.SysMenu{}
serviceSysMenu.Log = log
serviceSysMenu.Orm = db
result, err := serviceSysMenu.SetSysMenuLabel()
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
s := service.SysRole{}
s.Log = log
s.Orm = db
menuIds, err := s.GetRoleMenuId(db, d.RoleId)
if err != nil {
log.Errorf("GetIDS error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "")
return
}
e.OK(gin.H{
"menus": result,
"checkedKeys": menuIds,
}, "获取成功")
}
@@ -1,178 +0,0 @@
package sys_opera_log
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
)
type SysOperaLog struct {
apis.Api
}
func (e SysOperaLog) GetSysOperaLogList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysOperaLogSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查询列表
err = d.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]system.SysOperaLog, 0)
var count int64
serviceStudent := service.SysOperaLog{}
serviceStudent.Log = log
serviceStudent.Orm = db
err = serviceStudent.GetSysOperaLogPage(d, &list, &count)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.PageOK(list, int(count), d.GetPageIndex(), d.GetPageSize(), "查询成功")
}
func (e SysOperaLog) GetSysOperaLog(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysOperaLogById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object system.SysOperaLog
serviceSysOperlog := service.SysOperaLog{}
serviceSysOperlog.Log = log
serviceSysOperlog.Orm = db
err = serviceSysOperlog.GetSysOperaLog(control, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
func (e SysOperaLog) InsertSysOperaLog(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysOperaLogControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
serviceSysOperaLog := service.SysOperaLog{}
serviceSysOperaLog.Orm = db
serviceSysOperaLog.Log = log
err = serviceSysOperaLog.InsertSysOperaLog(object)
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(object.GetId(), "创建成功")
}
func (e SysOperaLog) UpdateSysOperaLog(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysOperaLogControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
serviceSysOperaLog := service.SysOperaLog{}
serviceSysOperaLog.Orm = db
serviceSysOperaLog.Log = log
err = serviceSysOperaLog.UpdateSysOperaLog(object)
if err != nil {
log.Error(err)
return
}
e.OK(object.GetId(), "更新成功")
}
func (e SysOperaLog) DeleteSysOperaLog(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysOperaLogById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
err = control.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
serviceSysOperaLog := service.SysOperaLog{}
serviceSysOperaLog.Orm = db
serviceSysOperaLog.Log = log
err = serviceSysOperaLog.RemoveSysOperaLog(control)
if err != nil {
log.Error(err)
return
}
e.OK(control.GetId(), "删除成功")
}
-223
View File
@@ -1,223 +0,0 @@
package sys_post
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
)
type SysPost struct {
apis.Api
}
// @Summary 岗位列表数据
// @Description 获取JSON
// @Tags 岗位
// @Param postName query string false "postName"
// @Param postCode query string false "postCode"
// @Param postId query string false "postId"
// @Param status query string false "status"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post [get]
// @Security Bearer
func (e SysPost) GetSysPostList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysPostSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查询列表
err = d.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]system.SysPost, 0)
var count int64
serviceStudent := service.SysPost{}
serviceStudent.Log = log
serviceStudent.Orm = db
err = serviceStudent.GetSysPostPage(d, &list, &count)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.PageOK(list, int(count), d.GetPageIndex(), d.GetPageSize(), "查询成功")
}
// @Summary 获取岗位信息
// @Description 获取JSON
// @Tags 岗位
// @Param postId path int true "postId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post/{postId} [get]
// @Security Bearer
func (e SysPost) GetSysPost(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysPostById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object system.SysPost
serviceSysOperlog := service.SysPost{}
serviceSysOperlog.Log = log
serviceSysOperlog.Orm = db
err = serviceSysOperlog.GetSysPost(control, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
// @Summary 添加岗位
// @Description 获取JSON
// @Tags 岗位
// @Accept application/json
// @Product application/json
// @Param data body dto.SysPostControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/post [post]
// @Security Bearer
func (e SysPost) InsertSysPost(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysPostControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置创建人
object.SetCreateBy(user.GetUserId(c))
serviceSysPost := service.SysPost{}
serviceSysPost.Orm = db
serviceSysPost.Log = log
err = serviceSysPost.InsertSysPost(object)
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
e.OK(object.GetId(), "创建成功")
}
// @Summary 修改岗位
// @Description 获取JSON
// @Tags 岗位
// @Accept application/json
// @Product application/json
// @Param data body dto.SysPostControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/post/ [put]
// @Security Bearer
func (e SysPost) UpdateSysPost(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysPostControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
serviceSysPost := service.SysPost{}
serviceSysPost.Orm = db
serviceSysPost.Log = log
err = serviceSysPost.UpdateSysPost(object)
if err != nil {
log.Error(err)
return
}
e.OK(object.GetId(), "更新成功")
}
// @Summary 删除岗位
// @Description 删除数据
// @Tags 岗位
// @Param id path int true "id"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 500 {string} string "{"code": 500, "message": "删除失败"}"
// @Router /api/v1/post/{postId} [delete]
func (e SysPost) DeleteSysPost(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysPostById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
err = control.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
serviceSysPost := service.SysPost{}
serviceSysPost.Orm = db
serviceSysPost.Log = log
err = serviceSysPost.RemoveSysPost(control)
if err != nil {
log.Error(err)
return
}
e.OK(control.GetId(), "删除成功")
}
-279
View File
@@ -1,279 +0,0 @@
package sys_role
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
"go-admin/common/global"
)
type SysRole struct {
apis.Api
}
// @Summary 角色列表数据
// @Description Get JSON
// @Tags 角色/Role
// @Param roleName query string false "roleName"
// @Param status query string false "status"
// @Param roleKey query string false "roleKey"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role [get]
// @Security Bearer
func (e SysRole) GetSysRoleList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
d := new(dto.SysRoleSearch)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查询列表
err = d.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
list := make([]system.SysRole, 0)
var count int64
s := service.SysRole{}
s.Log = log
s.Orm = db
err = s.GetSysRolePage(d, &list, &count)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.PageOK(list, int(count), d.GetPageIndex(), d.GetPageSize(), "查询成功")
}
// @Summary 获取Role数据
// @Description 获取JSON
// @Tags 角色/Role
// @Param roleId path string false "roleId"
// @Success 200 {string} string "{"code": 200, "data": [...]}"
// @Success 200 {string} string "{"code": -1, "message": "抱歉未找到相关信息"}"
// @Router /api/v1/role/{id} [get]
// @Security Bearer
func (e SysRole) GetSysRole(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysRoleById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//查看详情
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object system.SysRole
s := service.SysRole{}
s.Log = log
s.Orm = db
err = s.GetSysRole(control, &object)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
return
}
e.OK(object, "查看成功")
}
// @Summary 创建角色
// @Description 获取JSON
// @Tags 角色/Role
// @Accept application/json
// @Product application/json
// @Param data body dto.SysRoleControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/role [post]
// @Security Bearer
func (e SysRole) InsertSysRole(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysRoleControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//新增操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
// 设置创建人
object.CreateBy = user.GetUserId(c)
if object.Status == "" {
object.Status = "2"
}
s := service.SysRole{}
s.Orm = db
s.Log = log
err = s.InsertSysRole(object)
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "创建失败")
return
}
_, err = global.LoadPolicy(c)
if err != nil {
e.Error(http.StatusInternalServerError, err, "")
return
}
e.OK(object.GetId(), "创建成功")
}
// @Summary 修改用户角色
// @Description 获取JSON
// @Tags 角色/Role
// @Accept application/json
// @Product application/json
// @Param data body dto.SysRoleControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string "{"code": -1, "message": "修改失败"}"
// @Router /api/v1/role/{id} [put]
// @Security Bearer
func (e SysRole) UpdateSysRole(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysRoleControl)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = control.Bind(c)
if err != nil {
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(http.StatusInternalServerError, err, "模型生成失败")
return
}
object.UpdateBy = user.GetUserId(c)
s := service.SysRole{}
s.Orm = db
s.Log = log
err = s.UpdateSysRole(object)
if err != nil {
log.Error(err)
return
}
_, err = global.LoadPolicy(c)
if err != nil {
e.Error(http.StatusInternalServerError, err, "")
return
}
e.OK(object.GetId(), "更新成功")
}
// @Summary 删除用户角色
// @Description 删除数据
// @Tags 角色/Role
// @Param data body dto.SysRoleById true "body"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/role [delete]
// @Security Bearer
func (e SysRole) DeleteSysRole(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.SysRoleById)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//删除操作
err = control.Bind(c)
if err != nil {
log.Errorf("Bind error: %s", err)
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
s := service.SysRole{}
s.Orm = db
s.Log = log
err = s.RemoveSysRole(control)
if err != nil {
log.Error(err)
e.Error(http.StatusInternalServerError, err, "")
return
}
_, err = global.LoadPolicy(c)
if err != nil {
e.Error(http.StatusInternalServerError, err, "")
return
}
e.OK(control.GetId(), "删除成功")
}
func (e SysRole) UpdateRoleDataScope(c *gin.Context) {
e.Context = c
log := e.GetLogger()
control := new(dto.RoleDataScopeReq)
db, err := e.GetOrm()
if err != nil {
log.Error(err)
return
}
//更新操作
err = c.Bind(control)
if err != nil {
log.Errorf("request bind error, %s", err.Error())
e.Error(http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
data := &system.SysRole{
RoleId: control.RoleId,
DataScope: control.DataScope,
DeptIds: control.DeptIds,
}
data.UpdateBy = user.GetUserId(c)
s := &service.SysRole{}
s.Orm = db
s.Log = log
err = s.UpdateDataScope(data)
if err != nil {
e.Error(http.StatusInternalServerError, err, "")
return
}
e.OK(nil, "操作成功")
}
-582
View File
@@ -1,582 +0,0 @@
package tools
import (
"bytes"
"net/http"
"strconv"
"text/template"
"time"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"go-admin/app/admin/models"
"go-admin/app/admin/models/tools"
"go-admin/common/apis"
)
type Gen struct {
apis.Api
}
func (e Gen) Preview(c *gin.Context) {
e.Context = c
log := e.GetLogger()
table := tools.SysTables{}
id, err := pkg.StringToInt(c.Param("tableId"))
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
table.TableId = id
t1, err := template.ParseFiles("template/v4/model.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t2, err := template.ParseFiles("template/v4/no_actions/apis.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t3, err := template.ParseFiles("template/v4/js.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t4, err := template.ParseFiles("template/v4/vue.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t5, err := template.ParseFiles("template/v4/no_actions/router_check_role.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t6, err := template.ParseFiles("template/v4/dto.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t7, err := template.ParseFiles("template/v4/no_actions/service.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
tab, _ := table.Get(db)
var b1 bytes.Buffer
err = t1.Execute(&b1, tab)
var b2 bytes.Buffer
err = t2.Execute(&b2, tab)
var b3 bytes.Buffer
err = t3.Execute(&b3, tab)
var b4 bytes.Buffer
err = t4.Execute(&b4, tab)
var b5 bytes.Buffer
err = t5.Execute(&b5, tab)
var b6 bytes.Buffer
err = t6.Execute(&b6, tab)
var b7 bytes.Buffer
err = t7.Execute(&b7, tab)
mp := make(map[string]interface{})
mp["template/model.go.template"] = b1.String()
mp["template/api.go.template"] = b2.String()
mp["template/js.go.template"] = b3.String()
mp["template/vue.go.template"] = b4.String()
mp["template/router.go.template"] = b5.String()
mp["template/dto.go.template"] = b6.String()
mp["template/service.go.template"] = b7.String()
e.OK(mp, "")
}
func (e Gen) GenCode(c *gin.Context) {
e.Context = c
log := e.GetLogger()
table := tools.SysTables{}
id, err := pkg.StringToInt(c.Param("tableId"))
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
table.TableId = id
tab, _ := table.Get(db)
if tab.IsActions == 1 {
e.ActionsGen(c, tab)
} else {
e.NOActionsGen(c, tab)
}
e.OK("", "Code generated successfully!")
}
func (e Gen) GenApiToFile(c *gin.Context) {
e.Context = c
log := e.GetLogger()
table := tools.SysTables{}
id, err := pkg.StringToInt(c.Param("tableId"))
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
table.TableId = id
tab, _ := table.Get(db)
e.genApiToFile(c, tab)
e.OK("", "Code generated successfully!")
}
func (e Gen) NOActionsGen(c *gin.Context, tab tools.SysTables) {
e.Context = c
log := e.GetLogger()
basePath := "template/v4/"
routerFile := basePath + "no_actions/router_check_role.go.template"
if tab.IsAuth == 2 {
routerFile = basePath + "no_actions/router_no_check_role.go.template"
}
t1, err := template.ParseFiles(basePath + "model.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t2, err := template.ParseFiles(basePath + "no_actions/apis.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t3, err := template.ParseFiles(routerFile)
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t4, err := template.ParseFiles(basePath + "js.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t5, err := template.ParseFiles(basePath + "vue.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t6, err := template.ParseFiles(basePath + "dto.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t7, err := template.ParseFiles(basePath + "no_actions/service.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
_ = pkg.PathCreate("./app/" + tab.PackageName + "/apis/" + tab.ModuleName)
_ = pkg.PathCreate("./app/" + tab.PackageName + "/models/")
_ = pkg.PathCreate("./app/" + tab.PackageName + "/router/")
_ = pkg.PathCreate("./app/" + tab.PackageName + "/service/dto/")
_ = pkg.PathCreate(config.GenConfig.FrontPath + "/api/")
_ = pkg.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.BusinessName)
var b1 bytes.Buffer
err = t1.Execute(&b1, tab)
var b2 bytes.Buffer
err = t2.Execute(&b2, tab)
var b3 bytes.Buffer
err = t3.Execute(&b3, tab)
var b4 bytes.Buffer
err = t4.Execute(&b4, tab)
var b5 bytes.Buffer
err = t5.Execute(&b5, tab)
var b6 bytes.Buffer
err = t6.Execute(&b6, tab)
var b7 bytes.Buffer
err = t7.Execute(&b7, tab)
pkg.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go")
pkg.FileCreate(b2, "./app/"+tab.PackageName+"/apis/"+tab.ModuleName+"/"+tab.BusinessName+".go")
pkg.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go")
pkg.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js")
pkg.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue")
pkg.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go")
pkg.FileCreate(b7, "./app/"+tab.PackageName+"/service/"+tab.BusinessName+".go")
}
func (e Gen) genApiToFile(c *gin.Context, tab tools.SysTables) {
e.Context = c
log := e.GetLogger()
basePath := "template/"
t1, err := template.ParseFiles(basePath + "api_migrate.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
i := strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
var b1 bytes.Buffer
err = t1.Execute(&b1, struct {
tools.SysTables
GenerateTime string
}{tab, i})
pkg.FileCreate(b1, "./cmd/migrate/migration/version-local/"+i+"_migrate.go")
}
func (e Gen) ActionsGen(c *gin.Context, tab tools.SysTables) {
e.Context = c
log := api.GetRequestLogger(c)
basePath := "template/v4/"
routerFile := basePath + "actions/router_check_role.go.template"
if tab.IsAuth == 2 {
routerFile = basePath + "actions/router_no_check_role.go.template"
}
t1, err := template.ParseFiles(basePath + "model.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t3, err := template.ParseFiles(routerFile)
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t4, err := template.ParseFiles(basePath + "js.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t5, err := template.ParseFiles(basePath + "vue.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
t6, err := template.ParseFiles(basePath + "dto.go.template")
if err != nil {
log.Error(err)
e.Error(500, err, "")
return
}
_ = pkg.PathCreate("./app/" + tab.PackageName + "/models/")
_ = pkg.PathCreate("./app/" + tab.PackageName + "/router/")
_ = pkg.PathCreate("./app/" + tab.PackageName + "/service/dto/")
_ = pkg.PathCreate(config.GenConfig.FrontPath + "/api/")
_ = pkg.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.BusinessName)
var b1 bytes.Buffer
err = t1.Execute(&b1, tab)
var b3 bytes.Buffer
err = t3.Execute(&b3, tab)
var b4 bytes.Buffer
err = t4.Execute(&b4, tab)
var b5 bytes.Buffer
err = t5.Execute(&b5, tab)
var b6 bytes.Buffer
err = t6.Execute(&b6, tab)
pkg.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go")
pkg.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go")
pkg.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js")
pkg.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue")
pkg.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go")
}
func (e Gen) GenMenuAndApi(c *gin.Context) {
log := api.GetRequestLogger(c)
e.Context = c
table := tools.SysTables{}
timeNow := pkg.GetCurrentTime()
id, err := pkg.StringToInt(c.Param("tableId"))
pkg.HasError(err, "", -1)
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
e.Error(http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
table.TableId = id
tab, _ := table.Get(db)
Mmenu := models.Menu{}
Mmenu.MenuName = tab.TBName + "Manage"
Mmenu.Title = tab.TableComment
Mmenu.Icon = "pass"
Mmenu.Path = "/" + tab.TBName
Mmenu.MenuType = "M"
Mmenu.Action = "无"
Mmenu.ParentId = 0
Mmenu.NoCache = false
Mmenu.Component = "Layout"
Mmenu.Sort = 0
Mmenu.Visible = "0"
Mmenu.IsFrame = "0"
Mmenu.CreateBy = "1"
Mmenu.UpdateBy = "1"
Mmenu.CreatedAt = timeNow
Mmenu.UpdatedAt = timeNow
Mmenu.MenuId, err = Mmenu.Create(db)
Cmenu := models.Menu{}
Cmenu.MenuName = tab.TBName
Cmenu.Title = tab.TableComment
Cmenu.Icon = "pass"
Cmenu.Path = tab.TBName
Cmenu.MenuType = "C"
Cmenu.Action = "无"
Cmenu.Permission = tab.PackageName + ":" + tab.BusinessName + ":list"
Cmenu.ParentId = Mmenu.MenuId
Cmenu.NoCache = false
Cmenu.Component = "/" + tab.BusinessName + "/index"
Cmenu.Sort = 0
Cmenu.Visible = "0"
Cmenu.IsFrame = "0"
Cmenu.CreateBy = "1"
Cmenu.UpdateBy = "1"
Cmenu.CreatedAt = timeNow
Cmenu.UpdatedAt = timeNow
Cmenu.MenuId, err = Cmenu.Create(db)
MList := models.Menu{}
MList.MenuName = ""
MList.Title = "分页获取" + tab.TableComment
MList.Icon = ""
MList.Path = tab.TBName
MList.MenuType = "F"
MList.Action = "无"
MList.Permission = tab.PackageName + ":" + tab.BusinessName + ":query"
MList.ParentId = Cmenu.MenuId
MList.NoCache = false
MList.Sort = 0
MList.Visible = "0"
MList.IsFrame = "0"
MList.CreateBy = "1"
MList.UpdateBy = "1"
MList.CreatedAt = timeNow
MList.UpdatedAt = timeNow
MList.MenuId, err = MList.Create(db)
MCreate := models.Menu{}
MCreate.MenuName = ""
MCreate.Title = "创建" + tab.TableComment
MCreate.Icon = ""
MCreate.Path = tab.TBName
MCreate.MenuType = "F"
MCreate.Action = "无"
MCreate.Permission = tab.PackageName + ":" + tab.BusinessName + ":add"
MCreate.ParentId = Cmenu.MenuId
MCreate.NoCache = false
MCreate.Sort = 0
MCreate.Visible = "0"
MCreate.IsFrame = "0"
MCreate.CreateBy = "1"
MCreate.UpdateBy = "1"
MCreate.CreatedAt = timeNow
MCreate.UpdatedAt = timeNow
MCreate.MenuId, err = MCreate.Create(db)
MUpdate := models.Menu{}
MUpdate.MenuName = ""
MUpdate.Title = "修改" + tab.TableComment
MUpdate.Icon = ""
MUpdate.Path = tab.TBName
MUpdate.MenuType = "F"
MUpdate.Action = "无"
MUpdate.Permission = tab.PackageName + ":" + tab.BusinessName + ":edit"
MUpdate.ParentId = Cmenu.MenuId
MUpdate.NoCache = false
MUpdate.Sort = 0
MUpdate.Visible = "0"
MUpdate.IsFrame = "0"
MUpdate.CreateBy = "1"
MUpdate.UpdateBy = "1"
MUpdate.CreatedAt = timeNow
MUpdate.UpdatedAt = timeNow
MUpdate.MenuId, err = MUpdate.Create(db)
MDelete := models.Menu{}
MDelete.MenuName = ""
MDelete.Title = "删除" + tab.TableComment
MDelete.Icon = ""
MDelete.Path = tab.TBName
MDelete.MenuType = "F"
MDelete.Action = "无"
MDelete.Permission = tab.PackageName + ":" + tab.BusinessName + ":remove"
MDelete.ParentId = Cmenu.MenuId
MDelete.NoCache = false
MDelete.Sort = 0
MDelete.Visible = "0"
MDelete.IsFrame = "0"
MDelete.CreateBy = "1"
MDelete.UpdateBy = "1"
MDelete.CreatedAt = timeNow
MDelete.UpdatedAt = timeNow
MDelete.MenuId, err = MDelete.Create(db)
var InterfaceId = 63
Amenu := models.Menu{}
Amenu.MenuName = tab.TBName
Amenu.Title = tab.TableComment
Amenu.Icon = "bug"
Amenu.Path = tab.TBName
Amenu.MenuType = "M"
Amenu.Action = "无"
Amenu.ParentId = InterfaceId
Amenu.NoCache = false
Amenu.Sort = 0
Amenu.Visible = "1"
Amenu.IsFrame = "0"
Amenu.CreateBy = "1"
Amenu.UpdateBy = "1"
Amenu.CreatedAt = timeNow
Amenu.UpdatedAt = timeNow
Amenu.MenuId, err = Amenu.Create(db)
AList := models.Menu{}
AList.MenuName = ""
AList.Title = "分页获取" + tab.TableComment
AList.Icon = "bug"
AList.Path = "/api/v1/" + tab.ModuleName
AList.MenuType = "A"
AList.Action = "GET"
AList.ParentId = Amenu.MenuId
AList.NoCache = false
AList.Sort = 0
AList.Visible = "1"
AList.IsFrame = "0"
AList.CreateBy = "1"
AList.UpdateBy = "1"
AList.CreatedAt = timeNow
AList.UpdatedAt = timeNow
AList.MenuId, err = AList.Create(db)
AGet := models.Menu{}
AGet.MenuName = ""
AGet.Title = "根据id获取" + tab.TableComment
AGet.Icon = "bug"
AGet.Path = "/api/v1/" + tab.ModuleName + "/:id"
AGet.MenuType = "A"
AGet.Action = "GET"
AGet.ParentId = Amenu.MenuId
AGet.NoCache = false
AGet.Sort = 0
AGet.Visible = "1"
AGet.IsFrame = "0"
AGet.CreateBy = "1"
AGet.UpdateBy = "1"
AGet.CreatedAt = timeNow
AGet.UpdatedAt = timeNow
AGet.MenuId, err = AGet.Create(db)
ACreate := models.Menu{}
ACreate.MenuName = ""
ACreate.Title = "创建" + tab.TableComment
ACreate.Icon = "bug"
ACreate.Path = "/api/v1/" + tab.ModuleName
ACreate.MenuType = "A"
ACreate.Action = "POST"
ACreate.ParentId = Amenu.MenuId
ACreate.NoCache = false
ACreate.Sort = 0
ACreate.Visible = "1"
ACreate.IsFrame = "0"
ACreate.CreateBy = "1"
ACreate.UpdateBy = "1"
ACreate.CreatedAt = timeNow
ACreate.UpdatedAt = timeNow
ACreate.MenuId, err = ACreate.Create(db)
AUpdate := models.Menu{}
AUpdate.MenuName = ""
AUpdate.Title = "修改" + tab.TableComment
AUpdate.Icon = "bug"
AUpdate.Path = "/api/v1/" + tab.ModuleName + "/:id"
AUpdate.MenuType = "A"
AUpdate.Action = "PUT"
AUpdate.ParentId = Amenu.MenuId
AUpdate.NoCache = false
AUpdate.Sort = 0
AUpdate.Visible = "1"
AUpdate.IsFrame = "0"
AUpdate.CreateBy = "1"
AUpdate.UpdateBy = "1"
AUpdate.CreatedAt = timeNow
AUpdate.UpdatedAt = timeNow
AUpdate.MenuId, err = AUpdate.Create(db)
ADelete := models.Menu{}
ADelete.MenuName = ""
ADelete.Title = "删除" + tab.TableComment
ADelete.Icon = "bug"
ADelete.Path = "/api/v1/" + tab.ModuleName
ADelete.MenuType = "A"
ADelete.Action = "DELETE"
ADelete.ParentId = Amenu.MenuId
ADelete.NoCache = false
ADelete.Sort = 0
ADelete.Visible = "1"
ADelete.IsFrame = "0"
ADelete.CreateBy = "1"
ADelete.UpdateBy = "1"
ADelete.CreatedAt = timeNow
ADelete.UpdatedAt = timeNow
ADelete.MenuId, err = ADelete.Create(db)
e.OK("", "数据生成成功!")
}
+16
View File
@@ -0,0 +1,16 @@
package models
type CasbinRule struct {
ID uint `gorm:"primaryKey;autoIncrement"`
Ptype string `gorm:"size:512;uniqueIndex:unique_index"`
V0 string `gorm:"size:512;uniqueIndex:unique_index"`
V1 string `gorm:"size:512;uniqueIndex:unique_index"`
V2 string `gorm:"size:512;uniqueIndex:unique_index"`
V3 string `gorm:"size:512;uniqueIndex:unique_index"`
V4 string `gorm:"size:512;uniqueIndex:unique_index"`
V5 string `gorm:"size:512;uniqueIndex:unique_index"`
}
func (CasbinRule) TableName() string {
return "sys_casbin_rule"
}
+1 -1
View File
@@ -31,7 +31,7 @@ func ExecSql(db *gorm.DB, filePath string) error {
fmt.Println(sqlList[i])
continue
}
sql := strings.Replace(sqlList[i]+";", "\n", "", 0)
sql := strings.Replace(sqlList[i]+";", "\n", "", -1)
sql = strings.TrimSpace(sql)
if err = db.Exec(sql).Error; err != nil {
log.Printf("error sql: %s", sql)
-343
View File
@@ -1,343 +0,0 @@
package models
import (
"errors"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"go-admin/common/models"
"gorm.io/gorm"
"go-admin/app/admin/models/system"
)
type Menu struct {
MenuId int `json:"menuId" gorm:"primaryKey;autoIncrement"`
MenuName string `json:"menuName" gorm:"size:128;"`
Title string `json:"title" gorm:"size:128;"`
Icon string `json:"icon" gorm:"size:128;"`
Path string `json:"path" gorm:"size:128;"`
Paths string `json:"paths" gorm:"size:128;"`
MenuType string `json:"menuType" gorm:"size:1;"`
Action string `json:"action" gorm:"size:16;"`
Permission string `json:"permission" gorm:"size:255;"`
ParentId int `json:"parentId" gorm:"size:11;"`
NoCache bool `json:"noCache" gorm:"size:8;"`
Breadcrumb string `json:"breadcrumb" gorm:"size:255;"`
Component string `json:"component" gorm:"size:255;"`
Sort int `json:"sort" gorm:"size:4;"`
Visible string `json:"visible" gorm:"size:1;"`
CreateBy string `json:"createBy" gorm:"size:128;"`
UpdateBy string `json:"updateBy" gorm:"size:128;"`
IsFrame string `json:"isFrame" gorm:"size:1;DEFAULT:0;"`
DataScope string `json:"dataScope" gorm:"-"`
Params string `json:"params" gorm:"-"`
RoleId int `gorm:"-"`
Children []Menu `json:"children" gorm:"-"`
IsSelect bool `json:"is_select" gorm:"-"`
models.ModelTime
}
func (Menu) TableName() string {
return "sys_menu"
}
type MenuLable struct {
Id int `json:"id" gorm:"-"`
Label string `json:"label" gorm:"-"`
Children []MenuLable `json:"children" gorm:"-"`
}
type Menus struct {
MenuId int `json:"menuId" gorm:"column:menu_id;primaryKey;autoIncrement;"`
MenuName string `json:"menuName" gorm:"column:menu_name"`
Title string `json:"title" gorm:"column:title"`
Icon string `json:"icon" gorm:"column:icon"`
Path string `json:"path" gorm:"column:path"`
MenuType string `json:"menuType" gorm:"column:menu_type"`
Action string `json:"action" gorm:"column:action"`
Permission string `json:"permission" gorm:"column:permission"`
ParentId int `json:"parentId" gorm:"column:parent_id"`
NoCache bool `json:"noCache" gorm:"column:no_cache"`
Breadcrumb string `json:"breadcrumb" gorm:"column:breadcrumb"`
Component string `json:"component" gorm:"column:component"`
Sort int `json:"sort" gorm:"column:sort"`
Visible string `json:"visible" gorm:"column:visible"`
Children []Menu `json:"children" gorm:"-"`
CreateBy string `json:"createBy" gorm:"column:create_by"`
UpdateBy string `json:"updateBy" gorm:"column:update_by"`
DataScope string `json:"dataScope" gorm:"-"`
Params string `json:"params" gorm:"-"`
BaseModel
}
func (Menus) TableName() string {
return "sys_menu"
}
type MenuRole struct {
Menus
IsSelect bool `json:"is_select" gorm:"-"`
}
type MS []Menu
//func (e *Menu) GetByMenuId() (Menu Menu, err error) {
//
// table := orm.Eloquent.Table(e.TableName())
// table = table.Where("menu_id = ?", e.MenuId)
// if err = table.Find(&Menu).Error; err != nil {
// return
// }
// return
//}
//func (e *Menu) SetMenu() (m []Menu, err error) {
// menulist, err := e.GetPage()
//
// m = make([]Menu, 0)
// for i := 0; i < len(menulist); i++ {
// if menulist[i].ParentId != 0 {
// continue
// }
// menusInfo := DiguiMenu(&menulist, menulist[i])
//
// m = append(m, menusInfo)
// }
// return
//}
//func DiguiMenu(menulist *[]Menu, menu Menu) Menu {
// list := *menulist
//
// min := make([]Menu, 0)
// for j := 0; j < len(list); j++ {
//
// if menu.MenuId != list[j].ParentId {
// continue
// }
// mi := Menu{}
// mi.MenuId = list[j].MenuId
// mi.MenuName = list[j].MenuName
// mi.Title = list[j].Title
// mi.Icon = list[j].Icon
// mi.Path = list[j].Path
// mi.MenuType = list[j].MenuType
// mi.Action = list[j].Action
// mi.Permission = list[j].Permission
// mi.ParentId = list[j].ParentId
// mi.NoCache = list[j].NoCache
// mi.Breadcrumb = list[j].Breadcrumb
// mi.Component = list[j].Component
// mi.Sort = list[j].Sort
// mi.Visible = list[j].Visible
// mi.CreatedAt = list[j].CreatedAt
// mi.Children = []Menu{}
//
// if mi.MenuType != "F" {
// ms := DiguiMenu(menulist, mi)
// min = append(min, ms)
//
// } else {
// min = append(min, mi)
// }
//
// }
// menu.Children = min
// return menu
//}
//func (e *Menu) SetMenuLabel() (m *[]MenuLable, err error) {
// menulist, err := e.Get()
//
// ml := make([]MenuLable, 0)
// for i := 0; i < len(menulist); i++ {
// if menulist[i].ParentId != 0 {
// continue
// }
// e := MenuLable{}
// e.Id = menulist[i].MenuId
// e.Label = menulist[i].Title
// menusInfo := MenuLabelCall(&menulist, e)
//
// ml = append(ml, menusInfo)
// }
// return &ml, err
//}
//func MenuLabelCall(menulist *[]Menu, menu MenuLable) MenuLable {
// list := *menulist
//
// min := make([]MenuLable, 0)
// for j := 0; j < len(list); j++ {
//
// if menu.Id != list[j].ParentId {
// continue
// }
// mi := MenuLable{}
// mi.Id = list[j].MenuId
// mi.Label = list[j].Title
// mi.Children = []MenuLable{}
// if list[j].MenuType != "F" {
// ms := MenuLabelCall(menulist, mi)
// min = append(min, ms)
// } else {
// min = append(min, mi)
// }
//
// }
// if len(min) > 0 {
// menu.Children = min
// } else {
// menu.Children = nil
// }
// return menu
//}
//func (e *Menu) SetMenuRole(roleName string) (m []Menu, err error) {
//
// menus, err := e.GetByRoleName(roleName)
//
// m = make([]Menu, 0)
// for i := 0; i < len(menus); i++ {
// if menus[i].ParentId != 0 {
// continue
// }
// menusInfo := DiguiMenu(&menus, menus[i])
//
// m = append(m, menusInfo)
// }
// return
//}
//func (e *MenuRole) Get(tx *gorm.DB) (Menus []MenuRole, err error) {
// table := tx.Table(e.TableName())
// if e.MenuName != "" {
// table = table.Where("menu_name = ?", e.MenuName)
// }
// if err = table.Order("sort").Find(&Menus).Error; err != nil {
// return
// }
// return
//}
//func (e *Menu) GetByRoleName(roleName string) (Menus []Menu, err error) {
// var table *gorm.DB
// if roleName == "admin" {
// table = orm.Eloquent.Table(e.TableName()).Select("sys_menu.*")
// table = table.Where(" menu_type in ('M','C')")
// } else {
// table = orm.Eloquent.Table(e.TableName()).Select("sys_menu.*").Joins("left join sys_role_menu on sys_role_menu.menu_id=sys_menu.menu_id")
// table = table.Where("sys_role_menu.role_name=? and menu_type in ('M','C')", roleName)
// }
// if err = table.Order("sort").Find(&Menus).Error; err != nil {
// return
// }
// return
//}
func (e *Menu) Get(tx *gorm.DB) (Menus []Menu, err error) {
table := tx.Table(e.TableName())
if e.MenuName != "" {
table = table.Where("menu_name = ?", e.MenuName)
}
if e.Path != "" {
table = table.Where("path = ?", e.Path)
}
if e.Action != "" {
table = table.Where("action = ?", e.Action)
}
if e.MenuType != "" {
table = table.Where("menu_type = ?", e.MenuType)
}
if err = table.Order("sort").Find(&Menus).Error; err != nil {
return
}
return
}
func (e *Menu) GetPage(tx *gorm.DB) (Menus []Menu, err error) {
table := tx.Table(e.TableName())
if e.MenuName != "" {
table = table.Where("menu_name = ?", e.MenuName)
}
if e.Title != "" {
table = table.Where("title = ?", e.Title)
}
if e.Visible != "" {
table = table.Where("visible = ?", e.Visible)
}
if e.MenuType != "" {
table = table.Where("menu_type = ?", e.MenuType)
}
// 数据权限控制
dataPermission := new(system.DataPermission)
dataPermission.UserId, _ = pkg.StringToInt(e.DataScope)
table, err = dataPermission.GetDataScope("sys_menu", table)
if err != nil {
return nil, err
}
if err = table.Order("sort").Find(&Menus).Error; err != nil {
return
}
return
}
func (e *Menu) Create(tx *gorm.DB) (id int, err error) {
result := tx.Table(e.TableName()).Create(&e)
if result.Error != nil {
err = result.Error
return
}
err = InitPaths(tx, e)
if err != nil {
return
}
id = e.MenuId
return
}
func InitPaths(tx *gorm.DB, menu *Menu) (err error) {
parentMenu := new(Menu)
if menu.ParentId != 0 {
tx.Table("sys_menu").Where("menu_id = ?", menu.ParentId).First(parentMenu)
if parentMenu.Paths == "" {
err = errors.New("父级paths异常,请尝试对当前节点父级菜单进行更新操作!")
return
}
menu.Paths = parentMenu.Paths + "/" + pkg.IntToString(menu.MenuId)
} else {
menu.Paths = "/0/" + pkg.IntToString(menu.MenuId)
}
tx.Table("sys_menu").Where("menu_id = ?", menu.MenuId).Update("paths", menu.Paths)
return
}
//func (e *Menu) Update(tx *gorm.DB, id int) (update Menu, err error) {
// if err = tx.Table(e.TableName()).First(&update, id).Error; err != nil {
// return
// }
//
// //参数1:是要修改的数据
// //参数2:是修改的数据
// if err = tx.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
// return
// }
// err = InitPaths(tx, e)
// if err != nil {
// return
// }
// return
//}
//func (e *Menu) Delete(tx *gorm.DB, id int) (success bool, err error) {
// if err = tx.Table(e.TableName()).Where("menu_id = ?", id).Delete(&Menu{}).Error; err != nil {
// success = false
// return
// }
// success = true
// return
//}
-11
View File
@@ -1,11 +0,0 @@
package models
import (
"time"
)
type BaseModel struct {
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt"`
}
-243
View File
@@ -1,243 +0,0 @@
package models
import "go-admin/common/models"
type SysRole struct {
RoleId int `json:"roleId" gorm:"primaryKey;autoIncrement"` // 角色编码
RoleName string `json:"roleName" gorm:"size:128;"` // 角色名称
Status string `json:"status" gorm:"size:4;"` //
RoleKey string `json:"roleKey" gorm:"size:128;"` //角色代码
RoleSort int `json:"roleSort" gorm:""` //角色排序
Flag string `json:"flag" gorm:"size:128;"` //
Remark string `json:"remark" gorm:"size:255;"` //备注
Admin bool `json:"admin" gorm:"size:4;"`
DataScope string `json:"dataScope" gorm:"size:128;"`
models.ModelTime
models.ControlBy
Params string `json:"params" gorm:"-"`
MenuIds []int `json:"menuIds" gorm:"-"`
DeptIds []int `json:"deptIds" gorm:"-"`
}
func (SysRole) TableName() string {
return "sys_role"
}
type MenuIdList struct {
MenuId int `json:"menuId"`
}
//func (role *SysRole) GetById(tx *gorm.DB, id interface{}) error {
// return tx.First(role, id).Error
//}
//
//func (role *SysRole) GetPage(pageSize int, pageIndex int) ([]SysRole, int, error) {
// var doc []SysRole
//
// table := orm.Eloquent.Table("sys_role")
// if role.RoleId != 0 {
// table = table.Where("role_id = ?", role.RoleId)
// }
// if role.RoleName != "" {
// table = table.Where("role_name = ?", role.RoleName)
// }
// if role.Status != "" {
// table = table.Where("status = ?", role.Status)
// }
// if role.RoleKey != "" {
// table = table.Where("role_key = ?", role.RoleKey)
// }
//
// // 数据权限控制
// dataPermission := new(DataPermission)
// dataPermission.UserId, _ = tools.StringToInt(role.DataScope)
// table, err := dataPermission.GetDataScope("sys_role", table)
// if err != nil {
// return nil, 0, err
// }
// var count int64
//
// if err := table.Order("role_sort").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
// return nil, 0, err
// }
// //table.Where("`deleted_at` IS NULL").Count(&count)
// return doc, int(count), nil
//}
//
//func (role *SysRole) Get() (SysRole SysRole, err error) {
// table := orm.Eloquent.Table("sys_role")
// if role.RoleId != 0 {
// table = table.Where("role_id = ?", role.RoleId)
// }
// if role.RoleName != "" {
// table = table.Where("role_name = ?", role.RoleName)
// }
// if err = table.First(&SysRole).Error; err != nil {
// return
// }
//
// return
//}
//
//func (role *SysRole) GetOne(sysRole *SysRole) (err error) {
// table := orm.Eloquent.Table("sys_role")
// if role.RoleId != 0 {
// table = table.Where("role_id = ?", role.RoleId)
// }
// if role.RoleName != "" {
// table = table.Where("role_name = ?", role.RoleName)
// }
// if err = table.First(sysRole).Error; err != nil {
// return
// }
//
// return
//}
//
//func (role *SysRole) GetList() (SysRole []SysRole, err error) {
// table := orm.Eloquent.Table("sys_role")
// if role.RoleId != 0 {
// table = table.Where("role_id = ?", role.RoleId)
// }
// if role.RoleName != "" {
// table = table.Where("role_name = ?", role.RoleName)
// }
// if err = table.Order("role_sort").Find(&SysRole).Error; err != nil {
// return
// }
//
// return
//}
//
//// 获取角色对应的菜单ids
//func (role *SysRole) GetRoleMeunId() ([]int, error) {
// menuIds := make([]int, 0)
// menuList := make([]MenuIdList, 0)
// if err := orm.Eloquent.Table("sys_role_menu").
// Select("sys_role_menu.menu_id").
// Where("role_id = ? ", role.RoleId).
// Where(" sys_role_menu.menu_id not in(select sys_menu.parent_id from sys_role_menu " +
// "LEFT JOIN sys_menu on sys_menu.menu_id=sys_role_menu.menu_id where role_id =? and parent_id is not null)", role.RoleId).
// Find(&menuList).Error; err != nil {
// return nil, err
// }
//
// for i := 0; i < len(menuList); i++ {
// menuIds = append(menuIds, menuList[i].MenuId)
// }
// return menuIds, nil
//}
//
//func (role *SysRole) Insert() (id int, err error) {
// var i int64
// orm.Eloquent.Table(role.TableName()).Where("role_name=? or role_key = ?", role.RoleName, role.RoleKey).Count(&i)
// if i > 0 {
// return 0, errors.New("角色名称或者角色标识已经存在!")
// }
// role.UpdateBy = ""
// result := orm.Eloquent.Table(role.TableName()).Create(&role)
// if result.Error != nil {
// err = result.Error
// return
// }
// id = role.RoleId
// return
//}
//
//type DeptIdList struct {
// DeptId int `json:"DeptId"`
//}
//
//func (role *SysRole) GetRoleDeptId() ([]int, error) {
// deptIds := make([]int, 0)
// deptList := make([]DeptIdList, 0)
// if err := orm.Eloquent.Table("sys_role_dept").Select("sys_role_dept.dept_id").Joins("LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id").Where("role_id = ? ", role.RoleId).Where(" sys_role_dept.dept_id not in(select sys_dept.parent_id from sys_role_dept LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id where role_id =? )", role.RoleId).Find(&deptList).Error; err != nil {
// return nil, err
// }
//
// for i := 0; i < len(deptList); i++ {
// deptIds = append(deptIds, deptList[i].DeptId)
// }
//
// return deptIds, nil
//}
//
////修改
//func (role *SysRole) Update(id int) (update SysRole, err error) {
// if err = orm.Eloquent.Table(role.TableName()).First(&update, id).Error; err != nil {
// return
// }
//
// if role.RoleName != "" && role.RoleName != update.RoleName {
// return update, errors.New("角色名称不允许修改!")
// }
//
// if role.RoleKey != "" && role.RoleKey != update.RoleKey {
// return update, errors.New("角色标识不允许修改!")
// }
//
// //参数1:是要修改的数据
// //参数2:是修改的数据
// if err = orm.Eloquent.Table(role.TableName()).Model(&update).Updates(&role).Error; err != nil {
// return
// }
// return
//}
//
////批量删除
//func (role *SysRole) BatchDelete(id []int) (Result bool, err error) {
// tx := orm.Eloquent.Begin()
//
// defer func() {
// if r := recover(); r != nil {
// tx.Rollback()
// }
// }()
//
// if err := tx.Error; err != nil {
// return false, err
// }
// // 查询角色
// var roles []SysRole
// if err := tx.Table("sys_role").Where("role_id in (?)", id).Find(&roles).Error; err != nil {
// tx.Rollback()
// return false, err
// }
//
// var count int64
// if err := tx.Table("sys_user").Where("role_id in (?)", id).Count(&count).Error; err != nil {
// tx.Rollback()
// return false, err
// }
// if count > 0 {
// tx.Rollback()
// return false, errors.New("存在绑定用户,请解绑后重试")
// }
//
// // 删除角色
// if err = tx.Table(role.TableName()).Where("role_id in (?)", id).Unscoped().Delete(&SysRole{}).Error; err != nil {
// tx.Rollback()
// return false, err
// }
//
// // 删除角色菜单
// if err := tx.Table("sys_role_menu").Where("role_id in (?)", id).Delete(&RoleMenu{}).Error; err != nil {
// tx.Rollback()
// return false, err
// }
//
// // 删除casbin配置
// for i := 0; i < len(roles); i++ {
// if err := tx.Table("sys_casbin_rule").Where("v0 in (?)", roles[0].RoleKey).Delete(&CasbinRule{}).Error; err != nil {
// tx.Rollback()
// return false, err
// }
// }
//
// if err := tx.Commit().Error; err != nil {
// return false, err
// }
//
// return true, nil
//}
+91
View File
@@ -0,0 +1,91 @@
package models
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"regexp"
"strings"
"github.com/bitly/go-simplejson"
"github.com/go-admin-team/go-admin-core/v2/sdk"
"github.com/go-admin-team/go-admin-core/v2/sdk/runtime"
"github.com/go-admin-team/go-admin-core/v2/storage"
"go-admin/common/models"
)
type SysApi struct {
Id int `json:"id" gorm:"primaryKey;autoIncrement;comment:主键编码"`
Handle string `json:"handle" gorm:"size:128;comment:handle"`
Title string `json:"title" gorm:"size:128;comment:标题"`
Path string `json:"path" gorm:"size:128;comment:地址"`
Action string `json:"action" gorm:"size:16;comment:请求类型"`
Type string `json:"type" gorm:"size:16;comment:接口类型"`
models.ModelTime
models.ControlBy
}
func (*SysApi) TableName() string {
return "sys_api"
}
func (e *SysApi) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysApi) GetId() interface{} {
return e.Id
}
func SaveSysApi(message storage.Messager) (err error) {
var rb []byte
rb, err = json.Marshal(message.GetValues())
if err != nil {
err = fmt.Errorf("json Marshal error, %v", err.Error())
return err
}
var l runtime.Routers
err = json.Unmarshal(rb, &l)
if err != nil {
err = fmt.Errorf("json Unmarshal error, %s", err.Error())
return err
}
dbList := sdk.Runtime.GetAllDb()
for _, d := range dbList {
for _, v := range l.List {
if v.HttpMethod != "HEAD" ||
strings.Contains(v.RelativePath, "/swagger/") ||
strings.Contains(v.RelativePath, "/static/") ||
strings.Contains(v.RelativePath, "/form-generator/") ||
strings.Contains(v.RelativePath, "/sys/tables") {
// 根据接口方法注释里的@Summary填充接口名称,适用于代码生成器
// 可在此处增加配置路径前缀的if判断,只对代码生成的自建应用进行定向的接口名称填充
jsonFile, _ := ioutil.ReadFile("docs/swagger.json")
jsonData, _ := simplejson.NewFromReader(bytes.NewReader(jsonFile))
urlPath := v.RelativePath
idPatten := "(.*)/:(\\w+)" // 正则替换,把:id换成{id}
reg, _ := regexp.Compile(idPatten)
if reg.MatchString(urlPath) {
urlPath = reg.ReplaceAllString(v.RelativePath, "${1}/{${2}}") // 把:id换成{id}
}
apiTitle, _ := jsonData.Get("paths").Get(urlPath).Get(strings.ToLower(v.HttpMethod)).Get("summary").String()
err := d.Debug().Where(SysApi{Path: v.RelativePath, Action: v.HttpMethod}).
Attrs(SysApi{Handle: v.Handler, Title: apiTitle}).
FirstOrCreate(&SysApi{}).
//Update("handle", v.Handler).
Error
if err != nil {
err := fmt.Errorf("Models SaveSysApi error: %s \r\n ", err.Error())
return err
}
}
}
}
return nil
}
-29
View File
@@ -1,29 +0,0 @@
package models
import (
"go-admin/common/models"
)
type SysCategory struct {
models.Model
Name string `json:"name" gorm:"type:varchar(255);comment:名称"` //
Img string `json:"img" gorm:"type:varchar(255);comment:图标"` //
Sort int `json:"sort" gorm:"type:int(4);comment:排序"` //
Status int `json:"status" gorm:"type:int(1);comment:状态"` //
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"` //
models.ControlBy
models.ModelTime
}
func (SysCategory) TableName() string {
return "sys_category"
}
func (e *SysCategory) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysCategory) GetId() interface{} {
return e.Id
}
-27
View File
@@ -1,27 +0,0 @@
package models
import (
"go-admin/common/models"
)
type SysChinaAreaData struct {
models.Model
PId string `json:"pId" gorm:"type:int(11);comment:上级编码"`
Name string `json:"name" gorm:"type:varchar(128);comment:名称"`
models.ControlBy
models.ModelTime
}
func (SysChinaAreaData) TableName() string {
return "sys_china_area_data"
}
func (e *SysChinaAreaData) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysChinaAreaData) GetId() interface{} {
return e.Id
}
+30
View File
@@ -0,0 +1,30 @@
package models
import (
"go-admin/common/models"
)
type SysConfig struct {
models.Model
ConfigName string `json:"configName" gorm:"size:128;comment:ConfigName"` //
ConfigKey string `json:"configKey" gorm:"size:128;comment:ConfigKey"` //
ConfigValue string `json:"configValue" gorm:"size:255;comment:ConfigValue"` //
ConfigType string `json:"configType" gorm:"size:64;comment:ConfigType"`
IsFrontend string `json:"isFrontend" gorm:"size:64;comment:是否前台"` //
Remark string `json:"remark" gorm:"size:128;comment:Remark"` //
models.ControlBy
models.ModelTime
}
func (*SysConfig) TableName() string {
return "sys_config"
}
func (e *SysConfig) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysConfig) GetId() interface{} {
return e.Id
}
-33
View File
@@ -1,33 +0,0 @@
package models
import (
"go-admin/common/models"
)
type SysContent struct {
models.Model
CateId int `json:"cateId" gorm:"type:int(11);comment:分类id"`
Name string `json:"name" gorm:"type:varchar(255);comment:名称"`
Status int `json:"status" gorm:"type:int(1);comment:状态"`
Img string `json:"img" gorm:"type:varchar(255);comment:图片"`
Content string `json:"content" gorm:"type:text;comment:内容"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"`
Sort int `json:"sort" gorm:"type:int(4);comment:排序"`
models.ControlBy
models.ModelTime
}
// TableName
func (SysContent) TableName() string {
return "sys_content"
}
// Generate
func (e *SysContent) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysContent) GetId() interface{} {
return e.Id
}
@@ -1,4 +1,4 @@
package system
package models
import "go-admin/common/models"
@@ -7,11 +7,11 @@ type SysDept struct {
ParentId int `json:"parentId" gorm:""` //上级部门
DeptPath string `json:"deptPath" gorm:"size:255;"` //
DeptName string `json:"deptName" gorm:"size:128;"` //部门名称
Sort int `json:"sort" gorm:""` //排序
Sort int `json:"sort" gorm:"size:4;"` //排序
Leader string `json:"leader" gorm:"size:128;"` //负责人
Phone string `json:"phone" gorm:"size:11;"` //手机
Email string `json:"email" gorm:"size:64;"` //邮箱
Status string `json:"status" gorm:"size:4;"` //状态
Status int `json:"status" gorm:"size:4;"` //状态
models.ControlBy
models.ModelTime
DataScope string `json:"dataScope" gorm:"-"`
@@ -19,7 +19,7 @@ type SysDept struct {
Children []SysDept `json:"children" gorm:"-"`
}
func (SysDept) TableName() string {
func (*SysDept) TableName() string {
return "sys_dept"
}
+34
View File
@@ -0,0 +1,34 @@
package models
import (
"go-admin/common/models"
)
type SysDictData struct {
DictCode int `json:"dictCode" gorm:"primaryKey;column:dict_code;autoIncrement;comment:主键编码"`
DictSort int `json:"dictSort" gorm:"size:20;comment:DictSort"`
DictLabel string `json:"dictLabel" gorm:"size:128;comment:DictLabel"`
DictValue string `json:"dictValue" gorm:"size:255;comment:DictValue"`
DictType string `json:"dictType" gorm:"size:64;comment:DictType"`
CssClass string `json:"cssClass" gorm:"size:128;comment:CssClass"`
ListClass string `json:"listClass" gorm:"size:128;comment:ListClass"`
IsDefault string `json:"isDefault" gorm:"size:8;comment:IsDefault"`
Status int `json:"status" gorm:"size:4;comment:Status"`
Default string `json:"default" gorm:"size:8;comment:Default"`
Remark string `json:"remark" gorm:"size:255;comment:Remark"`
models.ControlBy
models.ModelTime
}
func (*SysDictData) TableName() string {
return "sys_dict_data"
}
func (e *SysDictData) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysDictData) GetId() interface{} {
return e.DictCode
}
@@ -1,21 +1,20 @@
package system
package models
import (
"go-admin/common/models"
)
type SysDictType struct {
ID int `json:"id" gorm:"primaryKey;column:dict_id;autoIncrement;comment:主键编码"`
DictName string `json:"dictName" gorm:"size:128;comment:DictName"`
DictType string `json:"dictType" gorm:"size:128;comment:DictType"`
Status int `json:"status" gorm:"size:4;comment:Status"`
Remark string `json:"remark" gorm:"size:255;comment:Remark"`
models.ControlBy
models.ModelTime
ID int `json:"id" gorm:"primaryKey;column:dict_id;autoIncrement;comment:主键编码"`
DictName string `json:"dictName" gorm:"type:varchar(128);comment:DictName"`
DictType string `json:"dictType" gorm:"type:varchar(128);comment:DictType"`
Status string `json:"status" gorm:"type:varchar(4);comment:Status"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:Remark"`
}
func (SysDictType) TableName() string {
func (*SysDictType) TableName() string {
return "sys_dict_type"
}
-40
View File
@@ -1,40 +0,0 @@
package models
import (
"go-admin/common/models"
)
type SysFileDir struct {
models.Model
Label string `json:"label" gorm:"type:varchar(255);comment:目录名称"` // 目录名称
PId int `json:"pId" gorm:"type:int(11);comment:上级目录"` // 上级目录
Sort string `json:"sort" gorm:"type:bigint(20);comment:排序"` // 排序
Path string `json:"path" gorm:"type:varchar(255);comment:路径"` // 路径
Children []SysFileDir `json:"children,omitempty" gorm:"-"` // 下级信息
models.ControlBy
models.ModelTime
}
type SysFileDirL struct {
models.Model
Label string `json:"label" gorm:"type:varchar(255);comment:目录名称"` // 目录名称
PId int `json:"pId" gorm:"type:int(11);comment:上级目录"` // 上级目录
Sort string `json:"sort" gorm:"type:bigint(20);comment:排序"` // 排序
Path string `json:"path" gorm:"type:varchar(255);comment:路径"` // 路径
models.ControlBy
models.ModelTime
Children []SysFileDirL `json:"children,omitempty" gorm:"-"` // 下级信息
}
func (SysFileDir) TableName() string { /**/
return "sys_file_dir"
}
func (e *SysFileDir) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysFileDir) GetId() interface{} {
return e.Id
}
-31
View File
@@ -1,31 +0,0 @@
package models
import (
"go-admin/common/models"
)
type SysFileInfo struct {
models.Model
Type string `json:"type" gorm:"type:varchar(255);comment:类型"` //
Name string `json:"name" gorm:"type:varchar(255);comment:名称"` //
Size string `json:"size" gorm:"type:int(11);comment:大小"` //
PId int `json:"pId" gorm:"type:int(11);comment:目录"` //
Source string `json:"source" gorm:"type:varchar(255);comment:来源"` //
Url string `json:"url" gorm:"type:varchar(255);comment:地址"` //
FullUrl string `json:"fullUrl" gorm:"type:varchar(255);comment:全地址"` //
models.ControlBy
models.ModelTime
}
func (SysFileInfo) TableName() string {
return "sys_file_info"
}
func (e *SysFileInfo) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysFileInfo) GetId() interface{} {
return e.Id
}
@@ -1,35 +1,35 @@
package system
package models
import (
"encoding/json"
"errors"
"time"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/storage"
log "github.com/go-admin-team/go-admin-core/v2/logger"
"github.com/go-admin-team/go-admin-core/v2/sdk"
"github.com/go-admin-team/go-admin-core/v2/storage"
"go-admin/common/models"
)
type SysLoginLog struct {
models.Model
Username string `json:"username" gorm:"type:varchar(128);comment:用户名"`
Status string `json:"status" gorm:"type:varchar(4);comment:状态"`
Ipaddr string `json:"ipaddr" gorm:"type:varchar(255);comment:ip地址"`
LoginLocation string `json:"loginLocation" gorm:"type:varchar(255);comment:归属地"`
Browser string `json:"browser" gorm:"type:varchar(255);comment:浏览器"`
Os string `json:"os" gorm:"type:varchar(255);comment:系统"`
Platform string `json:"platform" gorm:"type:varchar(255);comment:固件"`
LoginTime time.Time `json:"loginTime" gorm:"type:timestamp;comment:登录时间"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"`
Msg string `json:"msg" gorm:"type:varchar(255);comment:信息"`
Username string `json:"username" gorm:"size:128;comment:用户名"`
Status string `json:"status" gorm:"size:4;comment:状态"`
Ipaddr string `json:"ipaddr" gorm:"size:255;comment:ip地址"`
LoginLocation string `json:"loginLocation" gorm:"size:255;comment:归属地"`
Browser string `json:"browser" gorm:"size:255;comment:浏览器"`
Os string `json:"os" gorm:"size:255;comment:系统"`
Platform string `json:"platform" gorm:"size:255;comment:固件"`
LoginTime time.Time `json:"loginTime" gorm:"comment:登录时间"`
Remark string `json:"remark" gorm:"size:255;comment:备注"`
Msg string `json:"msg" gorm:"size:255;comment:信息"`
CreatedAt time.Time `json:"createdAt" gorm:"comment:创建时间"`
UpdatedAt time.Time `json:"updatedAt" gorm:"comment:最后更新时间"`
models.ControlBy
}
func (SysLoginLog) TableName() string {
func (*SysLoginLog) TableName() string {
return "sys_login_log"
}
@@ -45,7 +45,7 @@ func (e *SysLoginLog) GetId() interface{} {
// SaveLoginLog 从队列中获取登录日志
func SaveLoginLog(message storage.Messager) (err error) {
//准备db
db := sdk.Runtime.GetDbByKey(message.GetPrefix())
db := sdk.Runtime.GetDbByTenant(message.GetPrefix())
if db == nil {
err = errors.New("db not exist")
log.Errorf("host[%s]'s %s", message.GetPrefix(), err.Error())
@@ -1,4 +1,4 @@
package system
package models
import "go-admin/common/models"
@@ -19,38 +19,24 @@ type SysMenu struct {
Sort int `json:"sort" gorm:"size:4;"`
Visible string `json:"visible" gorm:"size:1;"`
IsFrame string `json:"isFrame" gorm:"size:1;DEFAULT:0;"`
SysApi []SysApi `json:"sysApi" gorm:"many2many:sys_menu_api_rule"`
Apis []int `json:"apis" gorm:"-"`
DataScope string `json:"dataScope" gorm:"-"`
Params string `json:"params" gorm:"-"`
RoleId int `gorm:"-"`
Children []SysMenu `json:"children" gorm:"-"`
Children []SysMenu `json:"children,omitempty" gorm:"-"`
IsSelect bool `json:"is_select" gorm:"-"`
models.ControlBy
models.ModelTime
}
type SysMenus struct {
MenuId int `json:"menuId" gorm:"column:menu_id;primaryKey;autoIncrement;"`
MenuName string `json:"menuName" gorm:"column:menu_name"`
Title string `json:"title" gorm:"column:title"`
Icon string `json:"icon" gorm:"column:icon"`
Path string `json:"path" gorm:"column:path"`
MenuType string `json:"menuType" gorm:"column:menu_type"`
Action string `json:"action" gorm:"column:action"`
Permission string `json:"permission" gorm:"column:permission"`
ParentId int `json:"parentId" gorm:"column:parent_id"`
NoCache bool `json:"noCache" gorm:"column:no_cache"`
Breadcrumb string `json:"breadcrumb" gorm:"column:breadcrumb"`
Component string `json:"component" gorm:"column:component"`
Sort int `json:"sort" gorm:"column:sort"`
Visible string `json:"visible" gorm:"column:visible"`
Children []SysMenu `json:"children" gorm:"-"`
models.ControlBy
models.ModelTime
DataScope string `json:"dataScope" gorm:"-"`
Params string `json:"params" gorm:"-"`
}
type SysMenuSlice []SysMenu
func (SysMenu) TableName() string {
func (x SysMenuSlice) Len() int { return len(x) }
func (x SysMenuSlice) Less(i, j int) bool { return x[i].Sort < x[j].Sort }
func (x SysMenuSlice) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (*SysMenu) TableName() string {
return "sys_menu"
}
+88
View File
@@ -0,0 +1,88 @@
package models
import (
"encoding/json"
"errors"
"time"
log "github.com/go-admin-team/go-admin-core/v2/logger"
"github.com/go-admin-team/go-admin-core/v2/sdk"
"github.com/go-admin-team/go-admin-core/v2/storage"
"go-admin/common/models"
)
type SysOperaLog struct {
models.Model
Title string `json:"title" gorm:"size:255;comment:操作模块"`
BusinessType string `json:"businessType" gorm:"size:128;comment:操作类型"`
BusinessTypes string `json:"businessTypes" gorm:"size:128;comment:BusinessTypes"`
Method string `json:"method" gorm:"size:128;comment:函数"`
RequestMethod string `json:"requestMethod" gorm:"size:128;comment:请求方式 GET POST PUT DELETE"`
OperatorType string `json:"operatorType" gorm:"size:128;comment:操作类型"`
OperName string `json:"operName" gorm:"size:128;comment:操作者"`
DeptName string `json:"deptName" gorm:"size:128;comment:部门名称"`
OperUrl string `json:"operUrl" gorm:"size:255;comment:访问地址"`
OperIp string `json:"operIp" gorm:"size:128;comment:客户端ip"`
OperLocation string `json:"operLocation" gorm:"size:128;comment:访问位置"`
OperParam string `json:"operParam" gorm:"text;comment:请求参数"`
Status string `json:"status" gorm:"size:4;comment:操作状态 1:正常 2:关闭"`
OperTime time.Time `json:"operTime" gorm:"comment:操作时间"`
JsonResult string `json:"jsonResult" gorm:"size:255;comment:返回数据"`
Remark string `json:"remark" gorm:"size:255;comment:备注"`
LatencyTime string `json:"latencyTime" gorm:"size:128;comment:耗时"`
UserAgent string `json:"userAgent" gorm:"size:255;comment:ua"`
CreatedAt time.Time `json:"createdAt" gorm:"comment:创建时间"`
UpdatedAt time.Time `json:"updatedAt" gorm:"comment:最后更新时间"`
models.ControlBy
}
func (*SysOperaLog) TableName() string {
return "sys_opera_log"
}
func (e *SysOperaLog) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysOperaLog) GetId() interface{} {
return e.Id
}
// SaveOperaLog 从队列中获取操作日志
func SaveOperaLog(message storage.Messager) (err error) {
//准备db
db := sdk.Runtime.GetDbByTenant(message.GetPrefix())
if db == nil {
err = errors.New("db not exist")
log.Errorf("host[%s]'s %s", message.GetPrefix(), err.Error())
// Log writing to the database ignores error
return nil
}
var rb []byte
rb, err = json.Marshal(message.GetValues())
if err != nil {
log.Errorf("json Marshal error, %s", err.Error())
// Log writing to the database ignores error
return nil
}
var l SysOperaLog
err = json.Unmarshal(rb, &l)
if err != nil {
log.Errorf("json Unmarshal error, %s", err.Error())
// Log writing to the database ignores error
return nil
}
// 超出100个字符返回值截断
if len(l.JsonResult) > 100 {
l.JsonResult = l.JsonResult[:100]
}
err = db.Create(&l).Error
if err != nil {
log.Errorf("db create error, %s", err.Error())
// Log writing to the database ignores error
return nil
}
return nil
}
@@ -1,4 +1,4 @@
package system
package models
import "go-admin/common/models"
@@ -6,7 +6,7 @@ type SysPost struct {
PostId int `gorm:"primaryKey;autoIncrement" json:"postId"` //岗位编号
PostName string `gorm:"size:128;" json:"postName"` //岗位名称
PostCode string `gorm:"size:128;" json:"postCode"` //岗位代码
Sort int `gorm:"" json:"sort"` //岗位排序
Sort int `gorm:"size:4;" json:"sort"` //岗位排序
Status int `gorm:"size:4;" json:"status"` //状态
Remark string `gorm:"size:255;" json:"remark"` //描述
models.ControlBy
@@ -16,7 +16,7 @@ type SysPost struct {
Params string `gorm:"-" json:"params"`
}
func (SysPost) TableName() string {
func (*SysPost) TableName() string {
return "sys_post"
}
+35
View File
@@ -0,0 +1,35 @@
package models
import "go-admin/common/models"
type SysRole struct {
RoleId int `json:"roleId" gorm:"primaryKey;autoIncrement"` // 角色编码
RoleName string `json:"roleName" gorm:"size:128;"` // 角色名称
Status string `json:"status" gorm:"size:4;"` // 状态 1禁用 2正常
RoleKey string `json:"roleKey" gorm:"size:128;"` //角色代码
RoleSort int `json:"roleSort" gorm:""` //角色排序
Flag string `json:"flag" gorm:"size:128;"` //
Remark string `json:"remark" gorm:"size:255;"` //备注
Admin bool `json:"admin" gorm:"size:4;"`
DataScope string `json:"dataScope" gorm:"size:128;"`
Params string `json:"params" gorm:"-"`
MenuIds []int `json:"menuIds" gorm:"-"`
DeptIds []int `json:"deptIds" gorm:"-"`
SysDept []SysDept `json:"sysDept" gorm:"many2many:sys_role_dept;foreignKey:RoleId;joinForeignKey:role_id;references:DeptId;joinReferences:dept_id;"`
SysMenu *[]SysMenu `json:"sysMenu" gorm:"many2many:sys_role_menu;foreignKey:RoleId;joinForeignKey:role_id;references:MenuId;joinReferences:menu_id;"`
models.ControlBy
models.ModelTime
}
func (*SysRole) TableName() string {
return "sys_role"
}
func (e *SysRole) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysRole) GetId() interface{} {
return e.RoleId
}
+89
View File
@@ -0,0 +1,89 @@
package models
import (
"go-admin/common/models"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type SysUser struct {
UserId int `gorm:"primaryKey;autoIncrement;comment:编码" json:"userId"`
Username string `json:"username" gorm:"size:64;comment:用户名"`
Password string `json:"-" gorm:"size:128;comment:密码"`
NickName string `json:"nickName" gorm:"size:128;comment:昵称"`
Phone string `json:"phone" gorm:"size:11;comment:手机号"`
RoleId int `json:"roleId" gorm:"size:20;comment:角色ID"`
Salt string `json:"-" gorm:"size:255;comment:加盐"`
Avatar string `json:"avatar" gorm:"size:255;comment:头像"`
Sex string `json:"sex" gorm:"size:255;comment:性别"`
Email string `json:"email" gorm:"size:128;comment:邮箱"`
DeptId int `json:"deptId" gorm:"size:20;comment:部门"`
PostId int `json:"postId" gorm:"size:20;comment:岗位"`
Remark string `json:"remark" gorm:"size:255;comment:备注"`
Status string `json:"status" gorm:"size:4;comment:状态"`
DeptIds []int `json:"deptIds" gorm:"-"`
PostIds []int `json:"postIds" gorm:"-"`
RoleIds []int `json:"roleIds" gorm:"-"`
Dept *SysDept `json:"dept"`
models.ControlBy
models.ModelTime
}
func (*SysUser) TableName() string {
return "sys_user"
}
func (e *SysUser) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysUser) GetId() interface{} {
return e.UserId
}
// Encrypt hashes Password, unless it already holds a hash.
//
// The hooks below run on whatever is in the struct, and a user read from the
// database carries the stored hash in that field. Hashing it again produces a
// hash of a hash, and the password that user knows no longer matches anything:
// they cannot log in, and nothing reports an error. The only thing preventing
// that today is an Omit("password") on the one update that loads a user first,
// which makes every other write to this model one line away from destroying
// credentials.
//
// bcrypt.Cost parses a hash and fails on anything else, so it distinguishes
// the two cases without the call site having to say which it is. The cost is
// that a password which is itself a well-formed bcrypt hash would be stored
// unchanged - a 60-character string beginning "$2a$", not something a person
// types, and it grants whoever set it no access they did not already have.
func (e *SysUser) Encrypt() error {
if e.Password == "" {
return nil
}
if _, err := bcrypt.Cost([]byte(e.Password)); err == nil {
return nil
}
hash, err := bcrypt.GenerateFromPassword([]byte(e.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
e.Password = string(hash)
return nil
}
func (e *SysUser) BeforeCreate(_ *gorm.DB) error {
return e.Encrypt()
}
func (e *SysUser) BeforeUpdate(_ *gorm.DB) error {
return e.Encrypt()
}
func (e *SysUser) AfterFind(_ *gorm.DB) error {
e.DeptIds = []int{e.DeptId}
e.PostIds = []int{e.PostId}
e.RoleIds = []int{e.RoleId}
return nil
}
+106
View File
@@ -0,0 +1,106 @@
package models
import (
"testing"
"golang.org/x/crypto/bcrypt"
)
const knownPassword = "correct-horse-battery-staple"
// A user loaded from the database carries the stored hash in Password, and the
// hooks run on whatever is in the struct. Hashing it a second time produces a
// hash of a hash: the password the user knows stops matching, they cannot log
// in, and nothing reports an error.
//
// Only an Omit("password") on one call site stood between this and every write
// to the model. This is the test that removes the need for it.
func TestEncryptLeavesAnAlreadyHashedPasswordAlone(t *testing.T) {
fresh := SysUser{Password: knownPassword}
if err := fresh.Encrypt(); err != nil {
t.Fatalf("Encrypt: %v", err)
}
stored := fresh.Password
if err := bcrypt.CompareHashAndPassword([]byte(stored), []byte(knownPassword)); err != nil {
t.Fatalf("setup failed: the password was not hashed: %v", err)
}
// What a query puts in the struct, and what an update then hands the hook.
loaded := SysUser{Password: stored}
if err := loaded.Encrypt(); err != nil {
t.Fatalf("Encrypt on a loaded user: %v", err)
}
if loaded.Password != stored {
t.Error("Encrypt re-hashed a stored hash; the user can no longer log in")
}
if err := bcrypt.CompareHashAndPassword([]byte(loaded.Password), []byte(knownPassword)); err != nil {
t.Errorf("the user can no longer log in with their password: %v", err)
}
}
// The other half: a password that is not a hash still gets hashed, on create
// and on update alike.
func TestEncryptHashesAPlaintextPassword(t *testing.T) {
for _, c := range []struct {
name string
hook func(*SysUser) error
}{
{"BeforeCreate", func(u *SysUser) error { return u.BeforeCreate(nil) }},
{"BeforeUpdate", func(u *SysUser) error { return u.BeforeUpdate(nil) }},
} {
t.Run(c.name, func(t *testing.T) {
u := SysUser{Password: knownPassword}
if err := c.hook(&u); err != nil {
t.Fatal(err)
}
if u.Password == knownPassword {
t.Fatal("the password was stored as it was typed")
}
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(knownPassword)); err != nil {
t.Errorf("the stored value does not verify the password: %v", err)
}
})
}
}
// An empty Password means "not being set", and must not become a hash of "".
func TestEncryptIgnoresAnEmptyPassword(t *testing.T) {
u := SysUser{}
if err := u.Encrypt(); err != nil {
t.Fatal(err)
}
if u.Password != "" {
t.Errorf("an unset password became %q", u.Password)
}
}
// Encrypt runs on every update of this model, including the ones that change
// something else entirely. What it costs when there is nothing to do is the
// difference between a profile update and a bcrypt round; the correctness test
// above is what catches a regression, this reports the size of it.
func BenchmarkEncrypt(b *testing.B) {
fresh := SysUser{Password: knownPassword}
if err := fresh.Encrypt(); err != nil {
b.Fatal(err)
}
b.Run("already hashed", func(b *testing.B) {
u := SysUser{Password: fresh.Password}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
if err := u.Encrypt(); err != nil {
b.Fatal(err)
}
}
})
b.Run("plaintext", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
u := SysUser{Password: knownPassword}
if err := u.Encrypt(); err != nil {
b.Fatal(err)
}
}
})
}
-44
View File
@@ -1,44 +0,0 @@
package models
import (
"go-admin/common/models"
)
type SysSetting struct {
SettingsId int `json:"settings_id" gorm:"primary_key;AUTO_INCREMENT"`
Name string `json:"name" gorm:"type:varchar(256);"`
Logo string `json:"logo" gorm:"type:varchar(256);"`
models.ModelTime
}
func (SysSetting) TableName() string {
return "sys_setting"
}
func (s *SysSetting) GetId() interface{} {
return s.SettingsId
}
//查询
//func (s *SysSetting) Get() (create SysSetting, err error) {
// result := orm.Eloquent.Table("sys_setting").First(&create)
// if result.Error != nil {
// err = result.Error
// return
// }
// return create, nil
//}
//修改
//func (s *SysSetting) Update() (update SysSetting, err error) {
// if err = orm.Eloquent.Table("sys_setting").Model(&update).Where("settings_id = ?", s.SettingsId).Updates(&s).Error; err != nil {
// return
// }
// return
//}
type ResponseSystemConfig struct {
Name string `json:"name" binding:"required"` // 名称
Logo string `json:"logo" binding:"required"` // 头像
SettingsId int `json:"settings_id" binding:"required"` // 头像
}
-16
View File
@@ -1,16 +0,0 @@
package system
//sys_casbin_rule
type CasbinRule struct {
PType string `json:"p_type" gorm:"size:100;"`
V0 string `json:"v0" gorm:"size:100;"`
V1 string `json:"v1" gorm:"size:100;"`
V2 string `json:"v2" gorm:"size:100;"`
V3 string `json:"v3" gorm:"size:100;"`
V4 string `json:"v4" gorm:"size:100;"`
V5 string `json:"v5" gorm:"size:100;"`
}
func (CasbinRule) TableName() string {
return "sys_casbin_rule"
}
-81
View File
@@ -1,81 +0,0 @@
package system
import (
"errors"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk/config"
)
type DataPermission struct {
DataScope string
UserId int
DeptId int
RoleId int
}
func (e *DataPermission) GetDataScope(tableName string, db *gorm.DB) (*gorm.DB, error) {
if !config.ApplicationConfig.EnableDP {
usageStr := `数据权限已经为您` + pkg.Green(`关闭`) + `,如需开启请参考配置文件字段说明`
log.Debug("%s\n", usageStr)
return db, nil
}
user := new(SysUser)
role := new(SysRole)
err := db.Find(user, e.UserId).Error
if err != nil {
return nil, errors.New("获取用户数据出错 msg:" + err.Error())
}
err = db.Find(role, user.RoleId).Error
if err != nil {
return nil, errors.New("获取用户数据出错 msg:" + err.Error())
}
if role.DataScope == "2" {
db = db.Where(tableName+".create_by in (select sys_user.user_id from sys_role_dept left join sys_user on sys_user.dept_id=sys_role_dept.dept_id where sys_role_dept.role_id = ?)", user.RoleId)
}
if role.DataScope == "3" {
db = db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", user.DeptId)
}
if role.DataScope == "4" {
db = db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+pkg.IntToString(user.DeptId)+"%")
}
if role.DataScope == "5" || role.DataScope == "" {
db = db.Where(tableName+".create_by = ?", e.UserId)
}
return db, nil
}
func DataScopes(tableName string, userId int) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
user := new(SysUser)
role := new(SysRole)
user.UserId = userId
err := db.Find(user, userId).Error
if err != nil {
db.Error = errors.New("获取用户数据出错 msg:" + err.Error())
return db
}
err = db.Find(role, user.RoleId).Error
if err != nil {
db.Error = errors.New("获取用户数据出错 msg:" + err.Error())
return db
}
if role.DataScope == "2" {
return db.Where(tableName+".create_by in (select sys_user.user_id from sys_role_dept left join sys_user on sys_user.dept_id=sys_role_dept.dept_id where sys_role_dept.role_id = ?)", user.RoleId)
}
if role.DataScope == "3" {
return db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", user.DeptId)
}
if role.DataScope == "4" {
return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+pkg.IntToString(user.DeptId)+"%")
}
if role.DataScope == "5" || role.DataScope == "" {
return db.Where(tableName+".create_by = ?", userId)
}
return db
}
}
-11
View File
@@ -1,11 +0,0 @@
package system
//sys_role_dept
type SysRoleDept struct {
RoleId int `gorm:"size:11;primaryKey"`
DeptId int `gorm:"size:11;primaryKey"`
}
func (SysRoleDept) TableName() string {
return "sys_role_dept"
}
-172
View File
@@ -1,172 +0,0 @@
package system
import (
"fmt"
"github.com/casbin/casbin/v2"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
"go-admin/common/models"
)
type RoleMenu struct {
RoleId int `gorm:""`
MenuId int `gorm:""`
RoleName string `gorm:"size:128"`
models.ControlBy
}
func (RoleMenu) TableName() string {
return "sys_role_menu"
}
type MenuPath struct {
Path string `json:"path"`
}
func (rm *RoleMenu) Get(tx *gorm.DB) ([]RoleMenu, error) {
var r []RoleMenu
table := tx.Table("sys_role_menu")
if rm.RoleId != 0 {
table = table.Where("role_id = ?", rm.RoleId)
}
if err := table.Find(&r).Error; err != nil {
return nil, err
}
return r, nil
}
func (rm *RoleMenu) GetPermis(tx *gorm.DB) ([]string, error) {
var r []SysMenu
table := tx.Select("sys_menu.permission").Table("sys_menu").Joins("left join sys_role_menu on sys_menu.menu_id = sys_role_menu.menu_id")
table = table.Where("role_id = ?", rm.RoleId)
table = table.Where("sys_menu.menu_type in('F','C')")
if err := table.Find(&r).Error; err != nil {
return nil, err
}
var list []string
for i := 0; i < len(r); i++ {
list = append(list, r[i].Permission)
}
return list, nil
}
func (rm *RoleMenu) GetIDS(tx *gorm.DB) ([]MenuPath, error) {
var r []MenuPath
table := tx.Select("sys_menu.path").Table("sys_role_menu")
table = table.Joins("left join sys_role on sys_role.role_id=sys_role_menu.role_id")
table = table.Joins("left join sys_menu on sys_menu.id=sys_role_menu.menu_id")
table = table.Where("sys_role.role_name = ? and sys_menu.type=1", rm.RoleName)
if err := table.Find(&r).Error; err != nil {
return nil, err
}
return r, nil
}
func (rm *RoleMenu) DeleteRoleMenu(tx *gorm.DB, roleId int) error {
if err := tx.Table("sys_role_dept").Where("role_id = ?", roleId).Delete(&rm).Error; err != nil {
return err
}
if err := tx.Table("sys_role_menu").Where("role_id = ?", roleId).Delete(&rm).Error; err != nil {
return err
}
var role SysRole
if err := tx.Table("sys_role").Where("role_id = ?", roleId).First(&role).Error; err != nil {
return err
}
sql3 := "delete from sys_casbin_rule where v0= '" + role.RoleKey + "';"
if err := tx.Exec(sql3).Error; err != nil {
return err
}
return nil
}
// 该方法即将弃用
func (rm *RoleMenu) BatchDeleteRoleMenu(tx *gorm.DB, roleIds []int) error {
if err := tx.Table("sys_role_menu").Where("role_id in (?)", roleIds).Delete(&rm).Error; err != nil {
return err
}
var role []SysRole
if err := tx.Table("sys_role").Where("role_id in (?)", roleIds).Find(&role).Error; err != nil {
return err
}
sql := ""
for i := 0; i < len(role); i++ {
sql += "delete from sys_casbin_rule where v0= '" + role[i].RoleName + "';"
}
if err := tx.Exec(sql).Error; err != nil {
return err
}
if err := tx.Commit().Error; err != nil {
return err
}
return nil
}
func (rm *RoleMenu) Insert(tx *gorm.DB, enforcer *casbin.SyncedEnforcer, roleId int, menuId []int) error {
var err error
var (
role SysRole
menu []SysMenu
casbinRules []CasbinRule // casbinRule 待插入队列
)
// 在事务中做一些数据库操作(从这一点使用'tx',而不是'db')
if err = tx.Table("sys_role").Where("role_id = ?", roleId).First(&role).Error; err != nil {
return err
}
if err = tx.Table("sys_menu").Where("menu_id in (?)", menuId).Find(&menu).Error; err != nil {
return err
}
//ORM不支持批量插入所以需要拼接 sql 串
sysRoleMenuSql := "INSERT INTO `sys_role_menu` (`role_id`,`menu_id`,`role_name`) VALUES "
for i, m := range menu {
// 拼装'role_menu'表批量插入SQL语句
sysRoleMenuSql += fmt.Sprintf("(%d,%d,'%s')", role.RoleId, m.MenuId, role.RoleKey)
if i == len(menu)-1 {
sysRoleMenuSql += ";" //最后一条数据 以分号结尾
} else {
sysRoleMenuSql += ","
}
if m.MenuType == "A" {
// 加入队列
casbinRules = append(casbinRules,
CasbinRule{
V0: role.RoleKey,
V1: m.Path,
V2: m.Action,
})
}
}
// 执行批量插入sys_role_menu
if err = tx.Exec(sysRoleMenuSql).Error; err != nil {
return err
}
// 执行批量插入sys_casbin_rule
if len(casbinRules) > 0 {
if err = tx.Create(&casbinRules).Error; err != nil {
return err
}
}
return nil
}
func (rm *RoleMenu) Delete(tx *gorm.DB, RoleId string, MenuID string) (bool, error) {
rm.RoleId, _ = pkg.StringToInt(RoleId)
table := tx.Table("sys_role_menu").Where("role_id = ?", RoleId)
if MenuID != "" {
table = table.Where("menu_id = ?", MenuID)
}
if err := table.Delete(&rm).Error; err != nil {
return false, err
}
return true, nil
}
-30
View File
@@ -1,30 +0,0 @@
package system
import (
"go-admin/common/models"
)
type SysConfig struct {
models.Model
ConfigName string `json:"configName" gorm:"type:varchar(128);comment:ConfigName"` //
ConfigKey string `json:"configKey" gorm:"type:varchar(128);comment:ConfigKey"` //
ConfigValue string `json:"configValue" gorm:"type:varchar(255);comment:ConfigValue"` //
ConfigType string `json:"configType" gorm:"type:varchar(64);comment:ConfigType"`
IsFrontend int `json:"isFrontend" gorm:"type:varchar(64);comment:是否前台"` //
Remark string `json:"remark" gorm:"type:varchar(128);comment:Remark"` //
models.ControlBy
models.ModelTime
}
func (SysConfig) TableName() string {
return "sys_config"
}
func (e *SysConfig) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysConfig) GetId() interface{} {
return e.Id
}
-35
View File
@@ -1,35 +0,0 @@
package system
import (
"go-admin/common/models"
)
type SysDictData struct {
models.ControlBy
models.ModelTime
DictCode int `json:"dictCode" gorm:"primaryKey;column:dict_code;autoIncrement;comment:主键编码"`
DictSort int `json:"dictSort" gorm:"type:bigint(20);comment:DictSort"`
DictLabel string `json:"dictLabel" gorm:"type:varchar(128);comment:DictLabel"`
DictValue string `json:"dictValue" gorm:"type:varchar(255);comment:DictValue"`
DictType string `json:"dictType" gorm:"type:varchar(64);comment:DictType"`
CssClass string `json:"cssClass" gorm:"type:varchar(128);comment:CssClass"`
ListClass string `json:"listClass" gorm:"type:varchar(128);comment:ListClass"`
IsDefault string `json:"isDefault" gorm:"type:varchar(8);comment:IsDefault"`
Status string `json:"status" gorm:"type:varchar(4);comment:Status"`
Default string `json:"default" gorm:"type:varchar(8);comment:Default"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:Remark"`
}
func (SysDictData) TableName() string {
return "sys_dict_data"
}
func (e *SysDictData) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysDictData) GetId() interface{} {
return e.DictCode
}
-85
View File
@@ -1,85 +0,0 @@
package system
import (
"encoding/json"
"errors"
"time"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/storage"
"go-admin/common/models"
)
type SysOperaLog struct {
models.Model
Title string `json:"title" gorm:"type:varchar(255);comment:操作模块"`
BusinessType string `json:"businessType" gorm:"type:varchar(128);comment:操作类型"`
BusinessTypes string `json:"businessTypes" gorm:"type:varchar(128);comment:BusinessTypes"`
Method string `json:"method" gorm:"type:varchar(128);comment:函数"`
RequestMethod string `json:"requestMethod" gorm:"type:varchar(128);comment:请求方式"`
OperatorType string `json:"operatorType" gorm:"type:varchar(128);comment:操作类型"`
OperName string `json:"operName" gorm:"type:varchar(128);comment:操作者"`
DeptName string `json:"deptName" gorm:"type:varchar(128);comment:部门名称"`
OperUrl string `json:"operUrl" gorm:"type:varchar(255);comment:访问地址"`
OperIp string `json:"operIp" gorm:"type:varchar(128);comment:客户端ip"`
OperLocation string `json:"operLocation" gorm:"type:varchar(128);comment:访问位置"`
OperParam string `json:"operParam" gorm:"type:varchar(255);comment:请求参数"`
Status string `json:"status" gorm:"type:varchar(4);comment:操作状态"`
OperTime time.Time `json:"operTime" gorm:"type:timestamp;comment:操作时间"`
JsonResult string `json:"jsonResult" gorm:"type:varchar(255);comment:返回数据"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"`
LatencyTime string `json:"latencyTime" gorm:"type:varchar(128);comment:耗时"`
UserAgent string `json:"userAgent" gorm:"type:varchar(255);comment:ua"`
CreatedAt time.Time `json:"createdAt" gorm:"comment:创建时间"`
UpdatedAt time.Time `json:"updatedAt" gorm:"comment:最后更新时间"`
models.ControlBy
}
func (SysOperaLog) TableName() string {
return "sys_opera_log"
}
func (e *SysOperaLog) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysOperaLog) GetId() interface{} {
return e.Id
}
// SaveOperaLog 从队列中获取操作日志
func SaveOperaLog(message storage.Messager) (err error) {
//准备db
db := sdk.Runtime.GetDbByKey(message.GetPrefix())
if db == nil {
err = errors.New("db not exist")
log.Errorf("host[%s]'s %s", message.GetPrefix(), err.Error())
return err
}
var rb []byte
rb, err = json.Marshal(message.GetValues())
if err != nil {
log.Errorf("json Marshal error, %s", err.Error())
return err
}
var l SysOperaLog
err = json.Unmarshal(rb, &l)
if err != nil {
log.Errorf("json Unmarshal error, %s", err.Error())
return err
}
if l.Title == "" {
m := &SysMenu{}
db.Model(m).Select("Title").Where("action = ?", l.Method).Where("path = ?", message.GetValues()["_fullPath"]).First(m)
l.Title = m.Title
}
err = db.Create(&l).Error
if err != nil {
log.Errorf("db create error, %s", err.Error())
return err
}
return nil
}
-33
View File
@@ -1,33 +0,0 @@
package system
import "go-admin/common/models"
type SysRole struct {
RoleId int `json:"roleId" gorm:"primaryKey;autoIncrement"` // 角色编码
RoleName string `json:"roleName" gorm:"size:128;"` // 角色名称
Status string `json:"status" gorm:"size:4;"` //
RoleKey string `json:"roleKey" gorm:"size:128;"` //角色代码
RoleSort int `json:"roleSort" gorm:""` //角色排序
Flag string `json:"flag" gorm:"size:128;"` //
Remark string `json:"remark" gorm:"size:255;"` //备注
Admin bool `json:"admin" gorm:"size:4;"`
DataScope string `json:"dataScope" gorm:"size:128;"`
Params string `json:"params" gorm:"-"`
MenuIds []int `json:"menuIds" gorm:"-"`
DeptIds []int `json:"deptIds" gorm:"-"`
models.ControlBy
models.ModelTime
}
func (SysRole) TableName() string {
return "sys_role"
}
func (e *SysRole) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysRole) GetId() interface{} {
return e.RoleId
}
-77
View File
@@ -1,77 +0,0 @@
package system
import (
"go-admin/common/models"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type SysUser struct {
models.ControlBy
models.ModelTime
UserId int `gorm:"primaryKey;autoIncrement;comment:编码" json:"userId"`
Username string `json:"username" gorm:"type:varchar(64);comment:用户名"`
Password string `json:"-" gorm:"type:varchar(128);comment:密码"`
NickName string `json:"nickName" gorm:"type:varchar(128);comment:昵称"`
Phone string `json:"phone" gorm:"type:varchar(11);comment:手机号"`
RoleId int `json:"roleId" gorm:"type:bigint(20);comment:角色ID"`
Salt string `json:"-" gorm:"type:varchar(255);comment:加盐"`
Avatar string `json:"avatar" gorm:"type:varchar(255);comment:头像"`
Sex string `json:"sex" gorm:"type:varchar(255);comment:性别"`
Email string `json:"email" gorm:"type:varchar(128);comment:邮箱"`
DeptId int `json:"deptId" gorm:"type:bigint(20);comment:部门"`
PostId int `json:"postId" gorm:"type:bigint(20);comment:岗位"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"`
Status string `json:"status" gorm:"type:varchar(4);comment:状态"`
DeptIds []int `json:"deptIds" gorm:"-"`
PostIds []int `json:"postIds" gorm:"-"`
RoleIds []int `json:"roleIds" gorm:"-"`
Dept *SysDept `json:"dept"`
}
func (SysUser) TableName() string {
return "sys_user"
}
func (e *SysUser) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysUser) GetId() interface{} {
return e.UserId
}
//加密
func (e *SysUser) Encrypt() (err error) {
if e.Password == "" {
return
}
var hash []byte
if hash, err = bcrypt.GenerateFromPassword([]byte(e.Password), bcrypt.DefaultCost); err != nil {
return
} else {
e.Password = string(hash)
return
}
}
func (e *SysUser) BeforeCreate(_ *gorm.DB) error {
return e.Encrypt()
}
func (e *SysUser) BeforeUpdate(_ *gorm.DB) error {
var err error
if e.Password != "" {
err = e.Encrypt()
}
return err
}
func (e *SysUser) AfterFind(_ *gorm.DB) error {
e.DeptIds = []int{e.DeptId}
e.PostIds = []int{e.PostId}
e.RoleIds = []int{e.RoleId}
return nil
}
-62
View File
@@ -1,62 +0,0 @@
package tools
import (
"errors"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
config2 "github.com/go-admin-team/go-admin-core/sdk/config"
)
type DBTables struct {
TableName string `gorm:"column:TABLE_NAME" json:"tableName"`
Engine string `gorm:"column:ENGINE" json:"engine"`
TableRows string `gorm:"column:TABLE_ROWS" json:"tableRows"`
TableCollation string `gorm:"column:TABLE_COLLATION" json:"tableCollation"`
CreateTime string `gorm:"column:CREATE_TIME" json:"createTime"`
UpdateTime string `gorm:"column:UPDATE_TIME" json:"updateTime"`
TableComment string `gorm:"column:TABLE_COMMENT" json:"tableComment"`
}
func (e *DBTables) GetPage(tx *gorm.DB, pageSize int, pageIndex int) ([]DBTables, int, error) {
var doc []DBTables
table := new(gorm.DB)
var count int64
if config2.DatabaseConfig.Driver == "mysql" {
table = tx.Table("information_schema.tables")
table = table.Where("TABLE_NAME not in (select table_name from `" + config2.GenConfig.DBName + "`.sys_tables) ")
table = table.Where("table_schema= ? ", config2.GenConfig.DBName)
if e.TableName != "" {
table = table.Where("TABLE_NAME = ?", e.TableName)
}
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
return nil, 0, err
}
} else {
pkg.Assert(true, "目前只支持mysql数据库", 500)
}
//table.Count(&count)
return doc, int(count), nil
}
func (e *DBTables) Get(tx *gorm.DB) (DBTables, error) {
var doc DBTables
if config2.DatabaseConfig.Driver == "mysql" {
table := tx.Table("information_schema.tables")
table = table.Where("table_schema= ? ", config2.GenConfig.DBName)
if e.TableName == "" {
return doc, errors.New("table name cannot be empty!")
}
table = table.Where("TABLE_NAME = ?", e.TableName)
if err := table.First(&doc).Error; err != nil {
return doc, err
}
} else {
pkg.Assert(true, "目前只支持mysql数据库", 500)
}
return doc, nil
}
+4 -16
View File
@@ -4,14 +4,9 @@ import (
"os"
"github.com/gin-gonic/gin"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
log "github.com/go-admin-team/go-admin-core/v2/logger"
"github.com/go-admin-team/go-admin-core/v2/sdk"
common "go-admin/common/middleware"
"go-admin/common/middleware/handler"
)
// InitRouter 路由初始化,不要怀疑,这里用到了
@@ -19,8 +14,8 @@ func InitRouter() {
var r *gin.Engine
h := sdk.Runtime.GetEngine()
if h == nil {
h = gin.New()
sdk.Runtime.SetEngine(h)
log.Fatal("not found engine...")
os.Exit(-1)
}
switch h.(type) {
case *gin.Engine:
@@ -29,14 +24,7 @@ func InitRouter() {
log.Fatal("not support other engine")
os.Exit(-1)
}
if config.SslConfig.Enable {
r.Use(handler.TlsHandler())
}
r.Use(common.Sentinel()).
Use(common.RequestId(pkg.TrafficKey)).
Use(api.SetRequestLogger)
common.InitMiddleware(r)
// the jwt middleware
authMiddleware, err := common.AuthInit()
if err != nil {
-32
View File
@@ -1,32 +0,0 @@
package router
import (
"github.com/go-admin-team/go-admin-core/sdk"
"net/http"
"github.com/gin-gonic/gin"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/tools/transfer"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func Monitor() {
var r *gin.Engine
h := sdk.Runtime.GetEngine()
if h == nil {
h = gin.New()
sdk.Runtime.SetEngine(h)
}
switch h.(type) {
case *gin.Engine:
r = h.(*gin.Engine)
default:
log.Fatal("not support other engine")
}
//开发环境启动监控指标
r.GET("/metrics", transfer.Handler(promhttp.Handler()))
//健康检查
r.GET("/health", func(c *gin.Context) {
c.Status(http.StatusOK)
})
}
+2 -12
View File
@@ -3,8 +3,8 @@ package router
import (
"github.com/gin-gonic/gin"
_ "github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"github.com/go-admin-team/go-admin-core/v2/jwtauth"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
)
var (
@@ -12,7 +12,6 @@ var (
routerCheckRole = make([]func(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware), 0)
)
// 路由示例
func InitExamplesRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
// 无需认证的路由
@@ -27,24 +26,15 @@ func InitExamplesRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gi
func examplesNoCheckRoleRouter(r *gin.Engine) {
// 可根据业务需求来设置接口版本
v1 := r.Group("/api/v1")
// 空接口防止v1定义无使用报错
v1.GET("/nilcheckrole", nil)
for _, f := range routerNoCheckRole {
f(v1)
}
// {{无需认证路由自动补充在此处请勿删除}}
//registerSysFileInfoRouter(v1)
}
// 需要认证的路由示例
func examplesCheckRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddleware) {
// 可根据业务需求来设置接口版本
v1 := r.Group("/api/v1")
// 空接口防止v1定义无使用报错
v1.GET("/checkrole", nil)
for _, f := range routerCheckRole {
f(v1, authMiddleware)
}
+24
View File
@@ -0,0 +1,24 @@
package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"go-admin/app/admin/apis"
"go-admin/common/middleware"
)
func init() {
routerCheckRole = append(routerCheckRole, registerSysApiRouter)
}
// registerSysApiRouter
func registerSysApiRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := apis.SysApi{}
r := v1.Group("/sys-api").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
r.GET("", api.GetPage)
r.GET("/:id", api.Get)
r.PUT("/:id", api.Update)
}
}
-31
View File
@@ -1,31 +0,0 @@
package router
import (
"github.com/gin-gonic/gin"
middleware2 "go-admin/common/middleware"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/models"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
)
func init() {
routerCheckRole = append(routerCheckRole, registerSysCategoryRouter)
}
// 需认证的路由代码
func registerSysCategoryRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
r := v1.Group("/syscategory").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
{
model := &models.SysCategory{}
r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.SysCategorySearch), func() interface{} {
list := make([]models.SysCategory, 0)
return &list
}))
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysCategoryById), nil))
r.POST("", actions.CreateAction(new(dto.SysCategoryControl)))
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.SysCategoryControl)))
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysCategoryById)))
}
}
-25
View File
@@ -1,25 +0,0 @@
package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/sys_china_area_data"
middleware2 "go-admin/common/middleware"
)
func init() {
routerCheckRole = append(routerCheckRole, registerSysChinaAreaDataRouter)
}
// 需认证的路由代码
func registerSysChinaAreaDataRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_china_area_data.SysChinaAreaData{}
r := v1.Group("/sys_china_area_data").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
{
r.GET("", api.GetSysChinaAreaDataList)
r.GET("/:id", api.GetSysChinaAreaData)
r.POST("", api.InsertSysChinaAreaData)
r.PUT("/:id", api.UpdateSysChinaAreaData)
r.DELETE("", api.DeleteSysChinaAreaData)
}
}
+19 -13
View File
@@ -1,10 +1,11 @@
package router
import (
"go-admin/app/admin/apis"
"go-admin/common/middleware"
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/system/sys_config"
middleware2 "go-admin/common/middleware"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
)
func init() {
@@ -13,15 +14,14 @@ func init() {
// 需认证的路由代码
func registerSysConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_config.SysConfig{}
r := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
api := apis.SysConfig{}
r := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
r.GET("", api.GetSysConfigList)
r.GET("/:id", api.GetSysConfig)
r.POST("", api.InsertSysConfig)
r.PUT("/:id", api.UpdateSysConfig)
r.DELETE("", api.DeleteSysConfig)
r.GET("", api.GetPage)
r.GET("/:id", api.Get)
r.POST("", api.Insert)
r.PUT("/:id", api.Update)
r.DELETE("", api.Delete)
}
r1 := v1.Group("/configKey").Use(authMiddleware.MiddlewareFunc())
@@ -31,7 +31,13 @@ func registerSysConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMidd
r2 := v1.Group("/app-config")
{
r2.GET("", api.GetSysConfigBySysApp)
r2.GET("", api.Get2SysApp)
}
}
r3 := v1.Group("/set-config").Use(authMiddleware.MiddlewareFunc())
{
r3.PUT("", api.Update2Set)
r3.GET("", api.Get2Set)
}
}
-37
View File
@@ -1,37 +0,0 @@
package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/models"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
middleware2 "go-admin/common/middleware"
)
func init() {
routerCheckRole = append(routerCheckRole, registerSysContentRouter)
}
// 需认证的路由代码
func registerSysContentRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
r := v1.Group("/syscontent").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
{
//r.GET("", sys_content.GetSysContentList)
//r.GET("/:id", sys_content.GetSysContent)
//r.POST("", sys_content.InsertSysContent)
//r.PUT("", sys_content.UpdateSysContent)
//r.DELETE("/:id", sys_content.DeleteSysContent)
model := &models.SysContent{}
r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.SysContentSearch), func() interface{} {
list := make([]models.SysContent, 0)
return &list
}))
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysContentById), nil))
r.POST("", actions.CreateAction(new(dto.SysContentControl)))
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.SysContentControl)))
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysContentById)))
}
}
+13 -12
View File
@@ -2,9 +2,9 @@ package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/system/sys_dept"
middleware2 "go-admin/common/middleware"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"go-admin/app/admin/apis"
"go-admin/common/middleware"
)
func init() {
@@ -13,19 +13,20 @@ func init() {
// 需认证的路由代码
func registerSysDeptRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_dept.SysDept{}
r := v1.Group("/dept").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
api := apis.SysDept{}
r := v1.Group("/dept").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
r.GET("", api.GetSysDeptList)
r.GET("/:id", api.GetSysDept)
r.POST("", api.InsertSysDept)
r.PUT("/:id", api.UpdateSysDept)
r.DELETE("/:id", api.DeleteSysDept)
r.GET("", api.GetPage)
r.GET("/:id", api.Get)
r.POST("", api.Insert)
r.PUT("/:id", api.Update)
r.DELETE("", api.Delete)
}
r1 := v1.Group("").Use(authMiddleware.MiddlewareFunc())
{
r1.GET("/deptTree", api.GetDeptTree)
r1.GET("/deptTree", api.Get2Tree)
}
}
}
+37
View File
@@ -0,0 +1,37 @@
package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"go-admin/app/admin/apis"
"go-admin/common/middleware"
)
func init() {
routerCheckRole = append(routerCheckRole, registerDictRouter)
}
func registerDictRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
dictApi := apis.SysDictType{}
dataApi := apis.SysDictData{}
dicts := v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
dicts.GET("/data", dataApi.GetPage)
dicts.GET("/data/:dictCode", dataApi.Get)
dicts.POST("/data", dataApi.Insert)
dicts.PUT("/data/:dictCode", dataApi.Update)
dicts.DELETE("/data", dataApi.Delete)
dicts.GET("/type-option-select", dictApi.GetAll)
dicts.GET("/type", dictApi.GetPage)
dicts.GET("/type/:id", dictApi.Get)
dicts.POST("/type", dictApi.Insert)
dicts.PUT("/type/:id", dictApi.Update)
dicts.DELETE("/type", dictApi.Delete)
}
opSelect := v1.Group("/dict-data").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
opSelect.GET("/option-select", dataApi.GetAll)
}
}
-25
View File
@@ -1,25 +0,0 @@
package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/sys_file"
middleware2 "go-admin/common/middleware"
)
func init() {
routerCheckRole = append(routerCheckRole, registerSysFileDirRouter)
}
// 需认证的路由代码
func registerSysFileDirRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_file.SysFileDir{}
r := v1.Group("/sysfiledir").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
{
r.GET("", api.GetSysFileDirList)
r.GET("/:id", api.GetSysFileDir)
r.POST("", api.InsertSysFileDir)
r.PUT("/:id", api.UpdateSysFileDir)
r.DELETE("/:id", api.DeleteSysFileDir)
}
}
-25
View File
@@ -1,25 +0,0 @@
package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/sys_file"
middleware2 "go-admin/common/middleware"
)
func init() {
routerCheckRole = append(routerCheckRole, registerSysFileInfoRouter)
}
// 需认证的路由代码
func registerSysFileInfoRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_file.SysFileInfo{}
r := v1.Group("/sysfileinfo").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
{
r.GET("", api.GetSysFileInfoList)
r.GET("/:id", api.GetSysFileInfo)
r.POST("", api.InsertSysFileInfo)
r.PUT("/:id", api.UpdateSysFileInfo)
r.DELETE("/:id", api.DeleteSysFileInfo)
}
}
+10 -11
View File
@@ -2,9 +2,9 @@ package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/system/sys_login_log"
middleware2 "go-admin/common/middleware"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"go-admin/app/admin/apis"
"go-admin/common/middleware"
)
func init() {
@@ -13,13 +13,12 @@ func init() {
// 需认证的路由代码
func registerSysLoginLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_login_log.SysLoginLog{}
r := v1.Group("/sys-login-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
api := apis.SysLoginLog{}
r := v1.Group("/sys-login-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
r.GET("", api.GetSysLoginLogList)
r.GET("/:id", api.GetSysLoginLog)
r.POST("", api.InsertSysLoginLog)
r.PUT("/:id", api.UpdateSysLoginLog)
r.DELETE("", api.DeleteSysLoginLog)
r.GET("", api.GetPage)
r.GET("/:id", api.Get)
r.DELETE("", api.Delete)
}
}
}
+13 -19
View File
@@ -2,9 +2,9 @@ package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/system/sys_menu"
middleware2 "go-admin/common/middleware"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"go-admin/app/admin/apis"
"go-admin/common/middleware"
)
func init() {
@@ -13,27 +13,21 @@ func init() {
// 需认证的路由代码
func registerSysMenuRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_menu.SysMenu{}
//menu := v1.Group("/menu").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
//{
// menu.GET("/:id", system.GetMenu)
// menu.POST("", system.InsertMenu)
// menu.PUT("", system.UpdateMenu)
// menu.DELETE("/:id", system.DeleteMenu)
//}
r := v1.Group("/menu").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
api := apis.SysMenu{}
r := v1.Group("/menu").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
r.GET("", api.GetSysMenuList)
r.GET("/:id", api.GetSysMenu)
r.POST("", api.InsertSysMenu)
r.PUT("/:id", api.UpdateSysMenu)
r.DELETE("/:id", api.DeleteSysMenu)
r.GET("", api.GetPage)
r.GET("/:id", api.Get)
r.POST("", api.Insert)
r.PUT("/:id", api.Update)
r.DELETE("", api.Delete)
}
r1 := v1.Group("").Use(authMiddleware.MiddlewareFunc())
{
r1.GET("/menurole", api.GetMenuRole)
r1.GET("/menuids", api.GetMenuIDS)
//r1.GET("/menuids", api.GetMenuIDS)
}
}
}
+9 -11
View File
@@ -2,9 +2,9 @@ package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/system/sys_opera_log"
middleware2 "go-admin/common/middleware"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"go-admin/app/admin/apis"
"go-admin/common/middleware"
)
func init() {
@@ -13,13 +13,11 @@ func init() {
// 需认证的路由代码
func registerSysOperaLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_opera_log.SysOperaLog{}
r := v1.Group("/sys-opera-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
api := apis.SysOperaLog{}
r := v1.Group("/sys-opera-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
r.GET("", api.GetSysOperaLogList)
r.GET("/:id", api.GetSysOperaLog)
r.POST("", api.InsertSysOperaLog)
r.PUT("/:id", api.UpdateSysOperaLog)
r.DELETE("", api.DeleteSysOperaLog)
r.GET("", api.GetPage)
r.GET("/:id", api.Get)
r.DELETE("", api.Delete)
}
}
}
+11 -11
View File
@@ -2,9 +2,9 @@ package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/system/sys_post"
middleware2 "go-admin/common/middleware"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"go-admin/app/admin/apis"
"go-admin/common/middleware"
)
func init() {
@@ -13,13 +13,13 @@ func init() {
// 需认证的路由代码
func registerSyPostRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_post.SysPost{}
r := v1.Group("/post").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
api := apis.SysPost{}
r := v1.Group("/post").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
r.GET("", api.GetSysPostList)
r.GET("/:id", api.GetSysPost)
r.POST("", api.InsertSysPost)
r.PUT("/:id", api.UpdateSysPost)
r.DELETE("/:id", api.DeleteSysPost)
r.GET("", api.GetPage)
r.GET("/:id", api.Get)
r.POST("", api.Insert)
r.PUT("/:id", api.Update)
r.DELETE("", api.Delete)
}
}
}
+16 -11
View File
@@ -2,9 +2,10 @@ package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/system/sys_role"
middleware2 "go-admin/common/middleware"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"go-admin/app/admin/apis"
"go-admin/common/middleware"
)
func init() {
@@ -13,14 +14,18 @@ func init() {
// 需认证的路由代码
func registerSysRoleRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_role.SysRole{}
r := v1.Group("/role").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
api := apis.SysRole{}
r := v1.Group("/role").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
r.GET("", api.GetSysRoleList)
r.GET("/:id", api.GetSysRole)
r.POST("", api.InsertSysRole)
r.PUT("/:id", api.UpdateSysRole)
r.DELETE("", api.DeleteSysRole)
r.GET("", api.GetPage)
r.GET("/:id", api.Get)
r.POST("", api.Insert)
r.PUT("/:id", api.Update)
r.DELETE("", api.Delete)
}
r1 := v1.Group("").Use(authMiddleware.MiddlewareFunc())
{
r1.PUT("/role-status", api.Update2Status)
r1.PUT("/roledatascope", api.Update2DataScope)
}
v1.PUT("/roledatascope", api.UpdateRoleDataScope)
}
+39 -166
View File
@@ -1,24 +1,21 @@
package router
import (
"go-admin/app/admin/apis"
"mime"
"github.com/go-admin-team/go-admin-core/v2/sdk/config"
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"github.com/go-admin-team/go-admin-core/sdk/pkg/ws"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"github.com/go-admin-team/go-admin-core/v2/sdk/pkg/ws"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
swaggerfiles "github.com/swaggo/files"
"go-admin/app/admin/apis/monitor"
"go-admin/app/admin/apis/public"
"go-admin/app/admin/apis/system"
"go-admin/app/admin/apis/system/dict"
"go-admin/app/admin/apis/system/sys_dept"
"go-admin/app/admin/apis/system/sys_menu"
"go-admin/app/admin/apis/tools"
"go-admin/common/middleware"
"go-admin/common/middleware/handler"
_ "go-admin/docs"
_ "go-admin/docs/admin"
)
func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.RouterGroup {
@@ -27,9 +24,9 @@ func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Rou
// 静态文件
sysStaticFileRouter(g)
// swagger;注意:生产环境可以注释掉
sysSwaggerRouter(g)
// 无需认证
sysNoCheckRoleRouter(g)
if config.ApplicationConfig.Mode != "prod" {
sysSwaggerRouter(g)
}
// 需要认证
sysCheckRoleRouterInit(g, authMiddleware)
return g
@@ -41,7 +38,9 @@ func sysBaseRouter(r *gin.RouterGroup) {
go ws.WebsocketManager.SendService()
go ws.WebsocketManager.SendAllService()
r.GET("/", system.HelloWorld)
if config.ApplicationConfig.Mode != "prod" {
r.GET("/", apis.GoAdmin)
}
r.GET("/info", handler.Ping)
}
@@ -51,172 +50,46 @@ func sysStaticFileRouter(r *gin.RouterGroup) {
return
}
r.Static("/static", "./static")
r.Static("/form-generator", "./static/form-generator")
if config.ApplicationConfig.Mode != "prod" {
r.Static("/form-generator", "./static/form-generator")
}
}
func sysSwaggerRouter(r *gin.RouterGroup) {
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}
func sysNoCheckRoleRouter(r *gin.RouterGroup) {
v1 := r.Group("/api/v1")
m := monitor.Monitor{}
v1.GET("/monitor/server", m.ServerInfo)
sys := system.System{}
v1.GET("/getCaptcha", sys.GenerateCaptchaHandler)
gen := tools.Gen{}
v1.GET("/gen/preview/:tableId", gen.Preview)
v1.GET("/gen/toproject/:tableId", gen.GenCode)
v1.GET("/gen/apitofile/:tableId", gen.GenApiToFile)
v1.GET("/gen/todb/:tableId", gen.GenMenuAndApi)
sysTable := tools.SysTable{}
v1.GET("/gen/tabletree", sysTable.GetSysTablesTree)
registerDBRouter(v1)
registerSysTableRouter(v1)
registerPublicRouter(v1)
registerSysSettingRouter(v1)
}
func registerDBRouter(api *gin.RouterGroup) {
db := api.Group("/db")
{
gen := tools.Gen{}
db.GET("/tables/page", gen.GetDBTableList)
db.GET("/columns/page", gen.GetDBColumnList)
}
}
func registerSysTableRouter(v1 *gin.RouterGroup) {
systables := v1.Group("/sys/tables")
{
sysTable := tools.SysTable{}
systables.GET("/page", sysTable.GetSysTableList)
tablesinfo := systables.Group("/info")
{
tablesinfo.POST("", sysTable.InsertSysTable)
tablesinfo.PUT("", sysTable.UpdateSysTable)
tablesinfo.DELETE("/:tableId", sysTable.DeleteSysTables)
tablesinfo.GET("/:tableId", sysTable.GetSysTables)
tablesinfo.GET("", sysTable.GetSysTablesInfo)
}
}
r.GET("/swagger/admin/*any", ginSwagger.WrapHandler(swaggerfiles.NewHandler(), ginSwagger.InstanceName("admin")))
}
func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
r.Group("").Use(authMiddleware.MiddlewareFunc()).GET("/ws/:id/:channel", ws.WebsocketManager.WsClient)
r.Group("").Use(authMiddleware.MiddlewareFunc()).GET("/wslogout/:id/:channel", ws.WebsocketManager.UnWsClient)
v1 := r.Group("/api/v1")
wss := r.Group("").Use(authMiddleware.MiddlewareFunc())
{
wss.GET("/ws/:id/:channel", ws.WebsocketManager.WsClient)
wss.GET("/wslogout/:id/:channel", ws.WebsocketManager.UnWsClient)
}
v1.POST("/login", authMiddleware.LoginHandler)
// Refresh time can be longer than token timeout
v1.GET("/refresh_token", authMiddleware.RefreshHandler)
//registerPageRouter(v1, authMiddleware)
v1 := r.Group("/api/v1")
{
v1.POST("/login", authMiddleware.LoginHandler)
// GET /api/v1/refresh_token 已移除,原因见 issue #820:
// 该接口用业务 token 即可换取新 token,而续期上限 MaxRefresh 依据的
// orig_iat 在每次续期时被一并重置,上限永远无法到达 —— token 一旦泄
// 露即等同于永久访问权。它此前还位于 CasbinExclude 中,任何角色的已
// 登录用户都能调用,不受权限约束。
//
// 官方前端从未调用该接口(store 中的 refreshToken action 无人 dispatch),
// 移除不影响正常使用。若确需无感续期,应在 go-admin-core 中区分
// access token 与 refresh token 后重新实现,而非沿用此路由。
}
registerBaseRouter(v1, authMiddleware)
registerDictRouter(v1, authMiddleware)
//registerSysUserRouter(v1, authMiddleware)
//registerUserCenterRouter(v1, authMiddleware)
}
func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_menu.SysMenu{}
api2 := sys_dept.SysDept{}
api := apis.SysMenu{}
api2 := apis.SysDept{}
v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
//v1auth.GET("/getinfo", system.GetInfo)
v1auth.GET("/roleMenuTreeselect/:roleId", api.GetMenuTreeSelect)
v1.GET("/menuTreeselect", api.GetMenuTreeSelect)
//v1.GET("/menuTreeselect", api.GetMenuTreeSelect)
v1auth.GET("/roleDeptTreeselect/:roleId", api2.GetDeptTreeRoleSelect)
//GetDeptTreeRoleselect)
v1auth.POST("/logout", handler.LogOut)
}
}
//func registerPageRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
// v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
// {
// v1auth.GET("/sysUserList", system.GetSysUserList)
// }
//}
//func registerUserCenterRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
// user := v1.Group("/user").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
// {
// user.GET("/profile", system.GetSysUserProfile)
// user.POST("/avatar", system.InsetSysUserAvatar)
// user.PUT("/pwd", system.SysUserUpdatePwd)
// }
//}
//func registerPostRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
// post := v1.Group("/post").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
// {
// post.GET("/:postId", system.GetPost)
// post.POST("", system.InsertPost)
// post.PUT("", system.UpdatePost)
// post.DELETE("/:postId", system.DeletePost)
// }
//}
//func registerSysUserRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
// sysuser := v1.Group("/sysUser").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
// {
// sysuser.GET("/:userId", system.GetSysUser)
// sysuser.GET("/", system.GetSysUserInit)
// sysuser.POST("", system.InsertSysUser)
// sysuser.PUT("", system.UpdateSysUser)
// sysuser.DELETE("/:userId", system.DeleteSysUser)
// }
//}
func registerDictRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
dictApi := dict.SysDictType{}
dataApi := dict.SysDictData{}
dicts := v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
dicts.GET("/data", dataApi.GetSysDictDataList)
dicts.GET("/data/:dictCode", dataApi.GetSysDictData)
dicts.POST("/data", dataApi.InsertSysDictData)
dicts.PUT("/data/:dictCode", dataApi.UpdateSysDictData)
dicts.DELETE("/data", dataApi.DeleteSysDictData)
dicts.GET("/type-option-select", dictApi.GetSysDictTypeAll)
dicts.GET("/type", dictApi.GetSysDictTypeList)
dicts.GET("/type/:id", dictApi.GetSysDictType)
dicts.POST("/type", dictApi.InsertSysDictType)
dicts.PUT("/type/:id", dictApi.UpdateSysDictType)
dicts.DELETE("/type", dictApi.DeleteSysDictType)
}
v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).GET("/data-all", dataApi.GetSysDictDataAll)
}
//func registerDeptRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
// dept := v1.Group("/dept").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
// {
// dept.GET("/:deptId", system.GetDept)
// dept.POST("", system.InsertDept)
// dept.PUT("", system.UpdateDept)
// dept.DELETE("/:id", system.DeleteDept)
// }
//}
func registerSysSettingRouter(v1 *gin.RouterGroup) {
api := system.SysSetting{}
m := monitor.Monitor{}
setting := v1.Group("/setting")
{
setting.GET("", api.GetSetting)
setting.POST("", api.CreateOrUpdateSetting)
setting.GET("/serverInfo", m.ServerInfo)
}
}
func registerPublicRouter(v1 *gin.RouterGroup) {
p := v1.Group("/public")
{
file := public.File{}
p.POST("/uploadFile", file.UploadFile)
}
}
+17 -15
View File
@@ -2,10 +2,10 @@ package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/sys_user"
jwt "github.com/go-admin-team/go-admin-core/v2/jwtauth"
"go-admin/app/admin/apis"
"go-admin/common/actions"
middleware2 "go-admin/common/middleware"
"go-admin/common/middleware"
)
func init() {
@@ -14,24 +14,26 @@ func init() {
// 需认证的路由代码
func registerSysUserRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_user.SysUser{}
r := v1.Group("/sysUser").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()).Use(actions.PermissionAction())
api := apis.SysUser{}
r := v1.Group("/sys-user").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()).Use(actions.PermissionAction())
{
r.GET("", api.GetSysUserList)
r.GET("/:id", api.GetSysUser)
r.POST("", api.InsertSysUser)
r.PUT("", api.UpdateSysUser)
r.DELETE("", api.DeleteSysUser)
r.GET("", api.GetPage)
r.GET("/:id", api.Get)
r.POST("", api.Insert)
r.PUT("", api.Update)
r.DELETE("", api.Delete)
}
user := v1.Group("/user").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()).Use(actions.PermissionAction())
user := v1.Group("/user").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()).Use(actions.PermissionAction())
{
user.GET("/profile", api.GetSysUserProfile)
user.POST("/avatar", api.InsetSysUserAvatar)
user.PUT("/pwd", api.SysUserUpdatePwd)
user.GET("/profile", api.GetProfile)
user.POST("/avatar", api.InsetAvatar)
user.PUT("/pwd/set", api.UpdatePwd)
user.PUT("/pwd/reset", api.ResetPwd)
user.PUT("/status", api.UpdateStatus)
}
v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc())
{
v1auth.GET("/getinfo", api.GetInfo)
}
}
}

Some files were not shown because too many files have changed in this diff Show More