Compare commits

...

No commits in common. "main" and "master" have entirely different histories.
main ... master

373 changed files with 41262 additions and 257 deletions

25
.gitignore vendored
View File

@ -1,23 +1,2 @@
# ---> Go
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
.idea/
log

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/server.iml" filepath="$PROJECT_DIR$/.idea/server.iml" />
</modules>
</component>
</project>

9
.idea/server.iml Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

28
Dockerfile Normal file
View File

@ -0,0 +1,28 @@
FROM dockerproxy.com/library/golang:alpine as builder
WORKDIR /go/src/miniapp
COPY . .
RUN go env -w GO111MODULE=on \
&& go env -w GOPROXY=https://goproxy.cn,direct \
&& go env -w CGO_ENABLED=0 \
&& go env \
&& go mod tidy \
&& go build -o server .
FROM dockerproxy.com/library/alpine:latest
WORKDIR /go/src/miniapp
COPY --from=0 /go/src/miniapp/server ./
COPY --from=0 /go/src/miniapp/resource ./resource/
COPY --from=0 /go/src/miniapp/docker/config.docker.yaml ./docker/
COPY --from=0 /go/src/miniapp/docker ./
# 添加时区环境变量,亚洲,上海
ENV TimeZone=Asia/Shanghai
# 使用软连接,并且将时区配置覆盖/etc/timezone
RUN ln -snf /usr/share/zoneinfo/$TimeZone /etc/localtime && echo $TimeZone > /etc/timezone
EXPOSE 8888
ENTRYPOINT ./server -c docker/config.docker.yaml

232
LICENSE
View File

@ -1,232 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,3 +1,54 @@
# JM-WechatMini
## server项目结构
```shell
├── api
│   └── v1
├── config
├── core
├── docs
├── global
├── initialize
│   └── internal
├── middleware
├── model
│   ├── request
│   └── response
├── packfile
├── resource
│   ├── excel
│   ├── page
│   └── template
├── router
├── service
├── source
└── utils
├── timer
└── upload
```
| 文件夹 | 说明 | 描述 |
| ------------ | ----------------------- | --------------------------- |
| `api` | api层 | api层 |
| `--v1` | v1版本接口 | v1版本接口 |
| `config` | 配置包 | config.yaml对应的配置结构体 |
| `core` | 核心文件 | 核心组件(zap, viper, server)的初始化 |
| `docs` | swagger文档目录 | swagger文档目录 |
| `global` | 全局对象 | 全局对象 |
| `initialize` | 初始化 | router,redis,gorm,validator, timer的初始化 |
| `--internal` | 初始化内部函数 | gorm 的 longger 自定义,在此文件夹的函数只能由 `initialize` 层进行调用 |
| `middleware` | 中间件层 | 用于存放 `gin` 中间件代码 |
| `model` | 模型层 | 模型对应数据表 |
| `--request` | 入参结构体 | 接收前端发送到后端的数据。 |
| `--response` | 出参结构体 | 返回给前端的数据结构体 |
| `packfile` | 静态文件打包 | 静态文件打包 |
| `resource` | 静态资源文件夹 | 负责存放静态文件 |
| `--excel` | excel导入导出默认路径 | excel导入导出默认路径 |
| `--page` | 表单生成器 | 表单生成器 打包后的dist |
| `--template` | 模板 | 模板文件夹,存放的是代码生成器的模板 |
| `router` | 路由层 | 路由层 |
| `service` | service层 | 存放业务逻辑问题 |
| `source` | source层 | 存放初始化数据的函数 |
| `utils` | 工具包 | 工具函数封装 |
| `--timer` | timer | 定时器接口封装 |
| `--upload` | oss | oss接口封装 |
积明医疗小程序

43
api/base.go Normal file
View File

@ -0,0 +1,43 @@
package api
import (
"git.echol.cn/loser/logger/log"
"github.com/gin-gonic/gin"
"miniapp/global"
"miniapp/model/app"
"miniapp/model/common/response"
"strconv"
)
func GetUser(ctx *gin.Context, u *app.User, dontResponse, dontCheck bool) {
userId := ctx.Request.Header.Get("userId")
if userId == "" {
if !dontResponse {
ctx.Abort()
response.FailWithMessage("未授权操作", ctx)
}
return
}
id, _ := strconv.Atoi(userId)
u.ID = uint(id)
// 查询
err := global.GVA_DB.Take(&u).Error
if err != nil {
log.Errorf("获取用户信息失败:%s", err.Error())
ctx.Abort()
if !dontResponse {
response.FailWithMessage("用户状态异常", ctx)
}
return
}
// 需要跳过微信绑定检验
if !dontCheck {
// 检查微信绑定
if u.WechatOpenId == "" {
log.Errorf("%v 未绑定微信", u.Nickname)
response.FailWithMessage("请先绑定微信", ctx)
ctx.Abort()
}
}
}

30
api/v1/app/ai_kefu.go Normal file
View File

@ -0,0 +1,30 @@
package app
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/app/request"
r "miniapp/model/common/response"
)
type AiKefuApi struct{}
// SendMessage 发送消息
func (a *AiKefuApi) SendMessage(ctx *gin.Context) {
var p request.Msg
if err := ctx.ShouldBind(&p); err != nil {
global.GVA_LOG.Error("参数校验失败", zap.Error(err))
r.FailWithMessage("参数校验失败", ctx)
return
}
kf, err := aiKefuService.MatchKeywordReplyContent(p)
if err != nil {
global.GVA_LOG.Error("查询失败", zap.Error(err))
r.FailWithMessage("查询失败", ctx)
return
}
r.OkWithDetailed(kf, "查询成功", ctx)
}

20
api/v1/app/enter.go Normal file
View File

@ -0,0 +1,20 @@
package app
import "miniapp/service"
type ApiGroup struct {
UserApi
LoginApi
FavoriteApi
VisionApi
TodosApi
AiKefuApi
}
var (
userService = service.ServiceGroupApp.AppServiceGroup.UserService
favoriteService = service.ServiceGroupApp.AppServiceGroup.FavoriteService
visionService = service.ServiceGroupApp.AppServiceGroup.VisionService
todosService = service.ServiceGroupApp.AppServiceGroup.TodesService
aiKefuService = service.ServiceGroupApp.AppServiceGroup.AiKefuService
)

80
api/v1/app/favorite.go Normal file
View File

@ -0,0 +1,80 @@
package app
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/app"
"miniapp/model/app/request"
r "miniapp/model/common/response"
)
type FavoriteApi struct{}
// GetList 获取收藏列表
func (f *FavoriteApi) GetList(ctx *gin.Context) {
var p request.GetFavoriteList
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("获取收藏列表失败", zap.Error(err))
return
}
// 获取收藏列表
err, list, total := favoriteService.GetFavoriteList(p)
if err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("获取收藏列表失败", zap.Error(err))
return
}
r.OkWithData(r.PageResult{
List: list,
Total: total,
Page: p.Page,
PageSize: p.PageSize,
}, ctx)
}
// Create 创建收藏
func (f *FavoriteApi) Create(ctx *gin.Context) {
var p app.Favorite
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("创建收藏失败", zap.Error(err))
return
}
// 创建收藏
err := favoriteService.CreateFavorite(&p)
if err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("创建收藏失败", zap.Error(err))
return
}
r.Ok(ctx)
}
// Delete 删除收藏
func (f *FavoriteApi) Delete(ctx *gin.Context) {
var p app.Favorite
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("删除收藏失败", zap.Error(err))
return
}
// 删除收藏
err := favoriteService.DeleteFavorite(&p)
if err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("删除收藏失败", zap.Error(err))
return
}
r.Ok(ctx)
}

120
api/v1/app/login.go Normal file
View File

@ -0,0 +1,120 @@
package app
import (
"context"
"encoding/json"
"fmt"
"git.echol.cn/loser/logger/log"
"github.com/gin-gonic/gin"
"miniapp/global"
"miniapp/model/app/request"
"miniapp/model/common/constant"
r "miniapp/model/common/response"
"miniapp/oauth2"
"miniapp/service"
"net/http"
"net/url"
"strconv"
)
type LoginApi struct{}
// Login 登录
func (l *LoginApi) Login(ctx *gin.Context) {
var p request.Login
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage(err.Error(), ctx)
return
}
// 获取用户基础账号信息
userId, err := oauth2.OAuthServer.UserAuthorizationHandler(ctx.Writer, ctx.Request)
if err != nil {
log.Errorf("获取用户基础账号信息失败: %v", err)
r.FailWithMessage(err.Error(), ctx)
return
}
// 重新组装登录参数
ctx.Request.Form = url.Values{
"username": {userId},
"password": {p.Password},
"scope": {"ALL"},
"grant_type": {"password"},
"nickName": {p.NickName},
"avatarUrl": {p.AvatarUrl},
}
// 参数解析成功,进行登录
if err = oauth2.OAuthServer.HandleTokenRequest(ctx.Writer, ctx.Request); err != nil {
log.Errorf("登录失败:%s", err.Error())
r.FailWithMessage(err.Error(), ctx)
return
}
// 登录成功才更新登录时间
if ctx.Writer.Status() == http.StatusOK {
// 登录成功更新登录时间和IP
uid, _ := strconv.Atoi(userId)
go service.ServiceGroupApp.AppServiceGroup.UserService.UpdateLastLoginInfo(uid)
}
}
// Refresh 刷新登录Token
func (l *LoginApi) Refresh(ctx *gin.Context) {
var p request.RefreshToken
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage("参数错误: "+err.Error(), ctx)
return
}
// 刷新Token
if err := oauth2.OAuthServer.HandleTokenRequest(ctx.Writer, ctx.Request); err != nil {
log.Errorf("Token数据返回失败: %v", err.Error())
r.FailWithMessage(err.Error(), ctx)
}
}
// Logout 退出登录
func (l *LoginApi) Logout(ctx *gin.Context) {
log.Debug("退出登录啦")
// Token字符串前缀
const bearerSchema string = "Bearer "
// 取出Token
tokenHeader := ctx.Request.Header.Get("Authorization")
tokenStr := tokenHeader[len(bearerSchema):]
// 取出原始RedisKey
baseDataId, err := global.GVA_REDIS.Get(context.Background(), constant.OAuth2RedisKey+tokenStr).Result()
if err != nil {
r.FailWithMessage("Token信息获取失败", ctx)
return
}
baseDataStr, err := global.GVA_REDIS.Get(context.Background(), constant.OAuth2RedisKey+baseDataId).Result()
if err != nil {
r.FailWithMessage("Token信息获取失败", ctx)
return
}
// 转换数据为Map
tokenData := make(map[string]any)
if err = json.Unmarshal([]byte(baseDataStr), &tokenData); err != nil {
r.FailWithMessage("系统错误: "+err.Error(), ctx)
return
}
// 删除Redis缓存的数据
global.GVA_REDIS.Del(context.Background(), constant.OAuth2RedisKey+baseDataId)
global.GVA_REDIS.Del(context.Background(), fmt.Sprintf("%v%v", constant.OAuth2RedisKey, tokenData["Access"]))
global.GVA_REDIS.Del(context.Background(), fmt.Sprintf("%v%v", constant.OAuth2RedisKey, tokenData["Refresh"]))
r.Ok(ctx)
}
func (l *LoginApi) GetWeChatToken(c *gin.Context) {
wechaetToken, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx3d38ce1103a82225&secret=3c41ca428b4d0f43cfaef6f567a1cc06")
if err != nil {
log.Errorf("获取微信Token失败: %v", err)
r.FailWithMessage(err.Error(), c)
return
}
r.OkWithData(wechaetToken, c)
}

106
api/v1/app/todos.go Normal file
View File

@ -0,0 +1,106 @@
package app
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/api"
"miniapp/global"
"miniapp/model/app"
"miniapp/model/common"
"miniapp/model/common/request"
r "miniapp/model/common/response"
"strconv"
"time"
)
type TodosApi struct{}
func (t TodosApi) GetUserTodos(ctx *gin.Context) {
var p request.GetUserNotes
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage("参数错误:"+err.Error(), ctx)
global.GVA_LOG.Error("参数错误", zap.Error(err))
return
}
var ue app.User
if api.GetUser(ctx, &ue, false, true); ctx.IsAborted() {
return
}
p.UserId = strconv.Itoa(int(ue.ID))
list, err := todosService.GetUserTodos(&p)
if err != nil {
r.FailWithMessage("获取Todo列表失败:"+err.Error(), ctx)
global.GVA_LOG.Error("获取Todo列表失败", zap.Error(err))
return
}
r.OkWithData(list, ctx)
}
// UpdateTodo 更新Todo
func (t TodosApi) UpdateTodo(ctx *gin.Context) {
var todo common.UserTodo
if err := ctx.ShouldBind(&todo); err != nil {
r.FailWithMessage("参数错误:"+err.Error(), ctx)
global.GVA_LOG.Error("参数错误", zap.Error(err))
return
}
// 更新
err := todosService.UpdateTodoById(&todo)
if err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("更新失败", zap.Error(err))
return
}
r.Ok(ctx)
}
// GetTodayTodos 获取今日待办
func (t TodosApi) GetTodayTodos(ctx *gin.Context) {
var p request.GetUserNotes
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage("参数错误:"+err.Error(), ctx)
global.GVA_LOG.Error("参数错误", zap.Error(err))
return
}
var ue app.User
if api.GetUser(ctx, &ue, false, true); ctx.IsAborted() {
return
}
p.UserId = strconv.Itoa(int(ue.ID))
list, err := todosService.GetTodayTodos(&p)
if err != nil {
r.FailWithMessage("获取Todo列表失败:"+err.Error(), ctx)
global.GVA_LOG.Error("获取Todo列表失败", zap.Error(err))
return
}
todos := make([]common.UserTodo, 0)
hour := time.Now().Hour()
for i := range list {
//将remind_time截取前两位 转为int
rt, _ := strconv.Atoi(list[i].RemindTime[:2])
rt2 := 24
if i+1 == len(list) {
rt2, _ = strconv.Atoi(list[len(list)-1].RemindTime[:2])
} else {
rt2, _ = strconv.Atoi(list[i+1].RemindTime[:2])
}
if hour >= rt && hour <= rt2 {
todos = append(todos, list[i])
}
}
//删除todos第一个元素
if len(todos) > 0 {
todos = todos[1:]
}
r.OkWithData(todos, ctx)
}

192
api/v1/app/user.go Normal file
View File

@ -0,0 +1,192 @@
package app
import (
"fmt"
"git.echol.cn/loser/logger/log"
"github.com/gin-gonic/gin"
"github.com/medivhzhan/weapp/v3"
msg "github.com/medivhzhan/weapp/v3/subscribemessage"
"miniapp/api"
"miniapp/model/app"
"miniapp/model/app/request"
"miniapp/model/app/response"
r "miniapp/model/common/response"
"miniapp/utils"
"strconv"
"strings"
)
type UserApi struct {
}
// GetUser 获取当前登录用户信息
func (u *UserApi) GetUser(ctx *gin.Context) {
// 取出当前登录用户
var ue app.User
if api.GetUser(ctx, &ue, false, true); ctx.IsAborted() {
return
}
// 转换为VO
var v response.UserVO
v.ParseOrdinary(ue)
r.OkWithData(v, ctx)
}
// BindingWeChat 绑定微信
func (u *UserApi) BindingWeChat(ctx *gin.Context) {
var p request.BindingWeChat
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
// 取出当前登录用户
var loginUser app.User
if api.GetUser(ctx, &loginUser, true, true); ctx.IsAborted() {
return
}
// 解析出UnionId和OpenId
unionId, openId, _, err := utils.WeChatUtils().GetWechatUnionId(p.Code)
if err != nil {
log.Errorf("获取微信UnionId失败%s", err.Error())
r.FailWithMessage("系统错误,请稍后再试", ctx)
return
}
// 解析成功,修改用户信息
loginUser.WechatUnionId = &unionId
loginUser.WechatOpenId = openId
if err = userService.UpdateUserInfo(&loginUser); err != nil {
log.Errorf("修改用户信息失败:%s", err.Error())
r.FailWithMessage("系统错误,请稍后再试", ctx)
return
}
r.Ok(ctx)
}
// UpdateUser 修改用户信息
func (u *UserApi) UpdateUser(ctx *gin.Context) {
var p request.ChangeUserInfo
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage("参数错误: "+err.Error(), ctx)
return
}
// 获取当前登录用户
var loginUser app.User
if api.GetUser(ctx, &loginUser, false, true); ctx.IsAborted() {
return
}
// 修改资料
if p.Nickname != "" {
loginUser.Nickname = p.Nickname
}
if p.Avatar != "" && strings.HasPrefix(p.Avatar, "http") {
loginUser.Avatar = p.Avatar
}
if p.Phone != "" {
loginUser.Phone = p.Phone
}
if p.SurgeryTime != "" {
//t, _ := time.Parse("2006-01-02", p.SurgeryTime)
//format := t.UTC().Format("2006-01-02")
loginUser.SurgeryTime = p.SurgeryTime
}
loginUser.IsSurgery = p.IsSurgery
loginUser.HospitalId = p.HospitalId
// 修改数据
if err := userService.UpdateUserInfo(&loginUser); err != nil {
log.Errorf("修改用户信息失败:%s", err.Error())
r.FailWithMessage("修改用户信息失败"+err.Error(), ctx)
return
}
// 操作成功,更新头像和昵称
r.Ok(ctx)
}
// UpdateUserHospital 修改用户医院信息
func (u *UserApi) UpdateUserHospital(ctx *gin.Context) {
var p request.ChangeUserHospital
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage("参数错误: "+err.Error(), ctx)
return
}
// 修改数据
if err := userService.UpdateUserHospital(&p); err != nil {
log.Errorf("修改用户信息失败:%s", err.Error())
r.FailWithMessage("修改用户信息失败"+err.Error(), ctx)
return
}
// 操作成功,更新头像和昵称
r.Ok(ctx)
}
// GetInfo 获取用户信息
func (u *UserApi) GetInfo(ctx *gin.Context) {
//id := ctx.Param("id")
//if id == "" {
// global.GVA_LOG.Error("参数错误")
// r.FailWithMessage("参数错误", ctx)
// return
//}
var ue app.User
if api.GetUser(ctx, &ue, false, true); ctx.IsAborted() {
return
}
// 获取用户信息
userInfo, err := userService.GetUserInfo(strconv.Itoa(int(ue.ID)))
if err != nil {
log.Errorf("获取用户信息失败:%s", err.Error())
r.FailWithMessage("获取用户信息失败"+err.Error(), ctx)
return
}
r.OkWithData(userInfo, ctx)
}
// SendMedicineRemind 发送用药提醒消息
func (u *UserApi) SendMedicineRemind(ctx *gin.Context) {
var req utils.SendRequest
if err := ctx.ShouldBind(&req); err != nil {
r.FailWithMessage("参数错误: "+err.Error(), ctx)
return
}
//app-id: wxaaf66dbb5c3983b3
//app-secret: 0abba24dbff43febba1e551651f693b4
//template-id: PgxoZOOSDgBcmIGd_EVLDnYUmL3eu6NQTAZCsHQeuWY
sdk := weapp.NewClient("wxaaf66dbb5c3983b3", "0abba24dbff43febba1e551651f693b4")
msgData := msg.SendRequest{
ToUser: "o9Fq_6_cYKvOWnyUM3McC11hWsTI",
TemplateID: "PgxoZOOSDgBcmIGd_EVLDnYUmL3eu6NQTAZCsHQeuWY",
Page: "page/index/todo",
MiniprogramState: msg.MiniprogramStateTrial,
Data: msg.SendData{
"thing1": msg.SendValue{Value: "眼药水"},
"time2": msg.SendValue{Value: "20:00"},
"short_thing17": msg.SendValue{Value: "一天4次"},
"time15": msg.SendValue{Value: "2024-03-20 20:00"},
},
}
send, err := sdk.NewSubscribeMessage().Send(&msgData)
if err != nil {
return
}
err = send.GetResponseError()
if err != nil {
fmt.Printf("微信返回错误: %#v", err)
return
}
fmt.Printf("返回结果: %#v", send)
r.Ok(ctx)
}

56
api/v1/app/vision.go Normal file
View File

@ -0,0 +1,56 @@
package app
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/app"
"miniapp/model/app/request"
r "miniapp/model/common/response"
)
type VisionApi struct{}
func (VisionApi) GetList(ctx *gin.Context) {
var p request.VisionListRequest
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage("参数错误:"+err.Error(), ctx)
global.GVA_LOG.Error("参数错误", zap.Error(err))
return
}
// 获取列表
list, total, err := visionService.GetVisionList(p)
if err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("获取列表失败", zap.Error(err))
return
}
r.OkWithData(r.PageResult{
List: list,
Total: total,
Page: p.Page,
PageSize: p.PageSize,
}, ctx)
}
func (VisionApi) Create(ctx *gin.Context) {
var p app.Vision
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("参数错误", zap.Error(err))
return
}
// 创建
err := visionService.CreateVision(&p)
if err != nil {
r.FailWithMessage(err.Error(), ctx)
global.GVA_LOG.Error("创建失败", zap.Error(err))
return
}
r.Ok(ctx)
}

15
api/v1/enter.go Normal file
View File

@ -0,0 +1,15 @@
package v1
import (
"miniapp/api/v1/app"
"miniapp/api/v1/example"
"miniapp/api/v1/system"
)
type ApiGroup struct {
SystemApiGroup system.ApiGroup
ExampleApiGroup example.ApiGroup
AppApiGroup app.ApiGroup
}
var ApiGroupApp = new(ApiGroup)

13
api/v1/example/enter.go Normal file
View File

@ -0,0 +1,13 @@
package example
import "miniapp/service"
type ApiGroup struct {
CustomerApi
FileUploadAndDownloadApi
}
var (
customerService = service.ServiceGroupApp.ExampleServiceGroup.CustomerService
fileUploadAndDownloadService = service.ServiceGroupApp.ExampleServiceGroup.FileUploadAndDownloadService
)

View File

@ -0,0 +1,150 @@
package example
import (
"fmt"
"io"
"mime/multipart"
"strconv"
"miniapp/model/example"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/response"
exampleRes "miniapp/model/example/response"
"miniapp/utils"
)
// BreakpointContinue
// @Tags ExaFileUploadAndDownload
// @Summary 断点续传到服务器
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "an example for breakpoint resume, 断点续传示例"
// @Success 200 {object} response.Response{msg=string} "断点续传到服务器"
// @Router /fileUploadAndDownload/breakpointContinue [post]
func (b *FileUploadAndDownloadApi) BreakpointContinue(c *gin.Context) {
fileMd5 := c.Request.FormValue("fileMd5")
fileName := c.Request.FormValue("fileName")
chunkMd5 := c.Request.FormValue("chunkMd5")
chunkNumber, _ := strconv.Atoi(c.Request.FormValue("chunkNumber"))
chunkTotal, _ := strconv.Atoi(c.Request.FormValue("chunkTotal"))
_, FileHeader, err := c.Request.FormFile("file")
if err != nil {
global.GVA_LOG.Error("接收文件失败!", zap.Error(err))
response.FailWithMessage("接收文件失败", c)
return
}
f, err := FileHeader.Open()
if err != nil {
global.GVA_LOG.Error("文件读取失败!", zap.Error(err))
response.FailWithMessage("文件读取失败", c)
return
}
defer func(f multipart.File) {
err := f.Close()
if err != nil {
fmt.Println(err)
}
}(f)
cen, _ := io.ReadAll(f)
if !utils.CheckMd5(cen, chunkMd5) {
global.GVA_LOG.Error("检查md5失败!", zap.Error(err))
response.FailWithMessage("检查md5失败", c)
return
}
file, err := fileUploadAndDownloadService.FindOrCreateFile(fileMd5, fileName, chunkTotal)
if err != nil {
global.GVA_LOG.Error("查找或创建记录失败!", zap.Error(err))
response.FailWithMessage("查找或创建记录失败", c)
return
}
pathC, err := utils.BreakPointContinue(cen, fileName, chunkNumber, chunkTotal, fileMd5)
if err != nil {
global.GVA_LOG.Error("断点续传失败!", zap.Error(err))
response.FailWithMessage("断点续传失败", c)
return
}
if err = fileUploadAndDownloadService.CreateFileChunk(file.ID, pathC, chunkNumber); err != nil {
global.GVA_LOG.Error("创建文件记录失败!", zap.Error(err))
response.FailWithMessage("创建文件记录失败", c)
return
}
response.OkWithMessage("切片创建成功", c)
}
// FindFile
// @Tags ExaFileUploadAndDownload
// @Summary 查找文件
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "Find the file, 查找文件"
// @Success 200 {object} response.Response{data=exampleRes.FileResponse,msg=string} "查找文件,返回包括文件详情"
// @Router /fileUploadAndDownload/findFile [post]
func (b *FileUploadAndDownloadApi) FindFile(c *gin.Context) {
fileMd5 := c.Query("fileMd5")
fileName := c.Query("fileName")
chunkTotal, _ := strconv.Atoi(c.Query("chunkTotal"))
file, err := fileUploadAndDownloadService.FindOrCreateFile(fileMd5, fileName, chunkTotal)
if err != nil {
global.GVA_LOG.Error("查找失败!", zap.Error(err))
response.FailWithMessage("查找失败", c)
} else {
response.OkWithDetailed(exampleRes.FileResponse{File: file}, "查找成功", c)
}
}
// BreakpointContinueFinish
// @Tags ExaFileUploadAndDownload
// @Summary 创建文件
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "上传文件完成"
// @Success 200 {object} response.Response{data=exampleRes.FilePathResponse,msg=string} "创建文件,返回包括文件路径"
// @Router /fileUploadAndDownload/findFile [post]
func (b *FileUploadAndDownloadApi) BreakpointContinueFinish(c *gin.Context) {
fileMd5 := c.Query("fileMd5")
fileName := c.Query("fileName")
filePath, err := utils.MakeFile(fileName, fileMd5)
if err != nil {
global.GVA_LOG.Error("文件创建失败!", zap.Error(err))
response.FailWithDetailed(exampleRes.FilePathResponse{FilePath: filePath}, "文件创建失败", c)
} else {
response.OkWithDetailed(exampleRes.FilePathResponse{FilePath: filePath}, "文件创建成功", c)
}
}
// RemoveChunk
// @Tags ExaFileUploadAndDownload
// @Summary 删除切片
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "删除缓存切片"
// @Success 200 {object} response.Response{msg=string} "删除切片"
// @Router /fileUploadAndDownload/removeChunk [post]
func (b *FileUploadAndDownloadApi) RemoveChunk(c *gin.Context) {
var file example.ExaFile
err := c.ShouldBindJSON(&file)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.RemoveChunk(file.FileMd5)
if err != nil {
global.GVA_LOG.Error("缓存切片删除失败!", zap.Error(err))
return
}
err = fileUploadAndDownloadService.DeleteFileChunk(file.FileMd5, file.FilePath)
if err != nil {
global.GVA_LOG.Error(err.Error(), zap.Error(err))
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithMessage("缓存切片删除成功", c)
}

View File

@ -0,0 +1,176 @@
package example
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/request"
"miniapp/model/common/response"
"miniapp/model/example"
exampleRes "miniapp/model/example/response"
"miniapp/utils"
)
type CustomerApi struct{}
// CreateExaCustomer
// @Tags ExaCustomer
// @Summary 创建客户
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body example.ExaCustomer true "客户用户名, 客户手机号码"
// @Success 200 {object} response.Response{msg=string} "创建客户"
// @Router /customer/customer [post]
func (e *CustomerApi) CreateExaCustomer(c *gin.Context) {
var customer example.ExaCustomer
err := c.ShouldBindJSON(&customer)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(customer, utils.CustomerVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
customer.SysUserID = utils.GetUserID(c)
customer.SysUserAuthorityID = utils.GetUserAuthorityId(c)
err = customerService.CreateExaCustomer(customer)
if err != nil {
global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
return
}
response.OkWithMessage("创建成功", c)
}
// DeleteExaCustomer
// @Tags ExaCustomer
// @Summary 删除客户
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body example.ExaCustomer true "客户ID"
// @Success 200 {object} response.Response{msg=string} "删除客户"
// @Router /customer/customer [delete]
func (e *CustomerApi) DeleteExaCustomer(c *gin.Context) {
var customer example.ExaCustomer
err := c.ShouldBindJSON(&customer)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(customer.GVA_MODEL, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = customerService.DeleteExaCustomer(customer)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// UpdateExaCustomer
// @Tags ExaCustomer
// @Summary 更新客户信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body example.ExaCustomer true "客户ID, 客户信息"
// @Success 200 {object} response.Response{msg=string} "更新客户信息"
// @Router /customer/customer [put]
func (e *CustomerApi) UpdateExaCustomer(c *gin.Context) {
var customer example.ExaCustomer
err := c.ShouldBindJSON(&customer)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(customer.GVA_MODEL, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(customer, utils.CustomerVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = customerService.UpdateExaCustomer(&customer)
if err != nil {
global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
return
}
response.OkWithMessage("更新成功", c)
}
// GetExaCustomer
// @Tags ExaCustomer
// @Summary 获取单一客户信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query example.ExaCustomer true "客户ID"
// @Success 200 {object} response.Response{data=exampleRes.ExaCustomerResponse,msg=string} "获取单一客户信息,返回包括客户详情"
// @Router /customer/customer [get]
func (e *CustomerApi) GetExaCustomer(c *gin.Context) {
var customer example.ExaCustomer
err := c.ShouldBindQuery(&customer)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(customer.GVA_MODEL, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
data, err := customerService.GetExaCustomer(customer.ID)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(exampleRes.ExaCustomerResponse{Customer: data}, "获取成功", c)
}
// GetExaCustomerList
// @Tags ExaCustomer
// @Summary 分页获取权限客户列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.PageInfo true "页码, 每页大小"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取权限客户列表,返回包括列表,总数,页码,每页数量"
// @Router /customer/customerList [get]
func (e *CustomerApi) GetExaCustomerList(c *gin.Context) {
var pageInfo request.PageInfo
err := c.ShouldBindQuery(&pageInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(pageInfo, utils.PageInfoVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
customerList, total, err := customerService.GetCustomerInfoList(utils.GetUserAuthorityId(c), pageInfo)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败"+err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: customerList,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}

View File

@ -0,0 +1,110 @@
package example
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/request"
"miniapp/model/common/response"
"miniapp/model/example"
exampleRes "miniapp/model/example/response"
)
type FileUploadAndDownloadApi struct{}
// UploadFile
// @Tags ExaFileUploadAndDownload
// @Summary 上传文件示例
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "上传文件示例"
// @Success 200 {object} response.Response{data=exampleRes.ExaFileResponse,msg=string} "上传文件示例,返回包括文件详情"
// @Router /fileUploadAndDownload/upload [post]
func (b *FileUploadAndDownloadApi) UploadFile(c *gin.Context) {
var file example.ExaFileUploadAndDownload
noSave := c.DefaultQuery("noSave", "0")
_, header, err := c.Request.FormFile("file")
if err != nil {
global.GVA_LOG.Error("接收文件失败!", zap.Error(err))
response.FailWithMessage("接收文件失败", c)
return
}
file, err = fileUploadAndDownloadService.UploadFile(header, noSave) // 文件上传后拿到文件路径
if err != nil {
global.GVA_LOG.Error("修改数据库链接失败!", zap.Error(err))
response.FailWithMessage("修改数据库链接失败", c)
return
}
response.OkWithDetailed(exampleRes.ExaFileResponse{File: file}, "上传成功", c)
}
// EditFileName 编辑文件名或者备注
func (b *FileUploadAndDownloadApi) EditFileName(c *gin.Context) {
var file example.ExaFileUploadAndDownload
err := c.ShouldBindJSON(&file)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = fileUploadAndDownloadService.EditFileName(file)
if err != nil {
global.GVA_LOG.Error("编辑失败!", zap.Error(err))
response.FailWithMessage("编辑失败", c)
return
}
response.OkWithMessage("编辑成功", c)
}
// DeleteFile
// @Tags ExaFileUploadAndDownload
// @Summary 删除文件
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body example.ExaFileUploadAndDownload true "传入文件里面id即可"
// @Success 200 {object} response.Response{msg=string} "删除文件"
// @Router /fileUploadAndDownload/deleteFile [post]
func (b *FileUploadAndDownloadApi) DeleteFile(c *gin.Context) {
var file example.ExaFileUploadAndDownload
err := c.ShouldBindJSON(&file)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := fileUploadAndDownloadService.DeleteFile(file); err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// GetFileList
// @Tags ExaFileUploadAndDownload
// @Summary 分页文件列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.PageInfo true "页码, 每页大小"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页文件列表,返回包括列表,总数,页码,每页数量"
// @Router /fileUploadAndDownload/getFileList [post]
func (b *FileUploadAndDownloadApi) GetFileList(c *gin.Context) {
var pageInfo request.PageInfo
err := c.ShouldBindJSON(&pageInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
list, total, err := fileUploadAndDownloadService.GetFileRecordInfoList(pageInfo)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}

113
api/v1/system/article.go Normal file
View File

@ -0,0 +1,113 @@
package system
import (
"github.com/gin-gonic/gin"
"miniapp/api"
"miniapp/global"
"miniapp/model/app"
"miniapp/model/common"
"miniapp/model/common/request"
r "miniapp/model/common/response"
"strconv"
)
type ArticleApi struct{}
// GetArticleList 获取文章列表
func (a ArticleApi) GetArticleList(ctx *gin.Context) {
var p request.PageInfo
if err := ctx.ShouldBind(&p); err != nil {
global.GVA_LOG.Error("参数错误" + err.Error())
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
list, total, err := articleService.GetArticleList(p)
if err != nil {
global.GVA_LOG.Error("获取文章列表失败" + err.Error())
r.FailWithMessage("获取文章列表失败", ctx)
return
}
r.OkWithDetailed(r.PageResult{List: list, Total: total, Page: p.Page, PageSize: p.PageSize}, "获取成功", ctx)
}
// CreateArticle 创建文章
func (a ArticleApi) CreateArticle(ctx *gin.Context) {
var article common.Article
if err := ctx.ShouldBindJSON(&article); err != nil {
global.GVA_LOG.Error("参数错误" + err.Error())
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := articleService.CreateArticle(&article)
if err != nil {
global.GVA_LOG.Error("创建失败" + err.Error())
r.FailWithMessage("创建失败"+err.Error(), ctx)
return
}
r.OkWithMessage("创建成功", ctx)
}
// UpdateArticle 更新文章
func (a ArticleApi) UpdateArticle(ctx *gin.Context) {
var article common.Article
if err := ctx.ShouldBindJSON(&article); err != nil {
global.GVA_LOG.Error("参数错误" + err.Error())
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := articleService.UpdateArticle(&article)
if err != nil {
global.GVA_LOG.Error("更新失败" + err.Error())
r.FailWithMessage("更新失败"+err.Error(), ctx)
return
}
r.OkWithMessage("更新成功", ctx)
}
// DeleteArticle 删除文章
func (a ArticleApi) DeleteArticle(ctx *gin.Context) {
var article common.Article
if err := ctx.ShouldBind(&article); err != nil {
global.GVA_LOG.Error("参数错误" + err.Error())
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := articleService.DeleteArticle(&article)
if err != nil {
global.GVA_LOG.Error("删除失败" + err.Error())
r.FailWithMessage("删除失败"+err.Error(), ctx)
return
}
r.OkWithMessage("删除成功", ctx)
}
// GetArticleById 根据id获取文章
func (a ArticleApi) GetArticleById(ctx *gin.Context) {
Id := ctx.Param("id")
if Id == "" {
global.GVA_LOG.Error("参数错误")
r.FailWithMessage("参数错误", ctx)
return
}
// 获取用户信息
var user app.User
api.GetUser(ctx, &user, false, true)
article, err := articleService.GetArticleById(Id, strconv.Itoa(int(user.ID)))
if err != nil {
global.GVA_LOG.Error("获取失败" + err.Error())
r.FailWithMessage("获取失败"+err.Error(), ctx)
return
}
r.OkWithDetailed(article, "获取成功", ctx)
}

127
api/v1/system/banner.go Normal file
View File

@ -0,0 +1,127 @@
package system
import (
"github.com/gin-gonic/gin"
"miniapp/global"
"miniapp/model/common"
"miniapp/model/common/request"
r "miniapp/model/common/response"
)
type BannerApi struct {
}
// GetBannerList 获取轮播图列表
func (b *BannerApi) GetBannerList(ctx *gin.Context) {
var p request.PageInfo
if err := ctx.ShouldBind(&p); err != nil {
global.GVA_LOG.Error("参数错误" + err.Error())
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
list, total, err := bannerService.GetBannerList(p)
if err != nil {
global.GVA_LOG.Error("获取轮播图列表失败" + err.Error())
r.FailWithMessage("获取轮播图列表失败", ctx)
return
}
r.OkWithDetailed(r.PageResult{List: list, Total: total, Page: p.Page, PageSize: p.PageSize}, "获取成功", ctx)
}
// CreateBanner 创建轮播图
func (b *BannerApi) CreateBanner(ctx *gin.Context) {
var banner common.Banner
if err := ctx.ShouldBindJSON(&banner); err != nil {
global.GVA_LOG.Error("参数错误" + err.Error())
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := bannerService.CreateBanner(&banner)
if err != nil {
global.GVA_LOG.Error("创建失败" + err.Error())
r.FailWithMessage("创建失败"+err.Error(), ctx)
return
}
r.OkWithMessage("创建成功", ctx)
}
// UpdateBanner 更新轮播图
func (b *BannerApi) UpdateBanner(ctx *gin.Context) {
var banner common.Banner
if err := ctx.ShouldBindJSON(&banner); err != nil {
global.GVA_LOG.Error("参数错误" + err.Error())
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := bannerService.UpdateBanner(&banner)
if err != nil {
global.GVA_LOG.Error("更新失败" + err.Error())
r.FailWithMessage("更新失败"+err.Error(), ctx)
return
}
r.OkWithMessage("更新成功", ctx)
}
// DeleteBanner 删除轮播图
func (b *BannerApi) DeleteBanner(ctx *gin.Context) {
var banner common.Banner
if err := ctx.ShouldBind(&banner); err != nil {
global.GVA_LOG.Error("参数错误" + err.Error())
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := bannerService.DeleteBanner(&banner)
if err != nil {
global.GVA_LOG.Error("删除失败" + err.Error())
r.FailWithMessage("删除失败"+err.Error(), ctx)
return
}
r.OkWithMessage("删除成功", ctx)
}
// GetBannerById 根据id获取轮播图
func (b *BannerApi) GetBannerById(ctx *gin.Context) {
Id := ctx.Param("id")
if Id == "" {
global.GVA_LOG.Error("参数错误")
r.FailWithMessage("参数错误", ctx)
return
}
banner, err := bannerService.GetBannerById(Id)
if err != nil {
global.GVA_LOG.Error("获取失败" + err.Error())
r.FailWithMessage("获取失败"+err.Error(), ctx)
return
}
r.OkWithDetailed(banner, "获取成功", ctx)
}
// UpdateBannerStatus 更新轮播图状态
func (b *BannerApi) UpdateBannerStatus(ctx *gin.Context) {
var banner common.Banner
if err := ctx.ShouldBindJSON(&banner); err != nil {
global.GVA_LOG.Error("参数错误" + err.Error())
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := bannerService.UpdateBannerStatus(&banner)
if err != nil {
global.GVA_LOG.Error("更新失败" + err.Error())
r.FailWithMessage("更新失败"+err.Error(), ctx)
return
}
r.OkWithMessage("更新成功", ctx)
}

50
api/v1/system/enter.go Normal file
View File

@ -0,0 +1,50 @@
package system
import "miniapp/service"
type ApiGroup struct {
DBApi
JwtApi
BaseApi
SystemApi
CasbinApi
AutoCodeApi
SystemApiApi
AuthorityApi
DictionaryApi
AuthorityMenuApi
OperationRecordApi
AutoCodeHistoryApi
DictionaryDetailApi
AuthorityBtnApi
ChatGptApi
BannerApi
HospitalApi
ArticleApi
AiKefulApi
PosterApi
}
var (
apiService = service.ServiceGroupApp.SystemServiceGroup.ApiService
jwtService = service.ServiceGroupApp.SystemServiceGroup.JwtService
menuService = service.ServiceGroupApp.SystemServiceGroup.MenuService
userService = service.ServiceGroupApp.SystemServiceGroup.UserService
initDBService = service.ServiceGroupApp.SystemServiceGroup.InitDBService
casbinService = service.ServiceGroupApp.SystemServiceGroup.CasbinService
autoCodeService = service.ServiceGroupApp.SystemServiceGroup.AutoCodeService
baseMenuService = service.ServiceGroupApp.SystemServiceGroup.BaseMenuService
authorityService = service.ServiceGroupApp.SystemServiceGroup.AuthorityService
dictionaryService = service.ServiceGroupApp.SystemServiceGroup.DictionaryService
systemConfigService = service.ServiceGroupApp.SystemServiceGroup.SystemConfigService
operationRecordService = service.ServiceGroupApp.SystemServiceGroup.OperationRecordService
autoCodeHistoryService = service.ServiceGroupApp.SystemServiceGroup.AutoCodeHistoryService
dictionaryDetailService = service.ServiceGroupApp.SystemServiceGroup.DictionaryDetailService
authorityBtnService = service.ServiceGroupApp.SystemServiceGroup.AuthorityBtnService
chatGptService = service.ServiceGroupApp.SystemServiceGroup.ChatGptService
hospitalService = service.ServiceGroupApp.SystemServiceGroup.HospitalService
bannerService = service.ServiceGroupApp.SystemServiceGroup.BannerService
articleService = service.ServiceGroupApp.SystemServiceGroup.ArticleService
aiKefuService = service.ServiceGroupApp.SystemServiceGroup.AiKefuService
posterService = service.ServiceGroupApp.SystemServiceGroup.PosterService
)

121
api/v1/system/hospital.go Normal file
View File

@ -0,0 +1,121 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common"
"miniapp/model/common/request"
r "miniapp/model/common/response"
"strconv"
)
type HospitalApi struct {
}
// GetHospitalList 获取医院列表
func (h HospitalApi) GetHospitalList(ctx *gin.Context) {
var p request.PageInfo
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
list, total, err := hospitalService.GetHospitalList(p)
if err != nil {
r.FailWithMessage("获取医院列表失败", ctx)
return
}
r.OkWithDetailed(r.PageResult{List: list, Total: total, Page: p.Page, PageSize: p.PageSize}, "获取成功", ctx)
}
// CreateHospital 创建医院
func (h HospitalApi) CreateHospital(ctx *gin.Context) {
var hospital common.Hospital
if err := ctx.ShouldBindJSON(&hospital); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := hospitalService.CreateHospital(&hospital)
if err != nil {
r.FailWithMessage("创建失败"+err.Error(), ctx)
return
}
r.OkWithMessage("创建成功", ctx)
}
// UpdateHospital 更新医院
func (h HospitalApi) UpdateHospital(ctx *gin.Context) {
var hospital common.Hospital
if err := ctx.ShouldBindJSON(&hospital); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := hospitalService.UpdateHospital(&hospital)
if err != nil {
r.FailWithMessage("更新失败"+err.Error(), ctx)
return
}
r.OkWithMessage("更新成功", ctx)
}
// DeleteHospital 删除医院
func (h HospitalApi) DeleteHospital(ctx *gin.Context) {
var hospital common.Hospital
if err := ctx.ShouldBind(&hospital); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := hospitalService.DeleteHospital(&hospital)
if err != nil {
r.FailWithMessage("删除失败"+err.Error(), ctx)
return
}
r.OkWithMessage("删除成功", ctx)
}
// GetHospitalById 根据id获取医院
func (h HospitalApi) GetHospitalById(ctx *gin.Context) {
Id := ctx.Param("id")
if Id == "" {
r.FailWithMessage("参数错误", ctx)
return
}
// 参数转换 string -> int
id, _ := strconv.Atoi(Id)
hospitalResult, err := hospitalService.GetHospitalById(uint(id))
if err != nil {
r.FailWithMessage("获取失败"+err.Error(), ctx)
return
}
r.OkWithDetailed(hospitalResult, "获取成功", ctx)
}
// GetHospitalNotes 根据id获取医院注意事项
func (h HospitalApi) GetHospitalNotes(ctx *gin.Context) {
p := request.GetHospitalNotes{}
if err := ctx.ShouldBind(&p); err != nil {
global.GVA_LOG.Error("参数错误", zap.Error(err))
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
notes, err := hospitalService.GetHospitalNotes(p)
if err != nil {
global.GVA_LOG.Error("获取医院注意事项失败", zap.Error(err))
r.FailWithMessage("获取医院注意事项失败"+err.Error(), ctx)
return
}
r.OkWithData(notes, ctx)
}

114
api/v1/system/poster.go Normal file
View File

@ -0,0 +1,114 @@
package system
import (
"github.com/gin-gonic/gin"
"miniapp/model/common"
"miniapp/model/common/request"
r "miniapp/model/common/response"
)
type PosterApi struct {
}
// GetPosterList 获取海报列表
func (p PosterApi) GetPosterList(ctx *gin.Context) {
var page request.PageInfo
if err := ctx.ShouldBind(&p); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
list, total, err := posterService.GetPosterList(page)
if err != nil {
r.FailWithMessage("获取海报列表失败", ctx)
return
}
r.OkWithDetailed(r.PageResult{List: list, Total: total, Page: page.Page, PageSize: page.PageSize}, "获取成功", ctx)
}
// CreatePoster 创建海报
func (p PosterApi) CreatePoster(ctx *gin.Context) {
var poster common.Poster
if err := ctx.ShouldBindJSON(&poster); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := posterService.AddPoster(&poster)
if err != nil {
r.FailWithMessage("创建失败"+err.Error(), ctx)
return
}
r.OkWithMessage("创建成功", ctx)
}
// UpdatePoster 更新海报
func (p PosterApi) UpdatePoster(ctx *gin.Context) {
var poster common.Poster
if err := ctx.ShouldBindJSON(&poster); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := posterService.UpdatePoster(&poster)
if err != nil {
r.FailWithMessage("更新失败"+err.Error(), ctx)
return
}
r.OkWithMessage("更新成功", ctx)
}
// DeletePoster 删除海报
func (p PosterApi) DeletePoster(ctx *gin.Context) {
var poster common.Poster
if err := ctx.ShouldBind(&poster); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := posterService.DeletePoster(&poster)
if err != nil {
r.FailWithMessage("删除失败"+err.Error(), ctx)
return
}
r.OkWithMessage("删除成功", ctx)
}
// GetPosterById 根据id获取海报
func (p PosterApi) GetPosterById(ctx *gin.Context) {
id := ctx.Param("id")
if id == "" {
r.FailWithMessage("参数错误", ctx)
return
}
poster, err := posterService.GetPosterById(id)
if err != nil {
r.FailWithMessage("获取失败"+err.Error(), ctx)
return
}
r.OkWithDetailed(poster, "获取成功", ctx)
}
// UpdatePosterSort 更新海报排序
func (p PosterApi) UpdatePosterSort(ctx *gin.Context) {
var poster common.Poster
if err := ctx.ShouldBind(&poster); err != nil {
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := posterService.UpdatePoster(&poster)
if err != nil {
r.FailWithMessage("更新失败"+err.Error(), ctx)
return
}
r.OkWithMessage("更新成功", ctx)
}

View File

@ -0,0 +1,108 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/request"
r "miniapp/model/common/response"
"miniapp/model/system"
)
type AiKefulApi struct {
}
// GetAiKefuList 获取列表
func (a *AiKefulApi) GetAiKefuList(ctx *gin.Context) {
p := request.PageInfo{}
if err := ctx.ShouldBind(&p); err != nil {
global.GVA_LOG.Error("参数错误", zap.Error(err))
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
list, total, err := aiKefuService.GetAiKefuList(p)
if err != nil {
global.GVA_LOG.Error("获取列表失败", zap.Error(err))
r.FailWithMessage("获取列表失败", ctx)
return
}
r.OkWithDetailed(r.PageResult{List: list, Total: total, Page: p.Page, PageSize: p.PageSize}, "获取成功", ctx)
}
// CreateAiKefu 创建
func (a *AiKefulApi) CreateAiKefu(ctx *gin.Context) {
var aiKefu system.Aikefu
if err := ctx.ShouldBind(&aiKefu); err != nil {
global.GVA_LOG.Error("参数错误", zap.Error(err))
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := aiKefuService.CreateAiKefu(&aiKefu)
if err != nil {
global.GVA_LOG.Error("创建失败", zap.Error(err))
r.FailWithMessage("创建失败"+err.Error(), ctx)
return
}
r.OkWithMessage("创建成功", ctx)
}
// UpdateAiKefu 更新
func (a *AiKefulApi) UpdateAiKefu(ctx *gin.Context) {
var aiKefu system.Aikefu
if err := ctx.ShouldBind(&aiKefu); err != nil {
global.GVA_LOG.Error("参数错误", zap.Error(err))
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := aiKefuService.UpdateAiKefu(&aiKefu)
if err != nil {
global.GVA_LOG.Error("更新失败", zap.Error(err))
r.FailWithMessage("更新失败"+err.Error(), ctx)
return
}
r.OkWithMessage("更新成功", ctx)
}
// DeleteAiKefu 删除
func (a *AiKefulApi) DeleteAiKefu(ctx *gin.Context) {
var aiKefu system.Aikefu
if err := ctx.ShouldBind(&aiKefu); err != nil {
global.GVA_LOG.Error("参数错误", zap.Error(err))
r.FailWithMessage("参数错误"+err.Error(), ctx)
return
}
err := aiKefuService.DeleteAiKefu(&aiKefu)
if err != nil {
global.GVA_LOG.Error("删除失败", zap.Error(err))
r.FailWithMessage("删除失败"+err.Error(), ctx)
return
}
r.OkWithMessage("删除成功", ctx)
}
// GetAiKefuById 根据id获取
func (a *AiKefulApi) GetAiKefuById(ctx *gin.Context) {
Id := ctx.Param("id")
if Id == "" {
global.GVA_LOG.Error("参数错误")
r.FailWithMessage("参数错误", ctx)
return
}
aiKefu, err := aiKefuService.GetAiKefuById(Id)
if err != nil {
global.GVA_LOG.Error("获取失败", zap.Error(err))
r.FailWithMessage("获取失败"+err.Error(), ctx)
return
}
r.OkWithData(aiKefu, ctx)
}

231
api/v1/system/sys_api.go Normal file
View File

@ -0,0 +1,231 @@
package system
import (
"miniapp/global"
"miniapp/model/common/request"
"miniapp/model/common/response"
"miniapp/model/system"
systemReq "miniapp/model/system/request"
systemRes "miniapp/model/system/response"
"miniapp/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
type SystemApiApi struct{}
// CreateApi
// @Tags SysApi
// @Summary 创建基础api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysApi true "api路径, api中文描述, api组, 方法"
// @Success 200 {object} response.Response{msg=string} "创建基础api"
// @Router /api/createApi [post]
func (s *SystemApiApi) CreateApi(c *gin.Context) {
var api system.SysApi
err := c.ShouldBindJSON(&api)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(api, utils.ApiVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = apiService.CreateApi(api)
if err != nil {
global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
return
}
response.OkWithMessage("创建成功", c)
}
// DeleteApi
// @Tags SysApi
// @Summary 删除api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysApi true "ID"
// @Success 200 {object} response.Response{msg=string} "删除api"
// @Router /api/deleteApi [post]
func (s *SystemApiApi) DeleteApi(c *gin.Context) {
var api system.SysApi
err := c.ShouldBindJSON(&api)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(api.GVA_MODEL, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = apiService.DeleteApi(api)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// GetApiList
// @Tags SysApi
// @Summary 分页获取API列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body systemReq.SearchApiParams true "分页获取API列表"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取API列表,返回包括列表,总数,页码,每页数量"
// @Router /api/getApiList [post]
func (s *SystemApiApi) GetApiList(c *gin.Context) {
var pageInfo systemReq.SearchApiParams
err := c.ShouldBindJSON(&pageInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
list, total, err := apiService.GetAPIInfoList(pageInfo.SysApi, pageInfo.PageInfo, pageInfo.OrderKey, pageInfo.Desc)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
// GetApiById
// @Tags SysApi
// @Summary 根据id获取api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "根据id获取api"
// @Success 200 {object} response.Response{data=systemRes.SysAPIResponse} "根据id获取api,返回包括api详情"
// @Router /api/getApiById [post]
func (s *SystemApiApi) GetApiById(c *gin.Context) {
var idInfo request.GetById
err := c.ShouldBindJSON(&idInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(idInfo, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
api, err := apiService.GetApiById(idInfo.ID)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(systemRes.SysAPIResponse{Api: api}, "获取成功", c)
}
// UpdateApi
// @Tags SysApi
// @Summary 修改基础api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysApi true "api路径, api中文描述, api组, 方法"
// @Success 200 {object} response.Response{msg=string} "修改基础api"
// @Router /api/updateApi [post]
func (s *SystemApiApi) UpdateApi(c *gin.Context) {
var api system.SysApi
err := c.ShouldBindJSON(&api)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(api, utils.ApiVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = apiService.UpdateApi(api)
if err != nil {
global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage("修改失败", c)
return
}
response.OkWithMessage("修改成功", c)
}
// GetAllApis
// @Tags SysApi
// @Summary 获取所有的Api 不分页
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=systemRes.SysAPIListResponse,msg=string} "获取所有的Api 不分页,返回包括api列表"
// @Router /api/getAllApis [post]
func (s *SystemApiApi) GetAllApis(c *gin.Context) {
apis, err := apiService.GetAllApis()
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(systemRes.SysAPIListResponse{Apis: apis}, "获取成功", c)
}
// DeleteApisByIds
// @Tags SysApi
// @Summary 删除选中Api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "ID"
// @Success 200 {object} response.Response{msg=string} "删除选中Api"
// @Router /api/deleteApisByIds [delete]
func (s *SystemApiApi) DeleteApisByIds(c *gin.Context) {
var ids request.IdsReq
err := c.ShouldBindJSON(&ids)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = apiService.DeleteApisByIds(ids)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// FreshCasbin
// @Tags SysApi
// @Summary 刷新casbin缓存
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "刷新成功"
// @Router /api/freshCasbin [get]
func (s *SystemApiApi) FreshCasbin(c *gin.Context) {
err := apiService.FreshCasbin()
if err != nil {
global.GVA_LOG.Error("刷新失败!", zap.Error(err))
response.FailWithMessage("刷新失败", c)
return
}
response.OkWithMessage("刷新成功", c)
}

View File

@ -0,0 +1,208 @@
package system
import (
"miniapp/global"
"miniapp/model/common/request"
"miniapp/model/common/response"
"miniapp/model/system"
systemReq "miniapp/model/system/request"
systemRes "miniapp/model/system/response"
"miniapp/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
type AuthorityApi struct{}
// CreateAuthority
// @Tags Authority
// @Summary 创建角色
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysAuthority true "权限id, 权限名, 父角色id"
// @Success 200 {object} response.Response{data=systemRes.SysAuthorityResponse,msg=string} "创建角色,返回包括系统角色详情"
// @Router /authority/createAuthority [post]
func (a *AuthorityApi) CreateAuthority(c *gin.Context) {
var authority system.SysAuthority
err := c.ShouldBindJSON(&authority)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(authority, utils.AuthorityVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if authBack, err := authorityService.CreateAuthority(authority); err != nil {
global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败"+err.Error(), c)
} else {
_ = menuService.AddMenuAuthority(systemReq.DefaultMenu(), authority.AuthorityId)
_ = casbinService.UpdateCasbin(authority.AuthorityId, systemReq.DefaultCasbin())
response.OkWithDetailed(systemRes.SysAuthorityResponse{Authority: authBack}, "创建成功", c)
}
}
// CopyAuthority
// @Tags Authority
// @Summary 拷贝角色
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body response.SysAuthorityCopyResponse true "旧角色id, 新权限id, 新权限名, 新父角色id"
// @Success 200 {object} response.Response{data=systemRes.SysAuthorityResponse,msg=string} "拷贝角色,返回包括系统角色详情"
// @Router /authority/copyAuthority [post]
func (a *AuthorityApi) CopyAuthority(c *gin.Context) {
var copyInfo systemRes.SysAuthorityCopyResponse
err := c.ShouldBindJSON(&copyInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(copyInfo, utils.OldAuthorityVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(copyInfo.Authority, utils.AuthorityVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
authBack, err := authorityService.CopyAuthority(copyInfo)
if err != nil {
global.GVA_LOG.Error("拷贝失败!", zap.Error(err))
response.FailWithMessage("拷贝失败"+err.Error(), c)
return
}
response.OkWithDetailed(systemRes.SysAuthorityResponse{Authority: authBack}, "拷贝成功", c)
}
// DeleteAuthority
// @Tags Authority
// @Summary 删除角色
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysAuthority true "删除角色"
// @Success 200 {object} response.Response{msg=string} "删除角色"
// @Router /authority/deleteAuthority [post]
func (a *AuthorityApi) DeleteAuthority(c *gin.Context) {
var authority system.SysAuthority
err := c.ShouldBindJSON(&authority)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(authority, utils.AuthorityIdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = authorityService.DeleteAuthority(&authority)
if err != nil { // 删除角色之前需要判断是否有用户正在使用此角色
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败"+err.Error(), c)
return
}
response.OkWithMessage("删除成功", c)
}
// UpdateAuthority
// @Tags Authority
// @Summary 更新角色信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysAuthority true "权限id, 权限名, 父角色id"
// @Success 200 {object} response.Response{data=systemRes.SysAuthorityResponse,msg=string} "更新角色信息,返回包括系统角色详情"
// @Router /authority/updateAuthority [post]
func (a *AuthorityApi) UpdateAuthority(c *gin.Context) {
var auth system.SysAuthority
err := c.ShouldBindJSON(&auth)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(auth, utils.AuthorityVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
authority, err := authorityService.UpdateAuthority(auth)
if err != nil {
global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败"+err.Error(), c)
return
}
response.OkWithDetailed(systemRes.SysAuthorityResponse{Authority: authority}, "更新成功", c)
}
// GetAuthorityList
// @Tags Authority
// @Summary 分页获取角色列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.PageInfo true "页码, 每页大小"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取角色列表,返回包括列表,总数,页码,每页数量"
// @Router /authority/getAuthorityList [post]
func (a *AuthorityApi) GetAuthorityList(c *gin.Context) {
var pageInfo request.PageInfo
err := c.ShouldBindJSON(&pageInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(pageInfo, utils.PageInfoVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
list, total, err := authorityService.GetAuthorityInfoList(pageInfo)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败"+err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
// SetDataAuthority
// @Tags Authority
// @Summary 设置角色资源权限
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysAuthority true "设置角色资源权限"
// @Success 200 {object} response.Response{msg=string} "设置角色资源权限"
// @Router /authority/setDataAuthority [post]
func (a *AuthorityApi) SetDataAuthority(c *gin.Context) {
var auth system.SysAuthority
err := c.ShouldBindJSON(&auth)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(auth, utils.AuthorityIdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = authorityService.SetDataAuthority(auth)
if err != nil {
global.GVA_LOG.Error("设置失败!", zap.Error(err))
response.FailWithMessage("设置失败"+err.Error(), c)
return
}
response.OkWithMessage("设置成功", c)
}

View File

@ -0,0 +1,80 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/response"
"miniapp/model/system/request"
)
type AuthorityBtnApi struct{}
// GetAuthorityBtn
// @Tags AuthorityBtn
// @Summary 获取权限按钮
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.SysAuthorityBtnReq true "菜单id, 角色id, 选中的按钮id"
// @Success 200 {object} response.Response{data=response.SysAuthorityBtnRes,msg=string} "返回列表成功"
// @Router /authorityBtn/getAuthorityBtn [post]
func (a *AuthorityBtnApi) GetAuthorityBtn(c *gin.Context) {
var req request.SysAuthorityBtnReq
err := c.ShouldBindJSON(&req)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
res, err := authorityBtnService.GetAuthorityBtn(req)
if err != nil {
global.GVA_LOG.Error("查询失败!", zap.Error(err))
response.FailWithMessage("查询失败", c)
return
}
response.OkWithDetailed(res, "查询成功", c)
}
// SetAuthorityBtn
// @Tags AuthorityBtn
// @Summary 设置权限按钮
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.SysAuthorityBtnReq true "菜单id, 角色id, 选中的按钮id"
// @Success 200 {object} response.Response{msg=string} "返回列表成功"
// @Router /authorityBtn/setAuthorityBtn [post]
func (a *AuthorityBtnApi) SetAuthorityBtn(c *gin.Context) {
var req request.SysAuthorityBtnReq
err := c.ShouldBindJSON(&req)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = authorityBtnService.SetAuthorityBtn(req)
if err != nil {
global.GVA_LOG.Error("分配失败!", zap.Error(err))
response.FailWithMessage("分配失败", c)
return
}
response.OkWithMessage("分配成功", c)
}
// CanRemoveAuthorityBtn
// @Tags AuthorityBtn
// @Summary 设置权限按钮
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "删除成功"
// @Router /authorityBtn/canRemoveAuthorityBtn [post]
func (a *AuthorityBtnApi) CanRemoveAuthorityBtn(c *gin.Context) {
id := c.Query("id")
err := authorityBtnService.CanRemoveAuthorityBtn(id)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithMessage("删除成功", c)
}

View File

@ -0,0 +1,315 @@
package system
import (
"errors"
"fmt"
"net/url"
"os"
"strings"
"miniapp/global"
"miniapp/model/common/response"
"miniapp/model/system"
"miniapp/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
type AutoCodeApi struct{}
// PreviewTemp
// @Tags AutoCode
// @Summary 预览创建后的代码
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.AutoCodeStruct true "预览创建代码"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "预览创建后的代码"
// @Router /autoCode/preview [post]
func (autoApi *AutoCodeApi) PreviewTemp(c *gin.Context) {
var a system.AutoCodeStruct
_ = c.ShouldBindJSON(&a)
if err := utils.Verify(a, utils.AutoCodeVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
a.Pretreatment() // 处理go关键字
a.PackageT = utils.FirstUpper(a.Package)
autoCode, err := autoCodeService.PreviewTemp(a)
if err != nil {
global.GVA_LOG.Error("预览失败!", zap.Error(err))
response.FailWithMessage("预览失败", c)
} else {
response.OkWithDetailed(gin.H{"autoCode": autoCode}, "预览成功", c)
}
}
// CreateTemp
// @Tags AutoCode
// @Summary 自动代码模板
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.AutoCodeStruct true "创建自动代码"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /autoCode/createTemp [post]
func (autoApi *AutoCodeApi) CreateTemp(c *gin.Context) {
var a system.AutoCodeStruct
_ = c.ShouldBindJSON(&a)
if err := utils.Verify(a, utils.AutoCodeVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
a.Pretreatment()
var apiIds []uint
if a.AutoCreateApiToSql {
if ids, err := autoCodeService.AutoCreateApi(&a); err != nil {
global.GVA_LOG.Error("自动化创建失败!请自行清空垃圾数据!", zap.Error(err))
c.Writer.Header().Add("success", "false")
c.Writer.Header().Add("msg", url.QueryEscape("自动化创建失败!请自行清空垃圾数据!"))
return
} else {
apiIds = ids
}
}
a.PackageT = utils.FirstUpper(a.Package)
err := autoCodeService.CreateTemp(a, apiIds...)
if err != nil {
if errors.Is(err, system.ErrAutoMove) {
c.Writer.Header().Add("success", "true")
c.Writer.Header().Add("msg", url.QueryEscape(err.Error()))
} else {
c.Writer.Header().Add("success", "false")
c.Writer.Header().Add("msg", url.QueryEscape(err.Error()))
_ = os.Remove("./ginvueadmin.zip")
}
} else {
c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", "ginvueadmin.zip")) // fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
c.Writer.Header().Add("Content-Type", "application/json")
c.Writer.Header().Add("success", "true")
c.File("./ginvueadmin.zip")
_ = os.Remove("./ginvueadmin.zip")
}
}
// GetDB
// @Tags AutoCode
// @Summary 获取当前所有数据库
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "获取当前所有数据库"
// @Router /autoCode/getDatabase [get]
func (autoApi *AutoCodeApi) GetDB(c *gin.Context) {
businessDB := c.Query("businessDB")
dbs, err := autoCodeService.Database(businessDB).GetDB(businessDB)
var dbList []map[string]interface{}
for _, db := range global.GVA_CONFIG.DBList {
var item = make(map[string]interface{})
item["aliasName"] = db.AliasName
item["dbName"] = db.Dbname
item["disable"] = db.Disable
item["dbtype"] = db.Type
dbList = append(dbList, item)
}
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(gin.H{"dbs": dbs, "dbList": dbList}, "获取成功", c)
}
}
// GetTables
// @Tags AutoCode
// @Summary 获取当前数据库所有表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "获取当前数据库所有表"
// @Router /autoCode/getTables [get]
func (autoApi *AutoCodeApi) GetTables(c *gin.Context) {
dbName := c.DefaultQuery("dbName", global.GVA_CONFIG.Mysql.Dbname)
businessDB := c.Query("businessDB")
tables, err := autoCodeService.Database(businessDB).GetTables(businessDB, dbName)
if err != nil {
global.GVA_LOG.Error("查询table失败!", zap.Error(err))
response.FailWithMessage("查询table失败", c)
} else {
response.OkWithDetailed(gin.H{"tables": tables}, "获取成功", c)
}
}
// GetColumn
// @Tags AutoCode
// @Summary 获取当前表所有字段
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "获取当前表所有字段"
// @Router /autoCode/getColumn [get]
func (autoApi *AutoCodeApi) GetColumn(c *gin.Context) {
businessDB := c.Query("businessDB")
dbName := c.DefaultQuery("dbName", global.GVA_CONFIG.Mysql.Dbname)
tableName := c.Query("tableName")
columns, err := autoCodeService.Database(businessDB).GetColumn(businessDB, tableName, dbName)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(gin.H{"columns": columns}, "获取成功", c)
}
}
// CreatePackage
// @Tags AutoCode
// @Summary 创建package
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysAutoCode true "创建package"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "创建package成功"
// @Router /autoCode/createPackage [post]
func (autoApi *AutoCodeApi) CreatePackage(c *gin.Context) {
var a system.SysAutoCode
_ = c.ShouldBindJSON(&a)
if err := utils.Verify(a, utils.AutoPackageVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err := autoCodeService.CreateAutoCode(&a)
if err != nil {
global.GVA_LOG.Error("创建成功!", zap.Error(err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// GetPackage
// @Tags AutoCode
// @Summary 获取package
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "创建package成功"
// @Router /autoCode/getPackage [post]
func (autoApi *AutoCodeApi) GetPackage(c *gin.Context) {
pkgs, err := autoCodeService.GetPackage()
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(gin.H{"pkgs": pkgs}, "获取成功", c)
}
}
// DelPackage
// @Tags AutoCode
// @Summary 删除package
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysAutoCode true "创建package"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "删除package成功"
// @Router /autoCode/delPackage [post]
func (autoApi *AutoCodeApi) DelPackage(c *gin.Context) {
var a system.SysAutoCode
_ = c.ShouldBindJSON(&a)
err := autoCodeService.DelPackage(a)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// AutoPlug
// @Tags AutoCode
// @Summary 创建插件模板
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysAutoCode true "创建插件模板"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "创建插件模板成功"
// @Router /autoCode/createPlug [post]
func (autoApi *AutoCodeApi) AutoPlug(c *gin.Context) {
var a system.AutoPlugReq
err := c.ShouldBindJSON(&a)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
a.Snake = strings.ToLower(a.PlugName)
a.NeedModel = a.HasRequest || a.HasResponse
err = autoCodeService.CreatePlug(a)
if err != nil {
global.GVA_LOG.Error("预览失败!", zap.Error(err))
response.FailWithMessage("预览失败", c)
return
}
response.Ok(c)
}
// InstallPlugin
// @Tags AutoCode
// @Summary 安装插件
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param plug formData file true "this is a test file"
// @Success 200 {object} response.Response{data=[]interface{},msg=string} "安装插件成功"
// @Router /autoCode/installPlugin [post]
func (autoApi *AutoCodeApi) InstallPlugin(c *gin.Context) {
header, err := c.FormFile("plug")
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
web, server, err := autoCodeService.InstallPlugin(header)
webStr := "web插件安装成功"
serverStr := "server插件安装成功"
if web == -1 {
webStr = "web端插件未成功安装请按照文档自行解压安装如果为纯后端插件请忽略此条提示"
}
if server == -1 {
serverStr = "server端插件未成功安装请按照文档自行解压安装如果为纯前端插件请忽略此条提示"
}
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithData([]interface{}{
gin.H{
"code": web,
"msg": webStr,
},
gin.H{
"code": server,
"msg": serverStr,
}}, c)
}
// PubPlug
// @Tags AutoCode
// @Summary 打包插件
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysAutoCode true "打包插件"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "打包插件成功"
// @Router /autoCode/pubPlug [get]
func (autoApi *AutoCodeApi) PubPlug(c *gin.Context) {
plugName := c.Query("plugName")
snake := strings.ToLower(plugName)
zipPath, err := autoCodeService.PubPlug(snake)
if err != nil {
global.GVA_LOG.Error("打包失败!", zap.Error(err))
response.FailWithMessage("打包失败"+err.Error(), c)
return
}
response.OkWithMessage(fmt.Sprintf("打包成功,文件路径为:%s", zipPath), c)
}

View File

@ -0,0 +1,115 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/request"
"miniapp/model/common/response"
systemReq "miniapp/model/system/request"
)
type AutoCodeHistoryApi struct{}
// First
// @Tags AutoCode
// @Summary 获取meta信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "请求参数"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "获取meta信息"
// @Router /autoCode/getMeta [post]
func (a *AutoCodeHistoryApi) First(c *gin.Context) {
var info request.GetById
err := c.ShouldBindJSON(&info)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
data, err := autoCodeHistoryService.First(&info)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(gin.H{"meta": data}, "获取成功", c)
}
// Delete
// @Tags AutoCode
// @Summary 删除回滚记录
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "请求参数"
// @Success 200 {object} response.Response{msg=string} "删除回滚记录"
// @Router /autoCode/delSysHistory [post]
func (a *AutoCodeHistoryApi) Delete(c *gin.Context) {
var info request.GetById
err := c.ShouldBindJSON(&info)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = autoCodeHistoryService.Delete(&info)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// RollBack
// @Tags AutoCode
// @Summary 回滚自动生成代码
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body systemReq.RollBack true "请求参数"
// @Success 200 {object} response.Response{msg=string} "回滚自动生成代码"
// @Router /autoCode/rollback [post]
func (a *AutoCodeHistoryApi) RollBack(c *gin.Context) {
var info systemReq.RollBack
err := c.ShouldBindJSON(&info)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = autoCodeHistoryService.RollBack(&info)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithMessage("回滚成功", c)
}
// GetList
// @Tags AutoCode
// @Summary 查询回滚记录
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body systemReq.SysAutoHistory true "请求参数"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "查询回滚记录,返回包括列表,总数,页码,每页数量"
// @Router /autoCode/getSysHistory [post]
func (a *AutoCodeHistoryApi) GetList(c *gin.Context) {
var search systemReq.SysAutoHistory
err := c.ShouldBindJSON(&search)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
list, total, err := autoCodeHistoryService.GetList(search.PageInfo)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: search.Page,
PageSize: search.PageSize,
}, "获取成功", c)
}

View File

@ -0,0 +1,70 @@
package system
import (
"time"
"github.com/gin-gonic/gin"
"github.com/mojocn/base64Captcha"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/response"
systemRes "miniapp/model/system/response"
)
// 当开启多服务器部署时替换下面的配置使用redis共享存储验证码
// var store = captcha.NewDefaultRedisStore()
var store = base64Captcha.DefaultMemStore
type BaseApi struct{}
// Captcha
// @Tags Base
// @Summary 生成验证码
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=systemRes.SysCaptchaResponse,msg=string} "生成验证码,返回包括随机数id,base64,验证码长度,是否开启验证码"
// @Router /base/captcha [post]
func (b *BaseApi) Captcha(c *gin.Context) {
// 判断验证码是否开启
openCaptcha := global.GVA_CONFIG.Captcha.OpenCaptcha // 是否开启防爆次数
openCaptchaTimeOut := global.GVA_CONFIG.Captcha.OpenCaptchaTimeOut // 缓存超时时间
key := c.ClientIP()
v, ok := global.BlackCache.Get(key)
if !ok {
global.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
}
var oc bool
if openCaptcha == 0 || openCaptcha < interfaceToInt(v) {
oc = true
}
// 字符,公式,验证码配置
// 生成默认数字的driver
driver := base64Captcha.NewDriverDigit(global.GVA_CONFIG.Captcha.ImgHeight, global.GVA_CONFIG.Captcha.ImgWidth, global.GVA_CONFIG.Captcha.KeyLong, 0.7, 80)
// cp := base64Captcha.NewCaptcha(driver, store.UseWithCtx(c)) // v8下使用redis
cp := base64Captcha.NewCaptcha(driver, store)
id, b64s, err := cp.Generate()
if err != nil {
global.GVA_LOG.Error("验证码获取失败!", zap.Error(err))
response.FailWithMessage("验证码获取失败", c)
return
}
response.OkWithDetailed(systemRes.SysCaptchaResponse{
CaptchaId: id,
PicPath: b64s,
CaptchaLength: global.GVA_CONFIG.Captcha.KeyLong,
OpenCaptcha: oc,
}, "验证码获取成功", c)
}
// 类型转换
func interfaceToInt(v interface{}) (i int) {
switch v := v.(type) {
case int:
i = v
default:
i = 0
}
return
}

View File

@ -0,0 +1,68 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/response"
"miniapp/model/system/request"
systemRes "miniapp/model/system/response"
"miniapp/utils"
)
type CasbinApi struct{}
// UpdateCasbin
// @Tags Casbin
// @Summary 更新角色api权限
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.CasbinInReceive true "权限id, 权限模型列表"
// @Success 200 {object} response.Response{msg=string} "更新角色api权限"
// @Router /casbin/UpdateCasbin [post]
func (cas *CasbinApi) UpdateCasbin(c *gin.Context) {
var cmr request.CasbinInReceive
err := c.ShouldBindJSON(&cmr)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(cmr, utils.AuthorityIdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = casbinService.UpdateCasbin(cmr.AuthorityId, cmr.CasbinInfos)
if err != nil {
global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
return
}
response.OkWithMessage("更新成功", c)
}
// GetPolicyPathByAuthorityId
// @Tags Casbin
// @Summary 获取权限列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.CasbinInReceive true "权限id, 权限模型列表"
// @Success 200 {object} response.Response{data=systemRes.PolicyPathResponse,msg=string} "获取权限列表,返回包括casbin详情列表"
// @Router /casbin/getPolicyPathByAuthorityId [post]
func (cas *CasbinApi) GetPolicyPathByAuthorityId(c *gin.Context) {
var casbin request.CasbinInReceive
err := c.ShouldBindJSON(&casbin)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(casbin, utils.AuthorityIdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
paths := casbinService.GetPolicyPathByAuthorityId(casbin.AuthorityId)
response.OkWithDetailed(systemRes.PolicyPathResponse{Paths: paths}, "获取成功", c)
}

View File

@ -0,0 +1,71 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/response"
sysModel "miniapp/model/system"
"miniapp/model/system/request"
)
type ChatGptApi struct{}
func (chat *ChatGptApi) CreateSK(c *gin.Context) {
var option sysModel.SysChatGptOption
c.ShouldBindJSON(&option)
err := chatGptService.CreateSK(option)
if err != nil {
global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败"+err.Error(), c)
return
}
response.OkWithMessage("创建成功", c)
}
func (chat *ChatGptApi) GetSK(c *gin.Context) {
var option sysModel.SysChatGptOption
c.ShouldBindJSON(&option)
_, err := chatGptService.GetSK()
if err != nil {
response.OkWithDetailed(gin.H{
"ok": false,
}, "无sk或获取失败", c)
return
}
response.OkWithDetailed(gin.H{
"ok": true,
}, "获取成功", c)
}
func (chat *ChatGptApi) DeleteSK(c *gin.Context) {
err := chatGptService.DeleteSK()
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败"+err.Error(), c)
return
}
response.OkWithMessage("删除成功", c)
}
func (chat *ChatGptApi) GetTable(c *gin.Context) {
var req request.ChatGptRequest
err := c.ShouldBindJSON(&req)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
sql, results, err := chatGptService.GetTable(req)
if err != nil {
global.GVA_LOG.Error("查询失败!", zap.Error(err))
response.FailWithDetailed(gin.H{
"sql": sql,
"results": results,
}, "生成失败"+err.Error(), c)
return
}
response.OkWithDetailed(gin.H{
"sql": sql,
"results": results,
}, "ChatGpt生成完成", c)
}

View File

@ -0,0 +1,148 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/response"
"miniapp/model/system"
"miniapp/model/system/request"
"miniapp/utils"
)
type DictionaryApi struct{}
// CreateSysDictionary
// @Tags SysDictionary
// @Summary 创建SysDictionary
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysDictionary true "SysDictionary模型"
// @Success 200 {object} response.Response{msg=string} "创建SysDictionary"
// @Router /sysDictionary/createSysDictionary [post]
func (s *DictionaryApi) CreateSysDictionary(c *gin.Context) {
var dictionary system.SysDictionary
err := c.ShouldBindJSON(&dictionary)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = dictionaryService.CreateSysDictionary(dictionary)
if err != nil {
global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
return
}
response.OkWithMessage("创建成功", c)
}
// DeleteSysDictionary
// @Tags SysDictionary
// @Summary 删除SysDictionary
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysDictionary true "SysDictionary模型"
// @Success 200 {object} response.Response{msg=string} "删除SysDictionary"
// @Router /sysDictionary/deleteSysDictionary [delete]
func (s *DictionaryApi) DeleteSysDictionary(c *gin.Context) {
var dictionary system.SysDictionary
err := c.ShouldBindJSON(&dictionary)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = dictionaryService.DeleteSysDictionary(dictionary)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// UpdateSysDictionary
// @Tags SysDictionary
// @Summary 更新SysDictionary
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysDictionary true "SysDictionary模型"
// @Success 200 {object} response.Response{msg=string} "更新SysDictionary"
// @Router /sysDictionary/updateSysDictionary [put]
func (s *DictionaryApi) UpdateSysDictionary(c *gin.Context) {
var dictionary system.SysDictionary
err := c.ShouldBindJSON(&dictionary)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = dictionaryService.UpdateSysDictionary(&dictionary)
if err != nil {
global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
return
}
response.OkWithMessage("更新成功", c)
}
// FindSysDictionary
// @Tags SysDictionary
// @Summary 用id查询SysDictionary
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query system.SysDictionary true "ID或字典英名"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "用id查询SysDictionary"
// @Router /sysDictionary/findSysDictionary [get]
func (s *DictionaryApi) FindSysDictionary(c *gin.Context) {
var dictionary system.SysDictionary
err := c.ShouldBindQuery(&dictionary)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
sysDictionary, err := dictionaryService.GetSysDictionary(dictionary.Type, dictionary.ID, dictionary.Status)
if err != nil {
global.GVA_LOG.Error("字典未创建或未开启!", zap.Error(err))
response.FailWithMessage("字典未创建或未开启", c)
return
}
response.OkWithDetailed(gin.H{"resysDictionary": sysDictionary}, "查询成功", c)
}
// GetSysDictionaryList
// @Tags SysDictionary
// @Summary 分页获取SysDictionary列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.SysDictionarySearch true "页码, 每页大小, 搜索条件"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取SysDictionary列表,返回包括列表,总数,页码,每页数量"
// @Router /sysDictionary/getSysDictionaryList [get]
func (s *DictionaryApi) GetSysDictionaryList(c *gin.Context) {
var pageInfo request.SysDictionarySearch
err := c.ShouldBindQuery(&pageInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
list, total, err := dictionaryService.GetSysDictionaryInfoList(pageInfo)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}

View File

@ -0,0 +1,148 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/response"
"miniapp/model/system"
"miniapp/model/system/request"
"miniapp/utils"
)
type DictionaryDetailApi struct{}
// CreateSysDictionaryDetail
// @Tags SysDictionaryDetail
// @Summary 创建SysDictionaryDetail
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysDictionaryDetail true "SysDictionaryDetail模型"
// @Success 200 {object} response.Response{msg=string} "创建SysDictionaryDetail"
// @Router /sysDictionaryDetail/createSysDictionaryDetail [post]
func (s *DictionaryDetailApi) CreateSysDictionaryDetail(c *gin.Context) {
var detail system.SysDictionaryDetail
err := c.ShouldBindJSON(&detail)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = dictionaryDetailService.CreateSysDictionaryDetail(detail)
if err != nil {
global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
return
}
response.OkWithMessage("创建成功", c)
}
// DeleteSysDictionaryDetail
// @Tags SysDictionaryDetail
// @Summary 删除SysDictionaryDetail
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysDictionaryDetail true "SysDictionaryDetail模型"
// @Success 200 {object} response.Response{msg=string} "删除SysDictionaryDetail"
// @Router /sysDictionaryDetail/deleteSysDictionaryDetail [delete]
func (s *DictionaryDetailApi) DeleteSysDictionaryDetail(c *gin.Context) {
var detail system.SysDictionaryDetail
err := c.ShouldBindJSON(&detail)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = dictionaryDetailService.DeleteSysDictionaryDetail(detail)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// UpdateSysDictionaryDetail
// @Tags SysDictionaryDetail
// @Summary 更新SysDictionaryDetail
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysDictionaryDetail true "更新SysDictionaryDetail"
// @Success 200 {object} response.Response{msg=string} "更新SysDictionaryDetail"
// @Router /sysDictionaryDetail/updateSysDictionaryDetail [put]
func (s *DictionaryDetailApi) UpdateSysDictionaryDetail(c *gin.Context) {
var detail system.SysDictionaryDetail
err := c.ShouldBindJSON(&detail)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = dictionaryDetailService.UpdateSysDictionaryDetail(&detail)
if err != nil {
global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
return
}
response.OkWithMessage("更新成功", c)
}
// FindSysDictionaryDetail
// @Tags SysDictionaryDetail
// @Summary 用id查询SysDictionaryDetail
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query system.SysDictionaryDetail true "用id查询SysDictionaryDetail"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "用id查询SysDictionaryDetail"
// @Router /sysDictionaryDetail/findSysDictionaryDetail [get]
func (s *DictionaryDetailApi) FindSysDictionaryDetail(c *gin.Context) {
var detail system.SysDictionaryDetail
err := c.ShouldBindQuery(&detail)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(detail, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
reSysDictionaryDetail, err := dictionaryDetailService.GetSysDictionaryDetail(detail.ID)
if err != nil {
global.GVA_LOG.Error("查询失败!", zap.Error(err))
response.FailWithMessage("查询失败", c)
return
}
response.OkWithDetailed(gin.H{"reSysDictionaryDetail": reSysDictionaryDetail}, "查询成功", c)
}
// GetSysDictionaryDetailList
// @Tags SysDictionaryDetail
// @Summary 分页获取SysDictionaryDetail列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.SysDictionaryDetailSearch true "页码, 每页大小, 搜索条件"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取SysDictionaryDetail列表,返回包括列表,总数,页码,每页数量"
// @Router /sysDictionaryDetail/getSysDictionaryDetailList [get]
func (s *DictionaryDetailApi) GetSysDictionaryDetailList(c *gin.Context) {
var pageInfo request.SysDictionaryDetailSearch
err := c.ShouldBindQuery(&pageInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
list, total, err := dictionaryDetailService.GetSysDictionaryDetailInfoList(pageInfo)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}

View File

@ -0,0 +1,59 @@
package system
import (
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/response"
"miniapp/model/system/request"
"github.com/gin-gonic/gin"
)
type DBApi struct{}
// InitDB
// @Tags InitDB
// @Summary 初始化用户数据库
// @Produce application/json
// @Param data body request.InitDB true "初始化数据库参数"
// @Success 200 {object} response.Response{data=string} "初始化用户数据库"
// @Router /init/initdb [post]
func (i *DBApi) InitDB(c *gin.Context) {
if global.GVA_DB != nil {
global.GVA_LOG.Error("已存在数据库配置!")
response.FailWithMessage("已存在数据库配置", c)
return
}
var dbInfo request.InitDB
if err := c.ShouldBindJSON(&dbInfo); err != nil {
global.GVA_LOG.Error("参数校验不通过!", zap.Error(err))
response.FailWithMessage("参数校验不通过", c)
return
}
if err := initDBService.InitDB(dbInfo); err != nil {
global.GVA_LOG.Error("自动创建数据库失败!", zap.Error(err))
response.FailWithMessage("自动创建数据库失败,请查看后台日志,检查后在进行初始化", c)
return
}
response.OkWithMessage("自动创建数据库成功", c)
}
// CheckDB
// @Tags CheckDB
// @Summary 初始化用户数据库
// @Produce application/json
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "初始化用户数据库"
// @Router /init/checkdb [post]
func (i *DBApi) CheckDB(c *gin.Context) {
var (
message = "前往初始化数据库"
needInit = true
)
if global.GVA_DB != nil {
message = "数据库无需初始化"
needInit = false
}
global.GVA_LOG.Info(message)
response.OkWithDetailed(gin.H{"needInit": needInit}, message, c)
}

View File

@ -0,0 +1,31 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/response"
"miniapp/model/system"
)
type JwtApi struct{}
// JsonInBlacklist
// @Tags Jwt
// @Summary jwt加入黑名单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "jwt加入黑名单"
// @Router /jwt/jsonInBlacklist [post]
func (j *JwtApi) JsonInBlacklist(c *gin.Context) {
token := c.Request.Header.Get("x-token")
jwt := system.JwtBlacklist{Jwt: token}
err := jwtService.JsonInBlacklist(jwt)
if err != nil {
global.GVA_LOG.Error("jwt作废失败!", zap.Error(err))
response.FailWithMessage("jwt作废失败", c)
return
}
response.OkWithMessage("jwt作废成功", c)
}

278
api/v1/system/sys_menu.go Normal file
View File

@ -0,0 +1,278 @@
package system
import (
"miniapp/global"
"miniapp/model/common/request"
"miniapp/model/common/response"
"miniapp/model/system"
systemReq "miniapp/model/system/request"
systemRes "miniapp/model/system/response"
"miniapp/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
type AuthorityMenuApi struct{}
// GetMenu
// @Tags AuthorityMenu
// @Summary 获取用户动态路由
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body request.Empty true "空"
// @Success 200 {object} response.Response{data=systemRes.SysMenusResponse,msg=string} "获取用户动态路由,返回包括系统菜单详情列表"
// @Router /menu/getMenu [post]
func (a *AuthorityMenuApi) GetMenu(c *gin.Context) {
menus, err := menuService.GetMenuTree(utils.GetUserAuthorityId(c))
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
if menus == nil {
menus = []system.SysMenu{}
}
response.OkWithDetailed(systemRes.SysMenusResponse{Menus: menus}, "获取成功", c)
}
// GetBaseMenuTree
// @Tags AuthorityMenu
// @Summary 获取用户动态路由
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body request.Empty true "空"
// @Success 200 {object} response.Response{data=systemRes.SysBaseMenusResponse,msg=string} "获取用户动态路由,返回包括系统菜单列表"
// @Router /menu/getBaseMenuTree [post]
func (a *AuthorityMenuApi) GetBaseMenuTree(c *gin.Context) {
menus, err := menuService.GetBaseMenuTree()
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(systemRes.SysBaseMenusResponse{Menus: menus}, "获取成功", c)
}
// AddMenuAuthority
// @Tags AuthorityMenu
// @Summary 增加menu和角色关联关系
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body systemReq.AddMenuAuthorityInfo true "角色ID"
// @Success 200 {object} response.Response{msg=string} "增加menu和角色关联关系"
// @Router /menu/addMenuAuthority [post]
func (a *AuthorityMenuApi) AddMenuAuthority(c *gin.Context) {
var authorityMenu systemReq.AddMenuAuthorityInfo
err := c.ShouldBindJSON(&authorityMenu)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := utils.Verify(authorityMenu, utils.AuthorityIdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := menuService.AddMenuAuthority(authorityMenu.Menus, authorityMenu.AuthorityId); err != nil {
global.GVA_LOG.Error("添加失败!", zap.Error(err))
response.FailWithMessage("添加失败", c)
} else {
response.OkWithMessage("添加成功", c)
}
}
// GetMenuAuthority
// @Tags AuthorityMenu
// @Summary 获取指定角色menu
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetAuthorityId true "角色ID"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "获取指定角色menu"
// @Router /menu/getMenuAuthority [post]
func (a *AuthorityMenuApi) GetMenuAuthority(c *gin.Context) {
var param request.GetAuthorityId
err := c.ShouldBindJSON(&param)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(param, utils.AuthorityIdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
menus, err := menuService.GetMenuAuthority(&param)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithDetailed(systemRes.SysMenusResponse{Menus: menus}, "获取失败", c)
return
}
response.OkWithDetailed(gin.H{"menus": menus}, "获取成功", c)
}
// AddBaseMenu
// @Tags Menu
// @Summary 新增菜单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysBaseMenu true "路由path, 父菜单ID, 路由name, 对应前端文件路径, 排序标记"
// @Success 200 {object} response.Response{msg=string} "新增菜单"
// @Router /menu/addBaseMenu [post]
func (a *AuthorityMenuApi) AddBaseMenu(c *gin.Context) {
var menu system.SysBaseMenu
err := c.ShouldBindJSON(&menu)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(menu, utils.MenuVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(menu.Meta, utils.MenuMetaVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = menuService.AddBaseMenu(menu)
if err != nil {
global.GVA_LOG.Error("添加失败!", zap.Error(err))
response.FailWithMessage("添加失败", c)
return
}
response.OkWithMessage("添加成功", c)
}
// DeleteBaseMenu
// @Tags Menu
// @Summary 删除菜单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "菜单id"
// @Success 200 {object} response.Response{msg=string} "删除菜单"
// @Router /menu/deleteBaseMenu [post]
func (a *AuthorityMenuApi) DeleteBaseMenu(c *gin.Context) {
var menu request.GetById
err := c.ShouldBindJSON(&menu)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(menu, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = baseMenuService.DeleteBaseMenu(menu.ID)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// UpdateBaseMenu
// @Tags Menu
// @Summary 更新菜单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysBaseMenu true "路由path, 父菜单ID, 路由name, 对应前端文件路径, 排序标记"
// @Success 200 {object} response.Response{msg=string} "更新菜单"
// @Router /menu/updateBaseMenu [post]
func (a *AuthorityMenuApi) UpdateBaseMenu(c *gin.Context) {
var menu system.SysBaseMenu
err := c.ShouldBindJSON(&menu)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(menu, utils.MenuVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(menu.Meta, utils.MenuMetaVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = baseMenuService.UpdateBaseMenu(menu)
if err != nil {
global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
return
}
response.OkWithMessage("更新成功", c)
}
// GetBaseMenuById
// @Tags Menu
// @Summary 根据id获取菜单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "菜单id"
// @Success 200 {object} response.Response{data=systemRes.SysBaseMenuResponse,msg=string} "根据id获取菜单,返回包括系统菜单列表"
// @Router /menu/getBaseMenuById [post]
func (a *AuthorityMenuApi) GetBaseMenuById(c *gin.Context) {
var idInfo request.GetById
err := c.ShouldBindJSON(&idInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(idInfo, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
menu, err := baseMenuService.GetBaseMenuById(idInfo.ID)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(systemRes.SysBaseMenuResponse{Menu: menu}, "获取成功", c)
}
// GetMenuList
// @Tags Menu
// @Summary 分页获取基础menu列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.PageInfo true "页码, 每页大小"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取基础menu列表,返回包括列表,总数,页码,每页数量"
// @Router /menu/getMenuList [post]
func (a *AuthorityMenuApi) GetMenuList(c *gin.Context) {
var pageInfo request.PageInfo
err := c.ShouldBindJSON(&pageInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(pageInfo, utils.PageInfoVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
menuList, total, err := menuService.GetInfoList()
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(response.PageResult{
List: menuList,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}

View File

@ -0,0 +1,149 @@
package system
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"miniapp/global"
"miniapp/model/common/request"
"miniapp/model/common/response"
"miniapp/model/system"
systemReq "miniapp/model/system/request"
"miniapp/utils"
)
type OperationRecordApi struct{}
// CreateSysOperationRecord
// @Tags SysOperationRecord
// @Summary 创建SysOperationRecord
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysOperationRecord true "创建SysOperationRecord"
// @Success 200 {object} response.Response{msg=string} "创建SysOperationRecord"
// @Router /sysOperationRecord/createSysOperationRecord [post]
func (s *OperationRecordApi) CreateSysOperationRecord(c *gin.Context) {
var sysOperationRecord system.SysOperationRecord
err := c.ShouldBindJSON(&sysOperationRecord)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = operationRecordService.CreateSysOperationRecord(sysOperationRecord)
if err != nil {
global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
return
}
response.OkWithMessage("创建成功", c)
}
// DeleteSysOperationRecord
// @Tags SysOperationRecord
// @Summary 删除SysOperationRecord
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysOperationRecord true "SysOperationRecord模型"
// @Success 200 {object} response.Response{msg=string} "删除SysOperationRecord"
// @Router /sysOperationRecord/deleteSysOperationRecord [delete]
func (s *OperationRecordApi) DeleteSysOperationRecord(c *gin.Context) {
var sysOperationRecord system.SysOperationRecord
err := c.ShouldBindJSON(&sysOperationRecord)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = operationRecordService.DeleteSysOperationRecord(sysOperationRecord)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// DeleteSysOperationRecordByIds
// @Tags SysOperationRecord
// @Summary 批量删除SysOperationRecord
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除SysOperationRecord"
// @Success 200 {object} response.Response{msg=string} "批量删除SysOperationRecord"
// @Router /sysOperationRecord/deleteSysOperationRecordByIds [delete]
func (s *OperationRecordApi) DeleteSysOperationRecordByIds(c *gin.Context) {
var IDS request.IdsReq
err := c.ShouldBindJSON(&IDS)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = operationRecordService.DeleteSysOperationRecordByIds(IDS)
if err != nil {
global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
response.FailWithMessage("批量删除失败", c)
return
}
response.OkWithMessage("批量删除成功", c)
}
// FindSysOperationRecord
// @Tags SysOperationRecord
// @Summary 用id查询SysOperationRecord
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query system.SysOperationRecord true "Id"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "用id查询SysOperationRecord"
// @Router /sysOperationRecord/findSysOperationRecord [get]
func (s *OperationRecordApi) FindSysOperationRecord(c *gin.Context) {
var sysOperationRecord system.SysOperationRecord
err := c.ShouldBindQuery(&sysOperationRecord)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(sysOperationRecord, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
reSysOperationRecord, err := operationRecordService.GetSysOperationRecord(sysOperationRecord.ID)
if err != nil {
global.GVA_LOG.Error("查询失败!", zap.Error(err))
response.FailWithMessage("查询失败", c)
return
}
response.OkWithDetailed(gin.H{"reSysOperationRecord": reSysOperationRecord}, "查询成功", c)
}
// GetSysOperationRecordList
// @Tags SysOperationRecord
// @Summary 分页获取SysOperationRecord列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.SysOperationRecordSearch true "页码, 每页大小, 搜索条件"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取SysOperationRecord列表,返回包括列表,总数,页码,每页数量"
// @Router /sysOperationRecord/getSysOperationRecordList [get]
func (s *OperationRecordApi) GetSysOperationRecordList(c *gin.Context) {
var pageInfo systemReq.SysOperationRecordSearch
err := c.ShouldBindQuery(&pageInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
list, total, err := operationRecordService.GetSysOperationRecordInfoList(pageInfo)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}

View File

@ -0,0 +1,89 @@
package system
import (
"miniapp/global"
"miniapp/model/common/response"
"miniapp/model/system"
systemRes "miniapp/model/system/response"
"miniapp/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
type SystemApi struct{}
// GetSystemConfig
// @Tags System
// @Summary 获取配置文件内容
// @Security ApiKeyAuth
// @Produce application/json
// @Success 200 {object} response.Response{data=systemRes.SysConfigResponse,msg=string} "获取配置文件内容,返回包括系统配置"
// @Router /system/getSystemConfig [post]
func (s *SystemApi) GetSystemConfig(c *gin.Context) {
config, err := systemConfigService.GetSystemConfig()
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(systemRes.SysConfigResponse{Config: config}, "获取成功", c)
}
// SetSystemConfig
// @Tags System
// @Summary 设置配置文件内容
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body system.System true "设置配置文件内容"
// @Success 200 {object} response.Response{data=string} "设置配置文件内容"
// @Router /system/setSystemConfig [post]
func (s *SystemApi) SetSystemConfig(c *gin.Context) {
var sys system.System
err := c.ShouldBindJSON(&sys)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = systemConfigService.SetSystemConfig(sys)
if err != nil {
global.GVA_LOG.Error("设置失败!", zap.Error(err))
response.FailWithMessage("设置失败", c)
return
}
response.OkWithMessage("设置成功", c)
}
// ReloadSystem
// @Tags System
// @Summary 重启系统
// @Security ApiKeyAuth
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "重启系统"
// @Router /system/reloadSystem [post]
func (s *SystemApi) ReloadSystem(c *gin.Context) {
err := utils.Reload()
if err != nil {
global.GVA_LOG.Error("重启系统失败!", zap.Error(err))
response.FailWithMessage("重启系统失败", c)
return
}
response.OkWithMessage("重启系统成功", c)
}
// GetServerInfo
// @Tags System
// @Summary 获取服务器信息
// @Security ApiKeyAuth
// @Produce application/json
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "获取服务器信息"
// @Router /system/getServerInfo [post]
func (s *SystemApi) GetServerInfo(c *gin.Context) {
server, err := systemConfigService.GetServerInfo()
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(gin.H{"server.exe.exe": server}, "获取成功", c)
}

462
api/v1/system/sys_user.go Normal file
View File

@ -0,0 +1,462 @@
package system
import (
"strconv"
"time"
"miniapp/global"
"miniapp/model/common/request"
"miniapp/model/common/response"
"miniapp/model/system"
systemReq "miniapp/model/system/request"
systemRes "miniapp/model/system/response"
"miniapp/utils"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
)
// Login
// @Tags Base
// @Summary 用户登录
// @Produce application/json
// @Param data body systemReq.Login true "用户名, 密码, 验证码"
// @Success 200 {object} response.Response{data=systemRes.LoginResponse,msg=string} "返回包括用户信息,token,过期时间"
// @Router /base/login [post]
func (b *BaseApi) Login(c *gin.Context) {
var l systemReq.Login
err := c.ShouldBindJSON(&l)
key := c.ClientIP()
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(l, utils.LoginVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
// 判断验证码是否开启
openCaptcha := global.GVA_CONFIG.Captcha.OpenCaptcha // 是否开启防爆次数
openCaptchaTimeOut := global.GVA_CONFIG.Captcha.OpenCaptchaTimeOut // 缓存超时时间
v, ok := global.BlackCache.Get(key)
if !ok {
global.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
}
var oc bool = openCaptcha == 0 || openCaptcha < interfaceToInt(v)
if !oc || (l.CaptchaId != "" && l.Captcha != "" && store.Verify(l.CaptchaId, l.Captcha, true)) {
u := &system.SysUser{Username: l.Username, Password: l.Password}
user, err := userService.Login(u)
if err != nil {
global.GVA_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Error(err))
// 验证码次数+1
global.BlackCache.Increment(key, 1)
response.FailWithMessage("用户名不存在或者密码错误", c)
return
}
if user.Enable != 1 {
global.GVA_LOG.Error("登陆失败! 用户被禁止登录!")
// 验证码次数+1
global.BlackCache.Increment(key, 1)
response.FailWithMessage("用户被禁止登录", c)
return
}
b.TokenNext(c, *user)
return
}
// 验证码次数+1
global.BlackCache.Increment(key, 1)
response.FailWithMessage("验证码错误", c)
}
// TokenNext 登录以后签发jwt
func (b *BaseApi) TokenNext(c *gin.Context, user system.SysUser) {
j := &utils.JWT{SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey)} // 唯一签名
claims := j.CreateClaims(systemReq.BaseClaims{
UUID: user.UUID,
ID: user.ID,
NickName: user.NickName,
Username: user.Username,
AuthorityId: user.AuthorityId,
})
token, err := j.CreateToken(claims)
if err != nil {
global.GVA_LOG.Error("获取token失败!", zap.Error(err))
response.FailWithMessage("获取token失败", c)
return
}
if !global.GVA_CONFIG.System.UseMultipoint {
response.OkWithDetailed(systemRes.LoginResponse{
User: user,
Token: token,
ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
}, "登录成功", c)
return
}
if jwtStr, err := jwtService.GetRedisJWT(user.Username); err == redis.Nil {
if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
response.FailWithMessage("设置登录状态失败", c)
return
}
response.OkWithDetailed(systemRes.LoginResponse{
User: user,
Token: token,
ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
}, "登录成功", c)
} else if err != nil {
global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
response.FailWithMessage("设置登录状态失败", c)
} else {
var blackJWT system.JwtBlacklist
blackJWT.Jwt = jwtStr
if err := jwtService.JsonInBlacklist(blackJWT); err != nil {
response.FailWithMessage("jwt作废失败", c)
return
}
if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
response.FailWithMessage("设置登录状态失败", c)
return
}
response.OkWithDetailed(systemRes.LoginResponse{
User: user,
Token: token,
ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
}, "登录成功", c)
}
}
// Register
// @Tags SysUser
// @Summary 用户注册账号
// @Produce application/json
// @Param data body systemReq.Register true "用户名, 昵称, 密码, 角色ID"
// @Success 200 {object} response.Response{data=systemRes.SysUserResponse,msg=string} "用户注册账号,返回包括用户信息"
// @Router /user/admin_register [post]
func (b *BaseApi) Register(c *gin.Context) {
var r systemReq.Register
err := c.ShouldBindJSON(&r)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(r, utils.RegisterVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
var authorities []system.SysAuthority
for _, v := range r.AuthorityIds {
authorities = append(authorities, system.SysAuthority{
AuthorityId: v,
})
}
user := &system.SysUser{Username: r.Username, NickName: r.NickName, Password: r.Password, HeaderImg: r.HeaderImg, AuthorityId: r.AuthorityId, Authorities: authorities, Enable: r.Enable, Phone: r.Phone, Email: r.Email}
userReturn, err := userService.Register(*user)
if err != nil {
global.GVA_LOG.Error("注册失败!", zap.Error(err))
response.FailWithDetailed(systemRes.SysUserResponse{User: userReturn}, "注册失败", c)
return
}
response.OkWithDetailed(systemRes.SysUserResponse{User: userReturn}, "注册成功", c)
}
// ChangePassword
// @Tags SysUser
// @Summary 用户修改密码
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body systemReq.ChangePasswordReq true "用户名, 原密码, 新密码"
// @Success 200 {object} response.Response{msg=string} "用户修改密码"
// @Router /user/changePassword [post]
func (b *BaseApi) ChangePassword(c *gin.Context) {
var req systemReq.ChangePasswordReq
err := c.ShouldBindJSON(&req)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(req, utils.ChangePasswordVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
uid := utils.GetUserID(c)
u := &system.SysUser{GVA_MODEL: global.GVA_MODEL{ID: uid}, Password: req.Password}
_, err = userService.ChangePassword(u, req.NewPassword)
if err != nil {
global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage("修改失败,原密码与当前账户不符", c)
return
}
response.OkWithMessage("修改成功", c)
}
// GetUserList
// @Tags SysUser
// @Summary 分页获取用户列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.PageInfo true "页码, 每页大小"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取用户列表,返回包括列表,总数,页码,每页数量"
// @Router /user/getUserList [post]
func (b *BaseApi) GetUserList(c *gin.Context) {
var pageInfo request.PageInfo
err := c.ShouldBindJSON(&pageInfo)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(pageInfo, utils.PageInfoVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
list, total, err := userService.GetUserInfoList(pageInfo)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
// SetUserAuthority
// @Tags SysUser
// @Summary 更改用户权限
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body systemReq.SetUserAuth true "用户UUID, 角色ID"
// @Success 200 {object} response.Response{msg=string} "设置用户权限"
// @Router /user/setUserAuthority [post]
func (b *BaseApi) SetUserAuthority(c *gin.Context) {
var sua systemReq.SetUserAuth
err := c.ShouldBindJSON(&sua)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if UserVerifyErr := utils.Verify(sua, utils.SetUserAuthorityVerify); UserVerifyErr != nil {
response.FailWithMessage(UserVerifyErr.Error(), c)
return
}
userID := utils.GetUserID(c)
err = userService.SetUserAuthority(userID, sua.AuthorityId)
if err != nil {
global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage(err.Error(), c)
return
}
claims := utils.GetUserInfo(c)
j := &utils.JWT{SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey)} // 唯一签名
claims.AuthorityId = sua.AuthorityId
if token, err := j.CreateToken(*claims); err != nil {
global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage(err.Error(), c)
} else {
c.Header("new-token", token)
c.Header("new-expires-at", strconv.FormatInt(claims.ExpiresAt.Unix(), 10))
response.OkWithMessage("修改成功", c)
}
}
// SetUserAuthorities
// @Tags SysUser
// @Summary 设置用户权限
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body systemReq.SetUserAuthorities true "用户UUID, 角色ID"
// @Success 200 {object} response.Response{msg=string} "设置用户权限"
// @Router /user/setUserAuthorities [post]
func (b *BaseApi) SetUserAuthorities(c *gin.Context) {
var sua systemReq.SetUserAuthorities
err := c.ShouldBindJSON(&sua)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = userService.SetUserAuthorities(sua.ID, sua.AuthorityIds)
if err != nil {
global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage("修改失败", c)
return
}
response.OkWithMessage("修改成功", c)
}
// DeleteUser
// @Tags SysUser
// @Summary 删除用户
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "用户ID"
// @Success 200 {object} response.Response{msg=string} "删除用户"
// @Router /user/deleteUser [delete]
func (b *BaseApi) DeleteUser(c *gin.Context) {
var reqId request.GetById
err := c.ShouldBindJSON(&reqId)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(reqId, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
jwtId := utils.GetUserID(c)
if jwtId == uint(reqId.ID) {
response.FailWithMessage("删除失败, 自杀失败", c)
return
}
err = userService.DeleteUser(reqId.ID)
if err != nil {
global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
response.OkWithMessage("删除成功", c)
}
// SetUserInfo
// @Tags SysUser
// @Summary 设置用户信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysUser true "ID, 用户名, 昵称, 头像链接"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "设置用户信息"
// @Router /user/setUserInfo [put]
func (b *BaseApi) SetUserInfo(c *gin.Context) {
var user systemReq.ChangeUserInfo
err := c.ShouldBindJSON(&user)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = utils.Verify(user, utils.IdVerify)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if len(user.AuthorityIds) != 0 {
err = userService.SetUserAuthorities(user.ID, user.AuthorityIds)
if err != nil {
global.GVA_LOG.Error("设置失败!", zap.Error(err))
response.FailWithMessage("设置失败", c)
return
}
}
err = userService.SetUserInfo(system.SysUser{
GVA_MODEL: global.GVA_MODEL{
ID: user.ID,
},
NickName: user.NickName,
HeaderImg: user.HeaderImg,
Phone: user.Phone,
Email: user.Email,
SideMode: user.SideMode,
Enable: user.Enable,
})
if err != nil {
global.GVA_LOG.Error("设置失败!", zap.Error(err))
response.FailWithMessage("设置失败", c)
return
}
response.OkWithMessage("设置成功", c)
}
// SetSelfInfo
// @Tags SysUser
// @Summary 设置用户信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body system.SysUser true "ID, 用户名, 昵称, 头像链接"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "设置用户信息"
// @Router /user/SetSelfInfo [put]
func (b *BaseApi) SetSelfInfo(c *gin.Context) {
var user systemReq.ChangeUserInfo
err := c.ShouldBindJSON(&user)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
user.ID = utils.GetUserID(c)
err = userService.SetSelfInfo(system.SysUser{
GVA_MODEL: global.GVA_MODEL{
ID: user.ID,
},
NickName: user.NickName,
HeaderImg: user.HeaderImg,
Phone: user.Phone,
Email: user.Email,
SideMode: user.SideMode,
Enable: user.Enable,
})
if err != nil {
global.GVA_LOG.Error("设置失败!", zap.Error(err))
response.FailWithMessage("设置失败", c)
return
}
response.OkWithMessage("设置成功", c)
}
// GetUserInfo
// @Tags SysUser
// @Summary 获取用户信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "获取用户信息"
// @Router /user/getUserInfo [get]
func (b *BaseApi) GetUserInfo(c *gin.Context) {
uuid := utils.GetUserUuid(c)
ReqUser, err := userService.GetUserInfo(uuid)
if err != nil {
global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "获取成功", c)
}
// ResetPassword
// @Tags SysUser
// @Summary 重置用户密码
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body system.SysUser true "ID"
// @Success 200 {object} response.Response{msg=string} "重置用户密码"
// @Router /user/resetPassword [post]
func (b *BaseApi) ResetPassword(c *gin.Context) {
var user system.SysUser
err := c.ShouldBindJSON(&user)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = userService.ResetPassword(user.ID)
if err != nil {
global.GVA_LOG.Error("重置失败!", zap.Error(err))
response.FailWithMessage("重置失败"+err.Error(), c)
return
}
response.OkWithMessage("重置成功", c)
}

25
client/redis.go Normal file
View File

@ -0,0 +1,25 @@
package client
import (
"context"
"git.echol.cn/loser/logger/log"
"github.com/go-redis/redis/v8"
"miniapp/global"
)
var Redis *redis.Client
func InitRedisClient() {
// 初始化连接
conn := redis.NewClient(&redis.Options{
Addr: global.GVA_CONFIG.Redis.Addr,
Password: global.GVA_CONFIG.Redis.Password,
DB: global.GVA_CONFIG.Redis.DB,
})
if err := conn.Ping(context.Background()).Err(); err != nil {
log.Panicf("Redis连接初始化失败: %v", err)
} else {
log.Debug("Redis连接初始化成功")
}
Redis = conn
}

18
config/auto_code.go Normal file
View File

@ -0,0 +1,18 @@
package config
type Autocode struct {
SModel string `mapstructure:"server.exe.exe-model" json:"server.exe.exe-model" yaml:"server.exe.exe-model"`
SRouter string `mapstructure:"server.exe.exe-router" json:"server.exe.exe-router" yaml:"server.exe.exe-router"`
Server string `mapstructure:"server.exe.exe" json:"server.exe.exe" yaml:"server.exe.exe"`
SApi string `mapstructure:"server.exe.exe-api" json:"server.exe.exe-api" yaml:"server.exe.exe-api"`
SPlug string `mapstructure:"server.exe.exe-plug" json:"server.exe.exe-plug" yaml:"server.exe.exe-plug"`
SInitialize string `mapstructure:"server.exe.exe-initialize" json:"server.exe.exe-initialize" yaml:"server.exe.exe-initialize"`
Root string `mapstructure:"root" json:"root" yaml:"root"`
WTable string `mapstructure:"web-table" json:"web-table" yaml:"web-table"`
Web string `mapstructure:"web" json:"web" yaml:"web"`
SService string `mapstructure:"server.exe.exe-service" json:"server.exe.exe-service" yaml:"server.exe.exe-service"`
SRequest string `mapstructure:"server.exe.exe-request" json:"server.exe.exe-request" yaml:"server.exe.exe-request"`
WApi string `mapstructure:"web-api" json:"web-api" yaml:"web-api"`
WForm string `mapstructure:"web-form" json:"web-form" yaml:"web-form"`
TransferRestart bool `mapstructure:"transfer-restart" json:"transfer-restart" yaml:"transfer-restart"`
}

9
config/captcha.go Normal file
View File

@ -0,0 +1,9 @@
package config
type Captcha struct {
KeyLong int `mapstructure:"key-long" json:"key-long" yaml:"key-long"` // 验证码长度
ImgWidth int `mapstructure:"img-width" json:"img-width" yaml:"img-width"` // 验证码宽度
ImgHeight int `mapstructure:"img-height" json:"img-height" yaml:"img-height"` // 验证码高度
OpenCaptcha int `mapstructure:"open-captcha" json:"open-captcha" yaml:"open-captcha"` // 防爆破验证码开启此数0代表每次登录都需要验证码其他数字代表错误密码此数如3代表错误三次后出现验证码
OpenCaptchaTimeOut int `mapstructure:"open-captcha-timeout" json:"open-captcha-timeout" yaml:"open-captcha-timeout"` // 防爆破验证码超时时间单位s(秒)
}

34
config/config.go Normal file
View File

@ -0,0 +1,34 @@
package config
type Server struct {
JWT JWT `mapstructure:"jwt" json:"jwt" yaml:"jwt"`
Zap Zap `mapstructure:"zap" json:"zap" yaml:"zap"`
Redis Redis `mapstructure:"redis" json:"redis" yaml:"redis"`
Email Email `mapstructure:"email" json:"email" yaml:"email"`
System System `mapstructure:"system" json:"system" yaml:"system"`
Captcha Captcha `mapstructure:"captcha" json:"captcha" yaml:"captcha"`
// auto
AutoCode Autocode `mapstructure:"autocode" json:"autocode" yaml:"autocode"`
// gorm
Mysql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"`
Mssql Mssql `mapstructure:"mssql" json:"mssql" yaml:"mssql"`
Pgsql Pgsql `mapstructure:"pgsql" json:"pgsql" yaml:"pgsql"`
Oracle Oracle `mapstructure:"oracle" json:"oracle" yaml:"oracle"`
Sqlite Sqlite `mapstructure:"sqlite" json:"sqlite" yaml:"sqlite"`
DBList []SpecializedDB `mapstructure:"db-list" json:"db-list" yaml:"db-list"`
// oss
Local Local `mapstructure:"local" json:"local" yaml:"local"`
Qiniu Qiniu `mapstructure:"qiniu" json:"qiniu" yaml:"qiniu"`
AliyunOSS AliyunOSS `mapstructure:"aliyun-oss" json:"aliyun-oss" yaml:"aliyun-oss"`
HuaWeiObs HuaWeiObs `mapstructure:"hua-wei-obs" json:"hua-wei-obs" yaml:"hua-wei-obs"`
TencentCOS TencentCOS `mapstructure:"tencent-cos" json:"tencent-cos" yaml:"tencent-cos"`
AwsS3 AwsS3 `mapstructure:"aws-s3" json:"aws-s3" yaml:"aws-s3"`
Excel Excel `mapstructure:"excel" json:"excel" yaml:"excel"`
Timer Timer `mapstructure:"timer" json:"timer" yaml:"timer"`
// 跨域配置
Cors CORS `mapstructure:"cors" json:"cors" yaml:"cors"`
MiniApp MiniApp `mapstructure:"mini-app" json:"mini-app" yaml:"mini-app"`
}

14
config/cors.go Normal file
View File

@ -0,0 +1,14 @@
package config
type CORS struct {
Mode string `mapstructure:"mode" json:"mode" yaml:"mode"`
Whitelist []CORSWhitelist `mapstructure:"whitelist" json:"whitelist" yaml:"whitelist"`
}
type CORSWhitelist struct {
AllowOrigin string `mapstructure:"allow-origin" json:"allow-origin" yaml:"allow-origin"`
AllowMethods string `mapstructure:"allow-methods" json:"allow-methods" yaml:"allow-methods"`
AllowHeaders string `mapstructure:"allow-headers" json:"allow-headers" yaml:"allow-headers"`
ExposeHeaders string `mapstructure:"expose-headers" json:"expose-headers" yaml:"expose-headers"`
AllowCredentials bool `mapstructure:"allow-credentials" json:"allow-credentials" yaml:"allow-credentials"`
}

32
config/db_list.go Normal file
View File

@ -0,0 +1,32 @@
package config
type DsnProvider interface {
Dsn() string
}
// Embeded 结构体可以压平到上一层,从而保持 config 文件的结构和原来一样
// 见 playground: https://go.dev/play/p/KIcuhqEoxmY
// GeneralDB 也被 Pgsql 和 Mysql 原样使用
type GeneralDB struct {
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"`
Port string `mapstructure:"port" json:"port" yaml:"port"`
Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
Dbname string `mapstructure:"db-name" json:"db-name" yaml:"db-name"` // 数据库名
Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库密码
Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
Path string `mapstructure:"path" json:"path" yaml:"path"`
Engine string `mapstructure:"engine" json:"engine" yaml:"engine" default:"InnoDB"` //数据库引擎默认InnoDB
LogMode string `mapstructure:"log-mode" json:"log-mode" yaml:"log-mode"` // 是否开启Gorm全局日志
MaxIdleConns int `mapstructure:"max-idle-conns" json:"max-idle-conns" yaml:"max-idle-conns"` // 空闲中的最大连接数
MaxOpenConns int `mapstructure:"max-open-conns" json:"max-open-conns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
Singular bool `mapstructure:"singular" json:"singular" yaml:"singular"` //是否开启全局禁用复数true表示开启
LogZap bool `mapstructure:"log-zap" json:"log-zap" yaml:"log-zap"` // 是否通过zap写入日志文件
}
type SpecializedDB struct {
Type string `mapstructure:"type" json:"type" yaml:"type"`
AliasName string `mapstructure:"alias-name" json:"alias-name" yaml:"alias-name"`
GeneralDB `yaml:",inline" mapstructure:",squash"`
Disable bool `mapstructure:"disable" json:"disable" yaml:"disable"`
}

11
config/email.go Normal file
View File

@ -0,0 +1,11 @@
package config
type Email struct {
To string `mapstructure:"to" json:"to" yaml:"to"` // 收件人:多个以英文逗号分隔 例a@qq.com b@qq.com 正式开发中请把此项目作为参数使用
From string `mapstructure:"from" json:"from" yaml:"from"` // 发件人 你自己要发邮件的邮箱
Host string `mapstructure:"host" json:"host" yaml:"host"` // 服务器地址 例如 smtp.qq.com 请前往QQ或者你要发邮件的邮箱查看其smtp协议
Secret string `mapstructure:"secret" json:"secret" yaml:"secret"` // 密钥 用于登录的密钥 最好不要用邮箱密码 去邮箱smtp申请一个用于登录的密钥
Nickname string `mapstructure:"nickname" json:"nickname" yaml:"nickname"` // 昵称 发件人昵称 通常为自己的邮箱
Port int `mapstructure:"port" json:"port" yaml:"port"` // 端口 请前往QQ或者你要发邮件的邮箱查看其smtp协议 大多为 465
IsSSL bool `mapstructure:"is-ssl" json:"is-ssl" yaml:"is-ssl"` // 是否SSL 是否开启SSL
}

5
config/excel.go Normal file
View File

@ -0,0 +1,5 @@
package config
type Excel struct {
Dir string `mapstructure:"dir" json:"dir" yaml:"dir"`
}

14
config/gorm_mssql.go Normal file
View File

@ -0,0 +1,14 @@
package config
type Mssql struct {
GeneralDB `yaml:",inline" mapstructure:",squash"`
}
// dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm"
func (m *Mssql) Dsn() string {
return "sqlserver://" + m.Username + ":" + m.Password + "@" + m.Path + ":" + m.Port + "?database=" + m.Dbname + "&encrypt=disable"
}
func (m *Mssql) GetLogMode() string {
return m.LogMode
}

13
config/gorm_mysql.go Normal file
View File

@ -0,0 +1,13 @@
package config
type Mysql struct {
GeneralDB `yaml:",inline" mapstructure:",squash"`
}
func (m *Mysql) Dsn() string {
return m.Username + ":" + m.Password + "@tcp(" + m.Path + ":" + m.Port + ")/" + m.Dbname + "?" + m.Config
}
func (m *Mysql) GetLogMode() string {
return m.LogMode
}

14
config/gorm_oracle.go Normal file
View File

@ -0,0 +1,14 @@
package config
type Oracle struct {
GeneralDB `yaml:",inline" mapstructure:",squash"`
}
func (m *Oracle) Dsn() string {
return "oracle://" + m.Username + ":" + m.Password + "@" + m.Path + ":" + m.Port + "/" + m.Dbname + "?" + m.Config
}
func (m *Oracle) GetLogMode() string {
return m.LogMode
}

21
config/gorm_pgsql.go Normal file
View File

@ -0,0 +1,21 @@
package config
type Pgsql struct {
GeneralDB `yaml:",inline" mapstructure:",squash"`
}
// Dsn 基于配置文件获取 dsn
// Author [SliverHorn](https://github.com/SliverHorn)
func (p *Pgsql) Dsn() string {
return "host=" + p.Path + " user=" + p.Username + " password=" + p.Password + " dbname=" + p.Dbname + " port=" + p.Port + " " + p.Config
}
// LinkDsn 根据 dbname 生成 dsn
// Author [SliverHorn](https://github.com/SliverHorn)
func (p *Pgsql) LinkDsn(dbname string) string {
return "host=" + p.Path + " user=" + p.Username + " password=" + p.Password + " dbname=" + dbname + " port=" + p.Port + " " + p.Config
}
func (m *Pgsql) GetLogMode() string {
return m.LogMode
}

17
config/gorm_sqlite.go Normal file
View File

@ -0,0 +1,17 @@
package config
import (
"path/filepath"
)
type Sqlite struct {
GeneralDB `yaml:",inline" mapstructure:",squash"`
}
func (s *Sqlite) Dsn() string {
return filepath.Join(s.Path, s.Dbname+".db")
}
func (s *Sqlite) GetLogMode() string {
return s.LogMode
}

8
config/jwt.go Normal file
View File

@ -0,0 +1,8 @@
package config
type JWT struct {
SigningKey string `mapstructure:"signing-key" json:"signing-key" yaml:"signing-key"` // jwt签名
ExpiresTime string `mapstructure:"expires-time" json:"expires-time" yaml:"expires-time"` // 过期时间
BufferTime string `mapstructure:"buffer-time" json:"buffer-time" yaml:"buffer-time"` // 缓冲时间
Issuer string `mapstructure:"issuer" json:"issuer" yaml:"issuer"` // 签发者
}

10
config/oss_aliyun.go Normal file
View File

@ -0,0 +1,10 @@
package config
type AliyunOSS struct {
Endpoint string `mapstructure:"endpoint" json:"endpoint" yaml:"endpoint"`
AccessKeyId string `mapstructure:"access-key-id" json:"access-key-id" yaml:"access-key-id"`
AccessKeySecret string `mapstructure:"access-key-secret" json:"access-key-secret" yaml:"access-key-secret"`
BucketName string `mapstructure:"bucket-name" json:"bucket-name" yaml:"bucket-name"`
BucketUrl string `mapstructure:"bucket-url" json:"bucket-url" yaml:"bucket-url"`
BasePath string `mapstructure:"base-path" json:"base-path" yaml:"base-path"`
}

13
config/oss_aws.go Normal file
View File

@ -0,0 +1,13 @@
package config
type AwsS3 struct {
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket"`
Region string `mapstructure:"region" json:"region" yaml:"region"`
Endpoint string `mapstructure:"endpoint" json:"endpoint" yaml:"endpoint"`
SecretID string `mapstructure:"secret-id" json:"secret-id" yaml:"secret-id"`
SecretKey string `mapstructure:"secret-key" json:"secret-key" yaml:"secret-key"`
BaseURL string `mapstructure:"base-url" json:"base-url" yaml:"base-url"`
PathPrefix string `mapstructure:"path-prefix" json:"path-prefix" yaml:"path-prefix"`
S3ForcePathStyle bool `mapstructure:"s3-force-path-style" json:"s3-force-path-style" yaml:"s3-force-path-style"`
DisableSSL bool `mapstructure:"disable-ssl" json:"disable-ssl" yaml:"disable-ssl"`
}

9
config/oss_huawei.go Normal file
View File

@ -0,0 +1,9 @@
package config
type HuaWeiObs struct {
Path string `mapstructure:"path" json:"path" yaml:"path"`
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket"`
Endpoint string `mapstructure:"endpoint" json:"endpoint" yaml:"endpoint"`
AccessKey string `mapstructure:"access-key" json:"access-key" yaml:"access-key"`
SecretKey string `mapstructure:"secret-key" json:"secret-key" yaml:"secret-key"`
}

6
config/oss_local.go Normal file
View File

@ -0,0 +1,6 @@
package config
type Local struct {
Path string `mapstructure:"path" json:"path" yaml:"path"` // 本地文件访问路径
StorePath string `mapstructure:"store-path" json:"store-path" yaml:"store-path"` // 本地文件存储路径
}

11
config/oss_qiniu.go Normal file
View File

@ -0,0 +1,11 @@
package config
type Qiniu struct {
Zone string `mapstructure:"zone" json:"zone" yaml:"zone"` // 存储区域
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket"` // 空间名称
ImgPath string `mapstructure:"img-path" json:"img-path" yaml:"img-path"` // CDN加速域名
AccessKey string `mapstructure:"access-key" json:"access-key" yaml:"access-key"` // 秘钥AK
SecretKey string `mapstructure:"secret-key" json:"secret-key" yaml:"secret-key"` // 秘钥SK
UseHTTPS bool `mapstructure:"use-https" json:"use-https" yaml:"use-https"` // 是否使用https
UseCdnDomains bool `mapstructure:"use-cdn-domains" json:"use-cdn-domains" yaml:"use-cdn-domains"` // 上传是否使用CDN上传加速
}

10
config/oss_tencent.go Normal file
View File

@ -0,0 +1,10 @@
package config
type TencentCOS struct {
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket"`
Region string `mapstructure:"region" json:"region" yaml:"region"`
SecretID string `mapstructure:"secret-id" json:"secret-id" yaml:"secret-id"`
SecretKey string `mapstructure:"secret-key" json:"secret-key" yaml:"secret-key"`
BaseURL string `mapstructure:"base-url" json:"base-url" yaml:"base-url"`
PathPrefix string `mapstructure:"path-prefix" json:"path-prefix" yaml:"path-prefix"`
}

7
config/redis.go Normal file
View File

@ -0,0 +1,7 @@
package config
type Redis struct {
Addr string `mapstructure:"addr" json:"addr" yaml:"addr"` // 服务器地址:端口
Password string `mapstructure:"password" json:"password" yaml:"password"` // 密码
DB int `mapstructure:"db" json:"db" yaml:"db"` // redis的哪个数据库
}

13
config/system.go Normal file
View File

@ -0,0 +1,13 @@
package config
type System struct {
Env string `mapstructure:"env" json:"env" yaml:"env"` // 环境值
DbType string `mapstructure:"db-type" json:"db-type" yaml:"db-type"` // 数据库类型:mysql(默认)|sqlite|sqlserver|postgresql
OssType string `mapstructure:"oss-type" json:"oss-type" yaml:"oss-type"` // Oss类型
RouterPrefix string `mapstructure:"router-prefix" json:"router-prefix" yaml:"router-prefix"`
Addr int `mapstructure:"addr" json:"addr" yaml:"addr"` // 端口值
LimitCountIP int `mapstructure:"iplimit-count" json:"iplimit-count" yaml:"iplimit-count"`
LimitTimeIP int `mapstructure:"iplimit-time" json:"iplimit-time" yaml:"iplimit-time"`
UseMultipoint bool `mapstructure:"use-multipoint" json:"use-multipoint" yaml:"use-multipoint"` // 多点登录拦截
UseRedis bool `mapstructure:"use-redis" json:"use-redis" yaml:"use-redis"` // 使用redis
}

15
config/timer.go Normal file
View File

@ -0,0 +1,15 @@
package config
type Timer struct {
Spec string `mapstructure:"spec" json:"spec" yaml:"spec"` // CRON表达式
Detail []Detail `mapstructure:"detail" json:"detail" yaml:"detail"`
Start bool `mapstructure:"start" json:"start" yaml:"start"` // 是否启用
WithSeconds bool `mapstructure:"with_seconds" json:"with_seconds" yaml:"with_seconds"` // 是否精确到秒
}
type Detail struct {
TableName string `mapstructure:"tableName" json:"tableName" yaml:"tableName"` // 需要清理的表名
CompareField string `mapstructure:"compareField" json:"compareField" yaml:"compareField"` // 需要比较时间的字段
Interval string `mapstructure:"interval" json:"interval" yaml:"interval"` // 时间间隔
}

23
config/wechat.go Normal file
View File

@ -0,0 +1,23 @@
package config
// MiniApp 微信小程序配置
type MiniApp struct {
AppId string `mapstructure:"app-id" yaml:"app-id"`
AppSecret string `mapstructure:"app-secret" yaml:"app-secret"`
TemplateID string `mapstructure:"template-id" yaml:"template-id"`
}
// 微信支付配置
type wechatPayConfig struct {
MchId string `mapstructure:"mchId" yaml:"mchId"` // 商户号
SerialNo string `mapstructure:"serialNo" yaml:"serialNo"` // 商户API证书的证书序列号
ApiV3Key string `mapstructure:"apiV3Key" yaml:"apiV3Key"` // 支付key
PrivateKey string `mapstructure:"privateKey" yaml:"privateKey"` // 支付私钥绝对路径
}
// api密钥配置
type CapiConfig struct {
AppId string `mapstructure:"app-id" yaml:"app-id"` // APP ID
SecretId string `mapstructure:"secret-id" yaml:"secret-id"` // Secret ID
SecretKey string `mapstructure:"secret-key" yaml:"secret-key"` // Secret Key
}

60
config/zap.go Normal file
View File

@ -0,0 +1,60 @@
package config
import (
"go.uber.org/zap/zapcore"
"strings"
)
type Zap struct {
Level string `mapstructure:"level" json:"level" yaml:"level"` // 级别
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` // 日志前缀
Format string `mapstructure:"format" json:"format" yaml:"format"` // 输出
Director string `mapstructure:"director" json:"director" yaml:"director"` // 日志文件夹
EncodeLevel string `mapstructure:"encode-level" json:"encode-level" yaml:"encode-level"` // 编码级
StacktraceKey string `mapstructure:"stacktrace-key" json:"stacktrace-key" yaml:"stacktrace-key"` // 栈名
MaxAge int `mapstructure:"max-age" json:"max-age" yaml:"max-age"` // 日志留存时间
ShowLine bool `mapstructure:"show-line" json:"show-line" yaml:"show-line"` // 显示行
LogInConsole bool `mapstructure:"log-in-console" json:"log-in-console" yaml:"log-in-console"` // 输出控制台
}
// ZapEncodeLevel 根据 EncodeLevel 返回 zapcore.LevelEncoder
// Author [SliverHorn](https://github.com/SliverHorn)
func (z *Zap) ZapEncodeLevel() zapcore.LevelEncoder {
switch {
case z.EncodeLevel == "LowercaseLevelEncoder": // 小写编码器(默认)
return zapcore.LowercaseLevelEncoder
case z.EncodeLevel == "LowercaseColorLevelEncoder": // 小写编码器带颜色
return zapcore.LowercaseColorLevelEncoder
case z.EncodeLevel == "CapitalLevelEncoder": // 大写编码器
return zapcore.CapitalLevelEncoder
case z.EncodeLevel == "CapitalColorLevelEncoder": // 大写编码器带颜色
return zapcore.CapitalColorLevelEncoder
default:
return zapcore.LowercaseLevelEncoder
}
}
// TransportLevel 根据字符串转化为 zapcore.Level
// Author [SliverHorn](https://github.com/SliverHorn)
func (z *Zap) TransportLevel() zapcore.Level {
z.Level = strings.ToLower(z.Level)
switch z.Level {
case "debug":
return zapcore.DebugLevel
case "info":
return zapcore.InfoLevel
case "warn":
return zapcore.WarnLevel
case "error":
return zapcore.WarnLevel
case "dpanic":
return zapcore.DPanicLevel
case "panic":
return zapcore.PanicLevel
case "fatal":
return zapcore.FatalLevel
default:
return zapcore.DebugLevel
}
}

128
config2.yaml Normal file
View File

@ -0,0 +1,128 @@
aliyun-oss:
endpoint: oss-cn-chengdu.aliyuncs.com
access-key-id: LTAI5tFHes6HBWJFUjuPwHso
access-key-secret: qXuWtEJvYEQvj9yhkmLYfRxHShheYa
bucket-name: jmyl-app
bucket-url: https://jmyl-app.oss-cn-chengdu.aliyuncs.com
base-path: miniapp
autocode:
server-model: /model/%s
server-router: /router/%s
server: /server.exe.exe
server-api: /api/v1/%s
server-plug: /plugin/%s
server-initialize: /initialize
root: C:\Users\Administrator\Desktop
web-table: /view
web: /web/src
server-service: /service/%s
server-request: /model/%s/request/
web-api: /api
web-form: /view
transfer-restart: true
captcha:
key-long: 4
img-width: 240
img-height: 80
open-captcha: 0
open-captcha-timeout: 3600
cors:
mode: strict-whitelist
whitelist:
- allow-origin: example1.com
allow-methods: POST, GET
allow-headers: Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id
expose-headers: Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type
allow-credentials: true
- allow-origin: example2.com
allow-methods: GET, POST
allow-headers: content-type
expose-headers: Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type
allow-credentials: true
db-list:
- type: ""
alias-name: ""
prefix: ""
port: ""
config: ""
db-name: ""
username: ""
password: ""
path: ""
engine: ""
log-mode: ""
max-idle-conns: 10
max-open-conns: 100
singular: false
log-zap: false
disable: true
email:
to: xxx@qq.com
from: xxx@163.com
host: smtp.163.com
secret: xxx
nickname: test
port: 465
is-ssl: true
excel:
dir: ./resource/excel/
jwt:
signing-key: f2b1b2af-c8f1-43cf-88e4-40b0a64b5487
expires-time: 7d
buffer-time: 1d
issuer: qmPlus
local:
path: uploads/file
store-path: uploads/file
mini-app:
app-id: wxaaf66dbb5c3983b3
app-secret: 0abba24dbff43febba1e551651f693b4
mysql:
prefix: ""
port: "3306"
config: charset=utf8mb4&parseTime=True&loc=Local
db-name: jmyl
username: jmyl
password: Jmyl123123
path: 101.35.50.11
engine: ""
log-mode: error
max-idle-conns: 10
max-open-conns: 100
singular: false
log-zap: false
redis:
addr: 101.35.50.11:6379
password: "loser7659"
db: 0
system:
env: public
db-type: mysql
oss-type: aliyun-oss
router-prefix: ""
addr: 8888
iplimit-count: 15000
iplimit-time: 3600
use-multipoint: false
use-redis: true
timer:
spec: '@daily'
detail:
- tableName: sys_operation_records
compareField: created_at
interval: 2160h
- tableName: jwt_blacklists
compareField: created_at
interval: 168h
start: true
with_seconds: false
zap:
level: info
prefix: '[miniapp]'
format: console
director: log
encode-level: LowercaseColorLevelEncoder
stacktrace-key: stacktrace
max-age: 0
show-line: true
log-in-console: true

View File

@ -0,0 +1,9 @@
package internal
const (
ConfigEnv = "GVA_CONFIG"
ConfigDefaultFile = "config.yaml"
ConfigTestFile = "config.test.yaml"
ConfigDebugFile = "config.debug.yaml"
ConfigReleaseFile = "config.release.yaml"
)

97
core/internal/cutter.go Normal file
View File

@ -0,0 +1,97 @@
package internal
import (
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
)
type Cutter struct {
level string // 日志级别(debug, info, warn, error, dpanic, panic, fatal)
format string // 时间格式(2006-01-02)
Director string // 日志文件夹
file *os.File // 文件句柄
mutex *sync.RWMutex // 读写锁
}
type CutterOption func(*Cutter)
// WithCutterFormat 设置时间格式
func WithCutterFormat(format string) CutterOption {
return func(c *Cutter) {
c.format = format
}
}
func NewCutter(director string, level string, options ...CutterOption) *Cutter {
rotate := &Cutter{
level: level,
Director: director,
mutex: new(sync.RWMutex),
}
for i := 0; i < len(options); i++ {
options[i](rotate)
}
return rotate
}
// Write satisfies the io.Writer interface. It writes to the
// appropriate file handle that is currently being used.
// If we have reached rotation time, the target file gets
// automatically rotated, and also purged if necessary.
func (c *Cutter) Write(bytes []byte) (n int, err error) {
c.mutex.Lock()
defer func() {
if c.file != nil {
_ = c.file.Close()
c.file = nil
}
c.mutex.Unlock()
}()
var business string
if strings.Contains(string(bytes), "business") {
var compile *regexp.Regexp
compile, err = regexp.Compile(`{"business": "([^,]+)"}`)
if err != nil {
return 0, err
}
if compile.Match(bytes) {
finds := compile.FindSubmatch(bytes)
business = string(finds[len(finds)-1])
bytes = compile.ReplaceAll(bytes, []byte(""))
}
compile, err = regexp.Compile(`"business": "([^,]+)"`)
if err != nil {
return 0, err
}
if compile.Match(bytes) {
finds := compile.FindSubmatch(bytes)
business = string(finds[len(finds)-1])
bytes = compile.ReplaceAll(bytes, []byte(""))
}
}
format := time.Now().Format(c.format)
formats := make([]string, 0, 4)
formats = append(formats, c.Director)
if format != "" {
formats = append(formats, format)
}
if business != "" {
formats = append(formats, business)
}
formats = append(formats, c.level+".log")
filename := filepath.Join(formats...)
dirname := filepath.Dir(filename)
err = os.MkdirAll(dirname, 0755)
if err != nil {
return 0, err
}
c.file, err = os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return 0, err
}
return c.file.Write(bytes)
}

View File

@ -0,0 +1,21 @@
package internal
import (
"go.uber.org/zap/zapcore"
"miniapp/global"
"os"
)
var FileRotatelogs = new(fileRotatelogs)
type fileRotatelogs struct{}
// GetWriteSyncer 获取 zapcore.WriteSyncer
// Author [SliverHorn](https://github.com/SliverHorn)
func (r *fileRotatelogs) GetWriteSyncer(level string) zapcore.WriteSyncer {
fileWriter := NewCutter(global.GVA_CONFIG.Zap.Director, level, WithCutterFormat("2006-01-02"))
if global.GVA_CONFIG.Zap.LogInConsole {
return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter))
}
return zapcore.AddSync(fileWriter)
}

101
core/internal/zap.go Normal file
View File

@ -0,0 +1,101 @@
package internal
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"miniapp/global"
"time"
)
var Zap = new(_zap)
type _zap struct{}
// GetEncoder 获取 zapcore.Encoder
// Author [SliverHorn](https://github.com/SliverHorn)
func (z *_zap) GetEncoder() zapcore.Encoder {
if global.GVA_CONFIG.Zap.Format == "json" {
return zapcore.NewJSONEncoder(z.GetEncoderConfig())
}
return zapcore.NewConsoleEncoder(z.GetEncoderConfig())
}
// GetEncoderConfig 获取zapcore.EncoderConfig
// Author [SliverHorn](https://github.com/SliverHorn)
func (z *_zap) GetEncoderConfig() zapcore.EncoderConfig {
return zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "level",
TimeKey: "time",
NameKey: "logger",
CallerKey: "caller",
StacktraceKey: global.GVA_CONFIG.Zap.StacktraceKey,
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: global.GVA_CONFIG.Zap.ZapEncodeLevel(),
EncodeTime: z.CustomTimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.FullCallerEncoder,
}
}
// GetEncoderCore 获取Encoder的 zapcore.Core
// Author [SliverHorn](https://github.com/SliverHorn)
func (z *_zap) GetEncoderCore(l zapcore.Level, level zap.LevelEnablerFunc) zapcore.Core {
writer := FileRotatelogs.GetWriteSyncer(l.String()) // 日志分割
return zapcore.NewCore(z.GetEncoder(), writer, level)
}
// CustomTimeEncoder 自定义日志输出时间格式
// Author [SliverHorn](https://github.com/SliverHorn)
func (z *_zap) CustomTimeEncoder(t time.Time, encoder zapcore.PrimitiveArrayEncoder) {
encoder.AppendString(global.GVA_CONFIG.Zap.Prefix + t.Format("2006/01/02 - 15:04:05.000"))
}
// GetZapCores 根据配置文件的Level获取 []zapcore.Core
// Author [SliverHorn](https://github.com/SliverHorn)
func (z *_zap) GetZapCores() []zapcore.Core {
cores := make([]zapcore.Core, 0, 7)
for level := global.GVA_CONFIG.Zap.TransportLevel(); level <= zapcore.FatalLevel; level++ {
cores = append(cores, z.GetEncoderCore(level, z.GetLevelPriority(level)))
}
return cores
}
// GetLevelPriority 根据 zapcore.Level 获取 zap.LevelEnablerFunc
// Author [SliverHorn](https://github.com/SliverHorn)
func (z *_zap) GetLevelPriority(level zapcore.Level) zap.LevelEnablerFunc {
switch level {
case zapcore.DebugLevel:
return func(level zapcore.Level) bool { // 调试级别
return level == zap.DebugLevel
}
case zapcore.InfoLevel:
return func(level zapcore.Level) bool { // 日志级别
return level == zap.InfoLevel
}
case zapcore.WarnLevel:
return func(level zapcore.Level) bool { // 警告级别
return level == zap.WarnLevel
}
case zapcore.ErrorLevel:
return func(level zapcore.Level) bool { // 错误级别
return level == zap.ErrorLevel
}
case zapcore.DPanicLevel:
return func(level zapcore.Level) bool { // dpanic级别
return level == zap.DPanicLevel
}
case zapcore.PanicLevel:
return func(level zapcore.Level) bool { // panic级别
return level == zap.PanicLevel
}
case zapcore.FatalLevel:
return func(level zapcore.Level) bool { // 终止级别
return level == zap.FatalLevel
}
default:
return func(level zapcore.Level) bool { // 调试级别
return level == zap.DebugLevel
}
}
}

39
core/server.go Normal file
View File

@ -0,0 +1,39 @@
package core
import (
"fmt"
"time"
"go.uber.org/zap"
"miniapp/global"
"miniapp/initialize"
"miniapp/service/system"
)
type server interface {
ListenAndServe() error
}
func RunWindowsServer() {
if global.GVA_CONFIG.System.UseMultipoint || global.GVA_CONFIG.System.UseRedis {
// 初始化redis服务
initialize.Redis()
}
// 从db加载jwt数据
if global.GVA_DB != nil {
system.LoadAll()
}
Router := initialize.Routers()
Router.Static("/form-generator", "./resource/page")
address := fmt.Sprintf(":%d", global.GVA_CONFIG.System.Addr)
s := initServer(address, Router)
// 保证文本顺序输出
// In order to ensure that the text order output can be deleted
time.Sleep(10 * time.Microsecond)
global.GVA_LOG.Info("server run success on ", zap.String("address", address))
global.GVA_LOG.Error(s.ListenAndServe().Error())
}

19
core/server_other.go Normal file
View File

@ -0,0 +1,19 @@
//go:build !windows
// +build !windows
package core
import (
"time"
"github.com/fvbock/endless"
"github.com/gin-gonic/gin"
)
func initServer(address string, router *gin.Engine) server {
s := endless.NewServer(address, router)
s.ReadHeaderTimeout = 20 * time.Second
s.WriteTimeout = 20 * time.Second
s.MaxHeaderBytes = 1 << 20
return s
}

21
core/server_win.go Normal file
View File

@ -0,0 +1,21 @@
//go:build windows
// +build windows
package core
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func initServer(address string, router *gin.Engine) server {
return &http.Server{
Addr: address,
Handler: router,
ReadTimeout: 20 * time.Second,
WriteTimeout: 20 * time.Second,
MaxHeaderBytes: 1 << 20,
}
}

74
core/viper.go Normal file
View File

@ -0,0 +1,74 @@
package core
import (
"flag"
"fmt"
"github.com/gin-gonic/gin"
"miniapp/core/internal"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"miniapp/global"
_ "miniapp/packfile"
)
// Viper //
// 优先级: 命令行 > 环境变量 > 默认值
// Author [SliverHorn](https://github.com/SliverHorn)
func Viper(path ...string) *viper.Viper {
var config string
if len(path) == 0 {
flag.StringVar(&config, "c", "", "choose config file.")
flag.Parse()
if config == "" { // 判断命令行参数是否为空
if configEnv := os.Getenv(internal.ConfigEnv); configEnv == "" { // 判断 internal.ConfigEnv 常量存储的环境变量是否为空
switch gin.Mode() {
case gin.DebugMode:
config = internal.ConfigDefaultFile
fmt.Printf("您正在使用gin模式的%s环境名称,config的路径为%s\n", gin.EnvGinMode, internal.ConfigDefaultFile)
case gin.ReleaseMode:
config = internal.ConfigReleaseFile
fmt.Printf("您正在使用gin模式的%s环境名称,config的路径为%s\n", gin.EnvGinMode, internal.ConfigReleaseFile)
case gin.TestMode:
config = internal.ConfigTestFile
fmt.Printf("您正在使用gin模式的%s环境名称,config的路径为%s\n", gin.EnvGinMode, internal.ConfigTestFile)
}
} else { // internal.ConfigEnv 常量存储的环境变量不为空 将值赋值于config
config = configEnv
fmt.Printf("您正在使用%s环境变量,config的路径为%s\n", internal.ConfigEnv, config)
}
} else { // 命令行参数不为空 将值赋值于config
fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%s\n", config)
}
} else { // 函数传递的可变参数的第一个值赋值于config
config = path[0]
fmt.Printf("您正在使用func Viper()传递的值,config的路径为%s\n", config)
}
v := viper.New()
v.SetConfigFile(config)
v.SetConfigType("yaml")
err := v.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
if err = v.Unmarshal(&global.GVA_CONFIG); err != nil {
fmt.Println(err)
}
})
if err = v.Unmarshal(&global.GVA_CONFIG); err != nil {
fmt.Println(err)
}
// root 适配性 根据root位置去找到对应迁移位置,保证root路径有效
global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
return v
}

28
core/zap.go Normal file
View File

@ -0,0 +1,28 @@
package core
import (
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"miniapp/core/internal"
"miniapp/global"
"miniapp/utils"
"os"
)
// Zap 获取 zap.Logger
// Author [SliverHorn](https://github.com/SliverHorn)
func Zap() (logger *zap.Logger) {
if ok, _ := utils.PathExists(global.GVA_CONFIG.Zap.Director); !ok { // 判断是否有Director文件夹
fmt.Printf("create %v directory\n", global.GVA_CONFIG.Zap.Director)
_ = os.Mkdir(global.GVA_CONFIG.Zap.Director, os.ModePerm)
}
cores := internal.Zap.GetZapCores()
logger = zap.New(zapcore.NewTee(cores...))
if global.GVA_CONFIG.Zap.ShowLine {
logger = logger.WithOptions(zap.AddCaller())
}
return logger
}

132
docker/config.docker.yaml Normal file
View File

@ -0,0 +1,132 @@
aliyun-oss:
endpoint: oss-cn-chengdu.aliyuncs.com
access-key-id: LTAI5tFHes6HBWJFUjuPwHso
access-key-secret: qXuWtEJvYEQvj9yhkmLYfRxHShheYa
bucket-name: jmyl-app
bucket-url: https://jmyl-app.oss-cn-chengdu.aliyuncs.com
base-path: miniapp
autocode:
server-model: /model/%s
server-router: /router/%s
server: /server.exe.exe
server-api: /api/v1/%s
server-plug: /plugin/%s
server-initialize: /initialize
root: C:\Users\Administrator\Desktop
web-table: /view
web: /web/src
server-service: /service/%s
server-request: /model/%s/request/
web-api: /api
web-form: /view
transfer-restart: true
captcha:
key-long: 4
img-width: 240
img-height: 80
open-captcha: 0
open-captcha-timeout: 3600
cors:
mode: strict-whitelist
whitelist:
- allow-origin: example1.com
allow-methods: POST, GET
allow-headers: Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id
expose-headers: Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type
allow-credentials: true
- allow-origin: example2.com
allow-methods: GET, POST
allow-headers: content-type
expose-headers: Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type
allow-credentials: true
db-list:
- type: ""
alias-name: ""
prefix: ""
port: ""
config: ""
db-name: ""
username: ""
password: ""
path: ""
engine: ""
log-mode: ""
max-idle-conns: 10
max-open-conns: 100
singular: false
log-zap: false
disable: true
email:
to: xxx@qq.com
from: xxx@163.com
host: smtp.163.com
secret: xxx
nickname: test
port: 465
is-ssl: true
excel:
dir: ./resource/excel/
jwt:
signing-key: f2b1b2af-c8f1-43cf-88e4-40b0a64b5487
expires-time: 7d
buffer-time: 1d
issuer: qmPlus
local:
path: uploads/file
store-path: uploads/file
mini-app:
app-id: wxaaf66dbb5c3983b3
app-secret: 0abba24dbff43febba1e551651f693b4
mysql:
prefix: ""
port: "3307"
config: charset=utf8mb4&parseTime=True&loc=Local
db-name: mini_app
username: root
password: Jmyl123123
path: 47.113.103.195
engine: ""
log-mode: error
max-idle-conns: 10
max-open-conns: 100
singular: false
log-zap: false
redis:
addr: 127.0.0.1:6379
password: "Jmyl123123"
db: 0
system:
env: public
db-type: mysql
oss-type: aliyun-oss
router-prefix: ""
addr: 8888
iplimit-count: 15000
iplimit-time: 3600
use-multipoint: false
use-redis: true
timer:
spec: '@daily'
detail:
- tableName: sys_operation_records
compareField: created_at
interval: 2160h
- tableName: jwt_blacklists
compareField: created_at
interval: 168h
start: true
with_seconds: false
zap:
level: info
prefix: '[miniapp]'
format: console
director: log
encode-level: LowercaseColorLevelEncoder
stacktrace-key: stacktrace
max-age: 0
show-line: true
log-in-console: true

6882
docs/docs.go Normal file

File diff suppressed because it is too large Load Diff

6916
docs/swagger.json Normal file

File diff suppressed because it is too large Load Diff

4196
docs/swagger.yaml Normal file

File diff suppressed because it is too large Load Diff

55
global/global.go Normal file
View File

@ -0,0 +1,55 @@
package global
import (
"miniapp/utils/flashtext"
"sync"
"github.com/songzhibin97/gkit/cache/local_cache"
"miniapp/utils/timer"
"golang.org/x/sync/singleflight"
"go.uber.org/zap"
"miniapp/config"
"github.com/redis/go-redis/v9"
"github.com/spf13/viper"
"gorm.io/gorm"
)
var (
GVA_DB *gorm.DB
GVA_DBList map[string]*gorm.DB
GVA_REDIS *redis.Client
GVA_CONFIG config.Server
GVA_VP *viper.Viper
// GVA_LOG *oplogging.Logger
GVA_LOG *zap.Logger
GVA_Timer timer.Timer = timer.NewTimerTask()
GVA_Concurrency_Control = &singleflight.Group{}
BlackCache local_cache.Cache
lock sync.RWMutex
// GVA_Kp 关键词处理器
GVA_Kp *flashtext.KeywordProcessor
)
// GetGlobalDBByDBName 通过名称获取db list中的db
func GetGlobalDBByDBName(dbname string) *gorm.DB {
lock.RLock()
defer lock.RUnlock()
return GVA_DBList[dbname]
}
// MustGetGlobalDBByDBName 通过名称获取db 如果不存在则panic
func MustGetGlobalDBByDBName(dbname string) *gorm.DB {
lock.RLock()
defer lock.RUnlock()
db, ok := GVA_DBList[dbname]
if !ok || db == nil {
panic("db no init")
}
return db
}

14
global/model.go Normal file
View File

@ -0,0 +1,14 @@
package global
import (
"time"
"gorm.io/gorm"
)
type GVA_MODEL struct {
ID uint `gorm:"primarykey"` // 主键ID
CreatedAt time.Time // 创建时间
UpdatedAt time.Time // 更新时间
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` // 删除时间
}

161
go.mod Normal file
View File

@ -0,0 +1,161 @@
module miniapp
go 1.20
require (
git.echol.cn/loser/logger v1.0.15
github.com/aliyun/aliyun-oss-go-sdk v2.2.7+incompatible
github.com/aws/aws-sdk-go v1.44.307
github.com/casbin/casbin/v2 v2.71.1
github.com/casbin/gorm-adapter/v3 v3.18.0
github.com/duke-git/lancet/v2 v2.2.7
github.com/flipped-aurora/gin-vue-admin/server v0.0.0-20240108135025-84b44eef9176
github.com/flipped-aurora/ws v1.0.2
github.com/fsnotify/fsnotify v1.6.0
github.com/fvbock/endless v0.0.0-20170109170031-447134032cb6
github.com/gin-gonic/gin v1.9.1
github.com/glebarez/sqlite v1.8.0
github.com/go-co-op/gocron v1.13.0
github.com/go-oauth2/oauth2/v4 v4.5.2
github.com/go-oauth2/redis/v4 v4.1.1
github.com/go-redis/redis/v8 v8.11.4
github.com/go-sql-driver/mysql v1.7.1
github.com/gofrs/uuid/v5 v5.0.0
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/google/uuid v1.6.0
github.com/gookit/color v1.5.4
github.com/huaweicloud/huaweicloud-sdk-go-obs v3.21.8+incompatible
github.com/jordan-wright/email v0.0.0-20200824153738-3f5bafa1cd84
github.com/medivhzhan/weapp/v3 v3.6.19
github.com/mojocn/base64Captcha v1.3.5
github.com/otiai10/copy v1.7.0
github.com/pkg/errors v0.9.1
github.com/qiniu/api.v7/v7 v7.4.1
github.com/qiniu/qmgo v1.1.8
github.com/redis/go-redis/v9 v9.0.5
github.com/robfig/cron/v3 v3.0.1
github.com/sashabaranov/go-openai v1.14.1
github.com/shirou/gopsutil/v3 v3.23.6
github.com/songzhibin97/gkit v1.2.11
github.com/spf13/viper v1.16.0
github.com/stretchr/testify v1.9.0
github.com/swaggo/files v1.0.1
github.com/swaggo/gin-swagger v1.6.0
github.com/swaggo/swag v1.16.2
github.com/tencentyun/cos-go-sdk-v5 v0.7.42
github.com/unrolled/secure v1.13.0
github.com/xuri/excelize/v2 v2.8.0
go.mongodb.org/mongo-driver v1.12.1
go.uber.org/zap v1.24.0
golang.org/x/crypto v0.16.0
golang.org/x/sync v0.5.0
golang.org/x/text v0.14.0
gorm.io/driver/mysql v1.5.1
gorm.io/driver/postgres v1.5.2
gorm.io/driver/sqlserver v1.5.1
gorm.io/gorm v1.25.2
nhooyr.io/websocket v1.8.7
)
require (
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/bytedance/sonic v1.9.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/clbanning/mxj v1.8.4 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fatih/color v1.15.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/glebarez/go-sqlite v1.21.1 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-openapi/jsonpointer v0.20.2 // indirect
github.com/go-openapi/jsonreference v0.20.3 // indirect
github.com/go-openapi/spec v0.20.12 // indirect
github.com/go-openapi/swag v0.22.5 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang-jwt/jwt v3.2.1+incompatible // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/go-querystring v1.0.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgx/v5 v5.3.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.15.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/microsoft/go-mssqldb v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/montanaflynn/stats v0.7.0 // indirect
github.com/mozillazg/go-httpheader v0.2.1 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.3 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
github.com/tidwall/btree v0.0.0-20191029221954-400434d76274 // indirect
github.com/tidwall/buntdb v1.1.2 // indirect
github.com/tidwall/gjson v1.12.1 // indirect
github.com/tidwall/grect v0.0.0-20161006141115-ba9a043346eb // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tidwall/rtree v0.0.0-20180113144539-6cd427091e0e // indirect
github.com/tidwall/tinyqueue v0.0.0-20180302190814-1e39f5511563 // indirect
github.com/tklauser/go-sysconf v0.3.11 // indirect
github.com/tklauser/numcpus v0.6.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca // indirect
github.com/xuri/nfp v0.0.0-20230819163627-dc951e3ffe1a // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
github.com/yusufpapurcu/wmi v1.2.3 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.8.0 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/image v0.11.0 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/time v0.1.0 // indirect
golang.org/x/tools v0.16.1 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/plugin/dbresolver v1.4.1 // indirect
modernc.org/libc v1.24.1 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.6.0 // indirect
modernc.org/sqlite v1.23.0 // indirect
)

1032
go.sum Normal file

File diff suppressed because it is too large Load Diff

36
initialize/db_list.go Normal file
View File

@ -0,0 +1,36 @@
package initialize
import (
"gorm.io/gorm"
"miniapp/config"
"miniapp/global"
)
const sys = "system"
func DBList() {
dbMap := make(map[string]*gorm.DB)
for _, info := range global.GVA_CONFIG.DBList {
if info.Disable {
continue
}
switch info.Type {
case "mysql":
dbMap[info.AliasName] = GormMysqlByConfig(config.Mysql{GeneralDB: info.GeneralDB})
case "mssql":
dbMap[info.AliasName] = GormMssqlByConfig(config.Mssql{GeneralDB: info.GeneralDB})
case "pgsql":
dbMap[info.AliasName] = GormPgSqlByConfig(config.Pgsql{GeneralDB: info.GeneralDB})
case "oracle":
dbMap[info.AliasName] = GormOracleByConfig(config.Oracle{GeneralDB: info.GeneralDB})
default:
continue
}
}
// 做特殊判断,是否有迁移
// 适配低版本迁移多数据库版本
if sysDB, ok := dbMap[sys]; ok {
global.GVA_DB = sysDB
}
global.GVA_DBList = dbMap
}

100
initialize/ensure_tables.go Normal file
View File

@ -0,0 +1,100 @@
package initialize
import (
"context"
adapter "github.com/casbin/gorm-adapter/v3"
"gorm.io/gorm"
"miniapp/model/example"
sysModel "miniapp/model/system"
"miniapp/service/system"
)
const initOrderEnsureTables = system.InitOrderExternal - 1
type ensureTables struct{}
// auto run
func init() {
system.RegisterInit(initOrderEnsureTables, &ensureTables{})
}
func (ensureTables) InitializerName() string {
return "ensure_tables_created"
}
func (e *ensureTables) InitializeData(ctx context.Context) (next context.Context, err error) {
return ctx, nil
}
func (e *ensureTables) DataInserted(ctx context.Context) bool {
return true
}
func (e *ensureTables) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
tables := []interface{}{
sysModel.SysApi{},
sysModel.SysUser{},
sysModel.SysBaseMenu{},
sysModel.SysAuthority{},
sysModel.JwtBlacklist{},
sysModel.SysDictionary{},
sysModel.SysAutoCodeHistory{},
sysModel.SysOperationRecord{},
sysModel.SysDictionaryDetail{},
sysModel.SysBaseMenuParameter{},
sysModel.SysBaseMenuBtn{},
sysModel.SysAuthorityBtn{},
sysModel.SysAutoCode{},
sysModel.SysChatGptOption{},
adapter.CasbinRule{},
example.ExaFile{},
example.ExaCustomer{},
example.ExaFileChunk{},
example.ExaFileUploadAndDownload{},
}
for _, t := range tables {
_ = db.AutoMigrate(&t)
// 视图 authority_menu 会被当成表来创建引发冲突错误更新版本的gorm似乎不会
// 由于 AutoMigrate() 基本无需考虑错误,因此显式忽略
}
return ctx, nil
}
func (e *ensureTables) TableCreated(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
tables := []interface{}{
sysModel.SysApi{},
sysModel.SysUser{},
sysModel.SysBaseMenu{},
sysModel.SysAuthority{},
sysModel.JwtBlacklist{},
sysModel.SysDictionary{},
sysModel.SysAutoCodeHistory{},
sysModel.SysOperationRecord{},
sysModel.SysDictionaryDetail{},
sysModel.SysBaseMenuParameter{},
sysModel.SysBaseMenuBtn{},
sysModel.SysAuthorityBtn{},
sysModel.SysAutoCode{},
sysModel.SysChatGptOption{},
adapter.CasbinRule{},
example.ExaFile{},
example.ExaCustomer{},
example.ExaFileChunk{},
example.ExaFileUploadAndDownload{},
}
yes := true
for _, t := range tables {
yes = yes && db.Migrator().HasTable(t)
}
return yes
}

80
initialize/gorm.go Normal file
View File

@ -0,0 +1,80 @@
package initialize
import (
"miniapp/model/app"
"miniapp/model/common"
"os"
"miniapp/global"
"miniapp/model/example"
"miniapp/model/system"
"go.uber.org/zap"
"gorm.io/gorm"
)
// Gorm 初始化数据库并产生数据库全局变量
// Author SliverHorn
func Gorm() *gorm.DB {
switch global.GVA_CONFIG.System.DbType {
case "mysql":
return GormMysql()
case "pgsql":
return GormPgSql()
case "oracle":
return GormOracle()
case "mssql":
return GormMssql()
case "sqlite":
return GormSqlite()
default:
return GormMysql()
}
}
// RegisterTables 注册数据库表专用
// Author SliverHorn
func RegisterTables() {
db := global.GVA_DB
err := db.AutoMigrate(
// 系统模块表
system.SysApi{},
system.SysUser{},
system.SysBaseMenu{},
system.JwtBlacklist{},
system.SysAuthority{},
system.SysDictionary{},
system.SysOperationRecord{},
system.SysAutoCodeHistory{},
system.SysDictionaryDetail{},
system.SysBaseMenuParameter{},
system.SysBaseMenuBtn{},
system.SysAuthorityBtn{},
system.SysAutoCode{},
system.SysChatGptOption{},
system.Aikefu{},
example.ExaFile{},
example.ExaCustomer{},
example.ExaFileChunk{},
example.ExaFileUploadAndDownload{},
app.User{},
app.OAuth2Client{},
app.Favorite{},
app.Vision{},
common.Hospital{},
common.Notes{},
common.Todos{},
common.Article{},
common.Banner{},
common.UserTodo{},
common.Poster{},
)
if err != nil {
global.GVA_LOG.Error("register table failed", zap.Error(err))
os.Exit(0)
}
global.GVA_LOG.Info("register table success")
}

59
initialize/gorm_mssql.go Normal file
View File

@ -0,0 +1,59 @@
/*
* @Author: 逆光飞翔 191180776@qq.com
* @Date: 2022-12-08 17:25:49
* @LastEditors: 逆光飞翔 191180776@qq.com
* @LastEditTime: 2022-12-08 18:00:00
* @FilePath: \server.exe.exe\initialize\gorm_mssql.go
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
package initialize
import (
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"miniapp/config"
"miniapp/global"
"miniapp/initialize/internal"
)
// GormMssql 初始化Mssql数据库
// Author [LouisZhang](191180776@qq.com)
func GormMssql() *gorm.DB {
m := global.GVA_CONFIG.Mssql
if m.Dbname == "" {
return nil
}
mssqlConfig := sqlserver.Config{
DSN: m.Dsn(), // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
}
if db, err := gorm.Open(sqlserver.New(mssqlConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
return nil
} else {
db.InstanceSet("gorm:table_options", "ENGINE="+m.Engine)
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
return db
}
}
// GormMssqlByConfig 初始化Mysql数据库用过传入配置
func GormMssqlByConfig(m config.Mssql) *gorm.DB {
if m.Dbname == "" {
return nil
}
mssqlConfig := sqlserver.Config{
DSN: m.Dsn(), // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
}
if db, err := gorm.Open(sqlserver.New(mssqlConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
panic(err)
} else {
db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
return db
}
}

55
initialize/gorm_mysql.go Normal file
View File

@ -0,0 +1,55 @@
package initialize
import (
_ "github.com/go-sql-driver/mysql"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"miniapp/config"
"miniapp/global"
"miniapp/initialize/internal"
)
// GormMysql 初始化Mysql数据库
// Author [piexlmax](https://github.com/piexlmax)
// Author [SliverHorn](https://github.com/SliverHorn)
func GormMysql() *gorm.DB {
m := global.GVA_CONFIG.Mysql
if m.Dbname == "" {
return nil
}
mysqlConfig := mysql.Config{
DSN: m.Dsn(), // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
SkipInitializeWithVersion: false, // 根据版本自动配置
}
if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
return nil
} else {
db.InstanceSet("gorm:table_options", "ENGINE="+m.Engine)
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
return db
}
}
// GormMysqlByConfig 初始化Mysql数据库用过传入配置
func GormMysqlByConfig(m config.Mysql) *gorm.DB {
if m.Dbname == "" {
return nil
}
mysqlConfig := mysql.Config{
DSN: m.Dsn(), // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
SkipInitializeWithVersion: false, // 根据版本自动配置
}
if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
panic(err)
} else {
db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
return db
}
}

52
initialize/gorm_oracle.go Normal file
View File

@ -0,0 +1,52 @@
package initialize
import (
//"github.com/dzwvip/oracle"
"miniapp/config"
"miniapp/global"
"miniapp/initialize/internal"
//_ "github.com/godror/godror"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// GormOracle 初始化oracle数据库
// 如果需要Oracle库 放开import里的注释 把下方 mysql.Config 改为 oracle.Config ; mysql.New 改为 oracle.New
func GormOracle() *gorm.DB {
m := global.GVA_CONFIG.Oracle
if m.Dbname == "" {
return nil
}
oracleConfig := mysql.Config{
DSN: m.Dsn(), // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
}
if db, err := gorm.Open(mysql.New(oracleConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
panic(err)
} else {
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
return db
}
}
// GormOracleByConfig 初始化Oracle数据库用过传入配置
func GormOracleByConfig(m config.Oracle) *gorm.DB {
if m.Dbname == "" {
return nil
}
oracleConfig := mysql.Config{
DSN: m.Dsn(), // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
}
if db, err := gorm.Open(mysql.New(oracleConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
panic(err)
} else {
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
return db
}
}

50
initialize/gorm_pgsql.go Normal file
View File

@ -0,0 +1,50 @@
package initialize
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
"miniapp/config"
"miniapp/global"
"miniapp/initialize/internal"
)
// GormPgSql 初始化 Postgresql 数据库
// Author [piexlmax](https://github.com/piexlmax)
// Author [SliverHorn](https://github.com/SliverHorn)
func GormPgSql() *gorm.DB {
p := global.GVA_CONFIG.Pgsql
if p.Dbname == "" {
return nil
}
pgsqlConfig := postgres.Config{
DSN: p.Dsn(), // DSN data source name
PreferSimpleProtocol: false,
}
if db, err := gorm.Open(postgres.New(pgsqlConfig), internal.Gorm.Config(p.Prefix, p.Singular)); err != nil {
return nil
} else {
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(p.MaxIdleConns)
sqlDB.SetMaxOpenConns(p.MaxOpenConns)
return db
}
}
// GormPgSqlByConfig 初始化 Postgresql 数据库 通过参数
func GormPgSqlByConfig(p config.Pgsql) *gorm.DB {
if p.Dbname == "" {
return nil
}
pgsqlConfig := postgres.Config{
DSN: p.Dsn(), // DSN data source name
PreferSimpleProtocol: false,
}
if db, err := gorm.Open(postgres.New(pgsqlConfig), internal.Gorm.Config(p.Prefix, p.Singular)); err != nil {
panic(err)
} else {
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(p.MaxIdleConns)
sqlDB.SetMaxOpenConns(p.MaxOpenConns)
return db
}
}

42
initialize/gorm_sqlite.go Normal file
View File

@ -0,0 +1,42 @@
package initialize
import (
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"miniapp/config"
"miniapp/global"
"miniapp/initialize/internal"
)
// GormSqlite 初始化Sqlite数据库
func GormSqlite() *gorm.DB {
s := global.GVA_CONFIG.Sqlite
if s.Dbname == "" {
return nil
}
if db, err := gorm.Open(sqlite.Open(s.Dsn()), internal.Gorm.Config(s.Prefix, s.Singular)); err != nil {
panic(err)
} else {
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(s.MaxIdleConns)
sqlDB.SetMaxOpenConns(s.MaxOpenConns)
return db
}
}
// GormSqliteByConfig 初始化Sqlite数据库用过传入配置
func GormSqliteByConfig(s config.Sqlite) *gorm.DB {
if s.Dbname == "" {
return nil
}
if db, err := gorm.Open(sqlite.Open(s.Dsn()), internal.Gorm.Config(s.Prefix, s.Singular)); err != nil {
panic(err)
} else {
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(s.MaxIdleConns)
sqlDB.SetMaxOpenConns(s.MaxOpenConns)
return db
}
}

View File

@ -0,0 +1,62 @@
package internal
import (
"gorm.io/gorm/schema"
"log"
"os"
"time"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"miniapp/global"
)
type DBBASE interface {
GetLogMode() string
}
var Gorm = new(_gorm)
type _gorm struct{}
// Config gorm 自定义配置
// Author [SliverHorn](https://github.com/SliverHorn)
func (g *_gorm) Config(prefix string, singular bool) *gorm.Config {
config := &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: prefix,
SingularTable: singular,
},
DisableForeignKeyConstraintWhenMigrating: true,
}
_default := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
SlowThreshold: 200 * time.Millisecond,
LogLevel: logger.Warn,
Colorful: true,
})
var logMode DBBASE
switch global.GVA_CONFIG.System.DbType {
case "mysql":
logMode = &global.GVA_CONFIG.Mysql
case "pgsql":
logMode = &global.GVA_CONFIG.Pgsql
case "oracle":
logMode = &global.GVA_CONFIG.Oracle
default:
logMode = &global.GVA_CONFIG.Mysql
}
switch logMode.GetLogMode() {
case "silent", "Silent":
config.Logger = _default.LogMode(logger.Silent)
case "error", "Error":
config.Logger = _default.LogMode(logger.Error)
case "warn", "Warn":
config.Logger = _default.LogMode(logger.Warn)
case "info", "Info":
config.Logger = _default.LogMode(logger.Info)
default:
config.Logger = _default.LogMode(logger.Info)
}
return config
}

View File

@ -0,0 +1,35 @@
package internal
import (
"fmt"
"gorm.io/gorm/logger"
"miniapp/global"
)
type writer struct {
logger.Writer
}
// NewWriter writer 构造函数
// Author [SliverHorn](https://github.com/SliverHorn)
func NewWriter(w logger.Writer) *writer {
return &writer{Writer: w}
}
// Printf 格式化打印日志
// Author [SliverHorn](https://github.com/SliverHorn)
func (w *writer) Printf(message string, data ...interface{}) {
var logZap bool
switch global.GVA_CONFIG.System.DbType {
case "mysql":
logZap = global.GVA_CONFIG.Mysql.LogZap
case "pgsql":
logZap = global.GVA_CONFIG.Pgsql.LogZap
}
if logZap {
global.GVA_LOG.Info(fmt.Sprintf(message+"\n", data...))
} else {
w.Writer.Printf(message, data...)
}
}

14
initialize/kp.go Normal file
View File

@ -0,0 +1,14 @@
package initialize
import (
"miniapp/global"
"miniapp/service"
"miniapp/utils/flashtext"
)
func InitKp() *flashtext.KeywordProcessor {
Kp := flashtext.NewKeywordProcessor(false)
global.GVA_Kp = Kp
service.ServiceGroupApp.AppServiceGroup.AiKefuService.AddKeyWord()
return Kp
}

23
initialize/other.go Normal file
View File

@ -0,0 +1,23 @@
package initialize
import (
"github.com/songzhibin97/gkit/cache/local_cache"
"miniapp/global"
"miniapp/utils"
)
func OtherInit() {
dr, err := utils.ParseDuration(global.GVA_CONFIG.JWT.ExpiresTime)
if err != nil {
panic(err)
}
_, err = utils.ParseDuration(global.GVA_CONFIG.JWT.BufferTime)
if err != nil {
panic(err)
}
global.BlackCache = local_cache.NewCache(
local_cache.SetDefaultExpire(dr),
)
}

36
initialize/plugin.go Normal file
View File

@ -0,0 +1,36 @@
package initialize
import (
"fmt"
"github.com/gin-gonic/gin"
"miniapp/global"
"miniapp/middleware"
"miniapp/plugin/email"
"miniapp/utils/plugin"
)
func PluginInit(group *gin.RouterGroup, Plugin ...plugin.Plugin) {
for i := range Plugin {
PluginGroup := group.Group(Plugin[i].RouterPath())
Plugin[i].Register(PluginGroup)
}
}
func InstallPlugin(Router *gin.Engine) {
PublicGroup := Router.Group("")
fmt.Println("无鉴权插件安装==》", PublicGroup)
PrivateGroup := Router.Group("")
fmt.Println("鉴权插件安装==》", PrivateGroup)
PrivateGroup.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())
// 添加跟角色挂钩权限的插件 示例 本地示例模式于在线仓库模式注意上方的import 可以自行切换 效果相同
PluginInit(PrivateGroup, email.CreateEmailPlug(
global.GVA_CONFIG.Email.To,
global.GVA_CONFIG.Email.From,
global.GVA_CONFIG.Email.Host,
global.GVA_CONFIG.Email.Secret,
global.GVA_CONFIG.Email.Nickname,
global.GVA_CONFIG.Email.Port,
global.GVA_CONFIG.Email.IsSSL,
))
}

26
initialize/redis.go Normal file
View File

@ -0,0 +1,26 @@
package initialize
import (
"context"
"miniapp/global"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
)
func Redis() {
redisCfg := global.GVA_CONFIG.Redis
client := redis.NewClient(&redis.Options{
Addr: redisCfg.Addr,
Password: redisCfg.Password, // no password set
DB: redisCfg.DB, // use default DB
})
pong, err := client.Ping(context.Background()).Result()
if err != nil {
global.GVA_LOG.Error("redis connect ping failed, err:", zap.Error(err))
} else {
global.GVA_LOG.Info("redis connect ping response:", zap.String("pong", pong))
global.GVA_REDIS = client
}
}

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