init
This commit is contained in:
+674
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 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:
|
||||
|
||||
{project} Copyright (C) {year} {fullname}
|
||||
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>.
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
# go-activerecord for mysql
|
||||
<pre>
|
||||
import github.com/snail007/go-activerecord/mysql
|
||||
|
||||
0.Configure
|
||||
var dbCfg = mysql.NewDBConfig()
|
||||
dbCfg.Password = "admin"
|
||||
db, err := mysql.NewDB(dbCfg)
|
||||
if err != nil {
|
||||
fmt.Printf("ERR:%s", err)
|
||||
return
|
||||
}
|
||||
dbCfg.xxx,"xxxx" default is below:
|
||||
Charset: "utf8",
|
||||
Collate: "utf8_general_ci",
|
||||
Database: "test",
|
||||
Host: "127.0.0.1",
|
||||
Port: 3306,
|
||||
Username: "root",
|
||||
Password: "",
|
||||
TablePrefix: "",
|
||||
TablePrefixSqlIdentifier: "",
|
||||
Timeout: 3000, //ms
|
||||
SetMaxOpenConns: 500,
|
||||
SetMaxIdleConns: 50,
|
||||
1.Connect to multilple Database
|
||||
group := mysql.NewDBGroup("default")
|
||||
group.Regist("default", NewDBConfigWith("127.0.0.1", 3306, "test", "root", "admin"))
|
||||
group.Regist("blog", NewDBConfigWith("127.0.0.1", 3306, "blog_db", "root", "admin"))
|
||||
group.Regist("www", NewDBConfigWith("127.0.0.1", 3306, "www_db", "root", "admin"))
|
||||
//group.DB() equal to group.DB("default")
|
||||
db := group.DB("www")
|
||||
if db != nil {
|
||||
rs, err := db.Query(db.AR().From("test"))
|
||||
if err != nil {
|
||||
t.Errorf("ERR:%s", err)
|
||||
} else {
|
||||
fmt.Println(rs.Rows())
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("db group config of name %s not found", "www")
|
||||
}
|
||||
2.Select
|
||||
type User{
|
||||
ID int `column:"id"`
|
||||
Name string `column:"name"`
|
||||
}
|
||||
rs, err := db.Query(db.AR().
|
||||
Select("*").
|
||||
From("log").
|
||||
Where(map[string]interface{}{
|
||||
"id": 11,
|
||||
})
|
||||
)
|
||||
if err != nil {
|
||||
fmt.Printf("ERR:%s", err)
|
||||
} else {
|
||||
fmt.Println(rs.Rows())
|
||||
}
|
||||
//struct
|
||||
_user :=User{}
|
||||
user,err:=rs.Struct(_user)
|
||||
if err != nil {
|
||||
fmt.Printf("ERR:%s", err)
|
||||
} else {
|
||||
fmt.Println(user)
|
||||
}
|
||||
//structs
|
||||
_user :=User{}
|
||||
users,err:=rs.Structs(_user)
|
||||
if err != nil {
|
||||
fmt.Printf("ERR:%s", err)
|
||||
} else {
|
||||
fmt.Println(users)
|
||||
}
|
||||
//Map structs
|
||||
_user :=User{}
|
||||
usersMap,err=rs.MapStructs("id",_user)
|
||||
if err != nil {
|
||||
fmt.Printf("ERR:%s", err)
|
||||
} else {
|
||||
fmt.Println(usersMap)
|
||||
}
|
||||
//db.AR() return a new *mysql.ActiveRecord,you can use it to build you sql.
|
||||
//all of db.AR() usage to see <a href="https://github.com/snail007/go-activerecord/blob/master/mysql/mysql_test.go">mysql_test.go</a>
|
||||
|
||||
rs is a ResultSet,all of ResultSet method and properties is :
|
||||
ResultSet.Len()
|
||||
how many rows of select
|
||||
ResultSet.MapRows(keyColumn string) (rowsMap map[string]map[string]string)
|
||||
get a map which key is each value of row[keyColumn]
|
||||
ResultSet.MapStructs(keyColumn string, strucT interface{}) (structsMap map[string]interface{},
|
||||
err error)
|
||||
get a map which key is row[keyColumn],value is strucT
|
||||
ResultSet.Rows() (rows []map[string]string)
|
||||
get rows of select
|
||||
ResultSet.Structs(strucT interface{}) (structs []interface{}, err error)
|
||||
get array of strucT of select
|
||||
ResultSet.Row() (row map[string]string)
|
||||
get first of rows
|
||||
ResultSet.Struct(strucT interface{}) (Struct interface{}, err error)
|
||||
get first strucT of select
|
||||
ResultSet.Values(column string) (values []string)
|
||||
get an array contains each row[column]
|
||||
ResultSet.MapValues(keyColumn, valueColumn string) (values map[string]string)
|
||||
get a map key is each row[column],value is row[valueColumn]
|
||||
ResultSet.Value(column string) (value string)
|
||||
get first row[column] of rows
|
||||
ResultSet.LastInsertId
|
||||
if sql type is insert , this is the last insert id
|
||||
ResultSet.RowsAffected
|
||||
if sql type is write , this is the count of rows affected
|
||||
|
||||
|
||||
3.Insert & Insert Batch
|
||||
Insert:
|
||||
rs, err := db.Exec(db.AR().Insert("test", map[string]interface{}{
|
||||
"id": "id11122",
|
||||
"name": "333",
|
||||
}))
|
||||
Insert Batch:
|
||||
rs, err := db.Exec(db.AR().InsertBatch("test", []map[string]interface{}{
|
||||
map[string]interface{}{
|
||||
"id": "id11122",
|
||||
"name": "333",
|
||||
},
|
||||
map[string]interface{}{
|
||||
"id": "id11122",
|
||||
"name": "4444",
|
||||
},
|
||||
}))
|
||||
lastInsertId:=rs.LastInsertId
|
||||
rowsAffected:=rs.RowsAffected
|
||||
fmt.printf("last insert id : %d,rows affected : %d",lastInsertId,rowsAffected)
|
||||
|
||||
4.Update & Update Batch
|
||||
Update:
|
||||
1.common Update(table,data,where)
|
||||
rs, err := db.Exec(db.AR().Update("test", map[string]interface{}{
|
||||
"id": "id11122",
|
||||
"name": "333",
|
||||
}),map[string]interface{}{
|
||||
"pid": 223,
|
||||
}))
|
||||
//equal sql below :
|
||||
UPDATE `test`
|
||||
SET `id` = ? , `name` = ?
|
||||
WHERE `pid` = ?
|
||||
|
||||
2.column operate
|
||||
Update:
|
||||
rs, err := db.Exec(db.AR().Update("test", map[string]interface{}{
|
||||
"id": "id11122",
|
||||
"score +": "333",
|
||||
}),map[string]interface{}{
|
||||
"pid": 223,
|
||||
}))
|
||||
//equal sql below :
|
||||
UPDATE `test`
|
||||
SET `id` = ? , `score` = `score` + ?
|
||||
WHERE `pid` = ?
|
||||
|
||||
Update Batch:
|
||||
1.common update UpdateBatch(table,data,DataWhereColumns)
|
||||
rs, err := db.Exec(db.AR().UpdateBatch("test", []map[string]interface{}{
|
||||
map[string]interface{}{
|
||||
"id": "id1",
|
||||
"name": "333",
|
||||
},
|
||||
map[string]interface{}{
|
||||
"id": "id2",
|
||||
"name": "4444",
|
||||
},
|
||||
}, []string{"id"}))
|
||||
rowsAffected:=rs.RowsAffected
|
||||
fmt.printf("rows affected : %d",rowsAffected)
|
||||
//equal sql below :
|
||||
UPDATE `test`
|
||||
SET `name` = CASE
|
||||
WHEN `id` = ? THEN ?
|
||||
WHEN `id` = ? THEN ?
|
||||
ELSE `score` END
|
||||
WHERE id IN (?,?)
|
||||
|
||||
2.column operate
|
||||
rs, err := db.Exec(db.AR().UpdateBatch("test", []map[string]interface{}{
|
||||
map[string]interface{}{
|
||||
"id": "id11",
|
||||
"score +": 10,
|
||||
},
|
||||
map[string]interface{}{
|
||||
"id": "id22",
|
||||
"score +": 20,
|
||||
},
|
||||
}, , []string{"id"}))
|
||||
rowsAffected:=rs.RowsAffected
|
||||
fmt.printf("rows affected : %d",rowsAffected)
|
||||
//equal sql below :
|
||||
UPDATE `test`
|
||||
SET `score` = CASE
|
||||
WHEN `id` = ? THEN `score` + ?
|
||||
WHEN `id` = ? THEN `score` + ?
|
||||
ELSE `score` END
|
||||
WHERE id IN (?,?)
|
||||
|
||||
3.where on more column
|
||||
rs, err := db.Exec(db.AR().UpdateBatch("test", []map[string]interface{}{
|
||||
map[string]interface{}{
|
||||
"id": "id1",
|
||||
"gid": 22,
|
||||
"name": "test1",
|
||||
"score +": 1,
|
||||
}, map[string]interface{}{
|
||||
"id": "id2",
|
||||
"gid": 33,
|
||||
"name": "test2",
|
||||
"score +": 1,
|
||||
},
|
||||
}, []string{"id", "gid"})
|
||||
rowsAffected:=rs.RowsAffected
|
||||
fmt.printf("rows affected : %d",rowsAffected)
|
||||
//equal sql below :
|
||||
UPDATE `test`
|
||||
SET `name` = CASE
|
||||
WHEN `id` = ? AND `gid` = ? THEN ?
|
||||
WHEN `id` = ? AND `gid` = ? THEN ?
|
||||
ELSE `name` END,`score` = CASE
|
||||
WHEN `id` = ? AND `gid` = ? THEN `score` + ?
|
||||
WHEN `id` = ? AND `gid` = ? THEN `score` + ?
|
||||
ELSE `score` END
|
||||
WHERE id IN (?,?) AND gid IN (?,?)
|
||||
5.Delete
|
||||
rs, err := db.Exec(db.AR().Delete("test", map[string]interface{}{
|
||||
"pid": 223,
|
||||
}))
|
||||
rowsAffected:=rs.RowsAffected
|
||||
fmt.printf("rows affected : %d",rowsAffected)
|
||||
6.Raw SQL Query
|
||||
rs, err := db.Exec(db.AR().Raw("insert into test(id,name) values (?,?)", 555,"6666"))
|
||||
if err != nil {
|
||||
fmt.Printf("ERR:%s", err)
|
||||
} else {
|
||||
fmt.Println(rs.RowsAffected, rs.LastInsertId)
|
||||
}
|
||||
//notice:
|
||||
if dbCfg.TablePrefix="user_"
|
||||
dbCfg.TablePrefixSqlIdentifier="{__PREFIX__}"
|
||||
then
|
||||
db.AR().Raw("insert into {__PREFIX__}test(id,name) values (?,?)
|
||||
when execute sql,{__PREFIX__} will be replaced with "user_"
|
||||
7.Cache Query
|
||||
MyCache is an example to set or get cache data .
|
||||
|
||||
var (
|
||||
cacheData = map[string][]byte{}
|
||||
)
|
||||
|
||||
type MyCache struct {
|
||||
}
|
||||
|
||||
func (c *MyCache) Set(key string, data []byte, expire uint) (err error) {
|
||||
cacheData[key] = data
|
||||
log.Println("set cache")
|
||||
return
|
||||
}
|
||||
func (c *MyCache) Get(key string) (data []byte, err error) {
|
||||
if v, ok := cacheData[key]; ok {
|
||||
log.Println("form cache")
|
||||
return v, nil
|
||||
}
|
||||
return nil, errors.New("key not found or expired")
|
||||
}
|
||||
func main() {
|
||||
g := mysql.NewDBGroupCache("default", &MyCache{})
|
||||
g.Regist("default", mysql.NewDBConfigWith("127.0.0.1", 3306, "test", "root", "admin"))
|
||||
fmt.Println(g.DB().Query(g.DB().AR().Cache("testkey", 30).From("test")))
|
||||
rs, _ := g.DB().Query(g.DB().AR().Cache("testkey", 30).From("test"))
|
||||
fmt.Println(rs.Row())
|
||||
}
|
||||
output like:
|
||||
2017/11/21 18:12:01 set cache
|
||||
&{0xc42000d340 0 0} <nil>
|
||||
2017/11/21 18:12:01 form cache
|
||||
map[pid:1 id:a1 name:a1111 gid:11]
|
||||
</pre>
|
||||
+1128
@@ -0,0 +1,1128 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
type DBGroup struct {
|
||||
defaultConfigKey string
|
||||
config map[string]DBConfig
|
||||
dbGroup map[string]*DB
|
||||
cache Cache
|
||||
}
|
||||
|
||||
func NewDBGroupCache(defaultConfigName string, cache Cache) (group *DBGroup) {
|
||||
group = &DBGroup{}
|
||||
group.defaultConfigKey = defaultConfigName
|
||||
group.config = map[string]DBConfig{}
|
||||
group.dbGroup = map[string]*DB{}
|
||||
group.cache = cache
|
||||
return
|
||||
}
|
||||
func NewDBGroup(defaultConfigName string) (group *DBGroup) {
|
||||
group = &DBGroup{}
|
||||
group.defaultConfigKey = defaultConfigName
|
||||
group.config = map[string]DBConfig{}
|
||||
group.dbGroup = map[string]*DB{}
|
||||
return
|
||||
}
|
||||
func (g *DBGroup) RegistGroup(cfg map[string]DBConfig) (err error) {
|
||||
g.config = cfg
|
||||
for name, config := range g.config {
|
||||
if config.Cache == nil {
|
||||
config.Cache = g.cache
|
||||
}
|
||||
g.Regist(name, config)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (g *DBGroup) Regist(name string, cfg DBConfig) (err error) {
|
||||
var db DB
|
||||
if cfg.Cache == nil {
|
||||
cfg.Cache = g.cache
|
||||
}
|
||||
db, err = NewDB(cfg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
g.config[name] = cfg
|
||||
g.dbGroup[name] = &db
|
||||
return
|
||||
}
|
||||
func (g *DBGroup) DB(name ...string) (db *DB) {
|
||||
key := ""
|
||||
if len(name) == 0 {
|
||||
key = g.defaultConfigKey
|
||||
} else {
|
||||
key = name[0]
|
||||
}
|
||||
db, _ = g.dbGroup[key]
|
||||
return
|
||||
}
|
||||
|
||||
type DB struct {
|
||||
Config DBConfig
|
||||
ConnPool *sql.DB
|
||||
DSN string
|
||||
}
|
||||
|
||||
func NewDB(config DBConfig) (db DB, err error) {
|
||||
db = DB{}
|
||||
err = db.init(config)
|
||||
return
|
||||
}
|
||||
func (db *DB) init(config DBConfig) (err error) {
|
||||
db.Config = config
|
||||
db.DSN = db.getDSN()
|
||||
db.ConnPool, err = db.getDB()
|
||||
return
|
||||
}
|
||||
|
||||
func (db *DB) getDSN() string {
|
||||
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?timeout=%dms&readTimeout=%dms&writeTimeout=%dms&charset=%s&collation=%s",
|
||||
url.QueryEscape(db.Config.Username),
|
||||
db.Config.Password,
|
||||
url.QueryEscape(db.Config.Host),
|
||||
db.Config.Port,
|
||||
url.QueryEscape(db.Config.Database),
|
||||
db.Config.Timeout,
|
||||
db.Config.ReadTimeout,
|
||||
db.Config.WriteTimeout,
|
||||
url.QueryEscape(db.Config.Charset),
|
||||
url.QueryEscape(db.Config.Collate))
|
||||
}
|
||||
func (db *DB) getDB() (connPool *sql.DB, err error) {
|
||||
connPool, err = sql.Open("mysql", db.getDSN())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
connPool.SetMaxOpenConns(db.Config.SetMaxOpenConns)
|
||||
connPool.SetMaxIdleConns(db.Config.SetMaxIdleConns)
|
||||
err = connPool.Ping()
|
||||
return
|
||||
}
|
||||
func (db *DB) AR() (ar *ActiveRecord) {
|
||||
ar = new(ActiveRecord)
|
||||
ar.Reset()
|
||||
ar.tablePrefix = db.Config.TablePrefix
|
||||
ar.tablePrefixSqlIdentifier = db.Config.TablePrefixSqlIdentifier
|
||||
return
|
||||
}
|
||||
func (db *DB) Begin(config DBConfig) (tx *sql.Tx, err error) {
|
||||
return db.ConnPool.Begin()
|
||||
}
|
||||
func (db *DB) ExecTx(ar *ActiveRecord, tx *sql.Tx) (rs *ResultSet, err error) {
|
||||
return db.ExecSQLTx(ar.SQL(), tx, ar.values...)
|
||||
}
|
||||
func (db *DB) ExecSQLTx(sqlStr string, tx *sql.Tx, values ...interface{}) (rs *ResultSet, err error) {
|
||||
sqlStr = strings.Replace(sqlStr, db.Config.TablePrefixSqlIdentifier, db.Config.TablePrefix, -1)
|
||||
var stmt *sql.Stmt
|
||||
var result sql.Result
|
||||
rs = new(ResultSet)
|
||||
stmt, err = tx.Prepare(sqlStr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer stmt.Close()
|
||||
result, err = stmt.Exec(values...)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rs.RowsAffected, err = result.RowsAffected()
|
||||
rs.LastInsertId, err = result.LastInsertId()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (db *DB) Exec(ar *ActiveRecord) (rs *ResultSet, err error) {
|
||||
return db.ExecSQL(ar.SQL(), ar.values...)
|
||||
}
|
||||
func (db *DB) ExecSQL(sqlStr string, values ...interface{}) (rs *ResultSet, err error) {
|
||||
sqlStr = strings.Replace(sqlStr, db.Config.TablePrefixSqlIdentifier, db.Config.TablePrefix, -1)
|
||||
var stmt *sql.Stmt
|
||||
var result sql.Result
|
||||
rs = new(ResultSet)
|
||||
stmt, err = db.ConnPool.Prepare(sqlStr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer stmt.Close()
|
||||
result, err = stmt.Exec(values...)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rs.RowsAffected, err = result.RowsAffected()
|
||||
rs.LastInsertId, err = result.LastInsertId()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (db *DB) Query(ar *ActiveRecord) (rs *ResultSet, err error) {
|
||||
var results []map[string][]byte
|
||||
if ar.cacheKey != "" {
|
||||
var data []byte
|
||||
data, err = db.Config.Cache.Get(ar.cacheKey)
|
||||
if err == nil {
|
||||
d := gob.NewDecoder(bytes.NewReader(data))
|
||||
err = d.Decode(&results)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if results == nil || len(results) == 0 {
|
||||
sqlStr := ar.SQL()
|
||||
var stmt *sql.Stmt
|
||||
stmt, err = db.ConnPool.Prepare(sqlStr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer stmt.Close()
|
||||
var rows *sql.Rows
|
||||
rows, err = stmt.Query(ar.values...)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
cols := []string{}
|
||||
cols, err = rows.Columns()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
vals := make([][]byte, len(cols))
|
||||
scans := make([]interface{}, len(cols))
|
||||
for i := range vals {
|
||||
scans[i] = &vals[i]
|
||||
}
|
||||
results = []map[string][]byte{}
|
||||
for rows.Next() {
|
||||
err = rows.Scan(scans...)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
row := make(map[string][]byte)
|
||||
for k, v := range vals {
|
||||
key := cols[k]
|
||||
row[key] = v
|
||||
}
|
||||
results = append(results, row)
|
||||
}
|
||||
if ar.cacheKey != "" {
|
||||
b := new(bytes.Buffer)
|
||||
e := gob.NewEncoder(b)
|
||||
err = e.Encode(results)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = db.Config.Cache.Set(ar.cacheKey, b.Bytes(), ar.cacheSeconds)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
rs = new(ResultSet)
|
||||
rs.Init(&results)
|
||||
return
|
||||
}
|
||||
|
||||
type DBConfig struct {
|
||||
Charset string
|
||||
Collate string
|
||||
Database string
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
Password string
|
||||
TablePrefix string
|
||||
TablePrefixSqlIdentifier string
|
||||
Timeout int
|
||||
ReadTimeout int
|
||||
WriteTimeout int
|
||||
SetMaxIdleConns int
|
||||
SetMaxOpenConns int
|
||||
Cache Cache
|
||||
}
|
||||
|
||||
func NewDBConfigWith(host string, port int, dbName, user, pass string) (cfg DBConfig) {
|
||||
cfg = NewDBConfig()
|
||||
cfg.Host = host
|
||||
cfg.Port = port
|
||||
cfg.Username = user
|
||||
cfg.Password = pass
|
||||
cfg.Database = dbName
|
||||
return
|
||||
}
|
||||
func NewDBConfig() DBConfig {
|
||||
return DBConfig{
|
||||
Charset: "utf8",
|
||||
Collate: "utf8_general_ci",
|
||||
Database: "test",
|
||||
Host: "127.0.0.1",
|
||||
Port: 3306,
|
||||
Username: "root",
|
||||
Password: "",
|
||||
TablePrefix: "",
|
||||
TablePrefixSqlIdentifier: "",
|
||||
Timeout: 3000,
|
||||
ReadTimeout: 5000,
|
||||
WriteTimeout: 5000,
|
||||
SetMaxOpenConns: 500,
|
||||
SetMaxIdleConns: 50,
|
||||
}
|
||||
}
|
||||
|
||||
type ActiveRecord struct {
|
||||
arSelect [][]interface{}
|
||||
arFrom []string
|
||||
arJoin [][]string
|
||||
arWhere [][]interface{}
|
||||
arGroupBy []string
|
||||
arHaving [][]interface{}
|
||||
arOrderBy map[string]string
|
||||
arLimit string
|
||||
arSet map[string][]interface{}
|
||||
arUpdateBatch []interface{}
|
||||
arInsert map[string]interface{}
|
||||
arInsertBatch []map[string]interface{}
|
||||
asTable map[string]bool
|
||||
values []interface{}
|
||||
sqlType string
|
||||
currentSQL string
|
||||
tablePrefix string
|
||||
tablePrefixSqlIdentifier string
|
||||
cacheKey string
|
||||
cacheSeconds uint
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) Cache(key string, seconds uint) *ActiveRecord {
|
||||
ar.cacheKey = key
|
||||
ar.cacheSeconds = seconds
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) getValues() []interface{} {
|
||||
return ar.values
|
||||
}
|
||||
func (ar *ActiveRecord) Reset() {
|
||||
ar.arSelect = [][]interface{}{}
|
||||
ar.arFrom = []string{}
|
||||
ar.arJoin = [][]string{}
|
||||
ar.arWhere = [][]interface{}{}
|
||||
ar.arGroupBy = []string{}
|
||||
ar.arHaving = [][]interface{}{}
|
||||
ar.arOrderBy = map[string]string{}
|
||||
ar.arLimit = ""
|
||||
ar.arSet = map[string][]interface{}{}
|
||||
ar.arUpdateBatch = []interface{}{}
|
||||
ar.arInsert = map[string]interface{}{}
|
||||
ar.arInsertBatch = []map[string]interface{}{}
|
||||
ar.asTable = map[string]bool{}
|
||||
ar.values = []interface{}{}
|
||||
ar.sqlType = "select"
|
||||
ar.currentSQL = ""
|
||||
ar.cacheKey = ""
|
||||
ar.cacheSeconds = 0
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) Select(columns string) *ActiveRecord {
|
||||
return ar._select(columns, true)
|
||||
}
|
||||
func (ar *ActiveRecord) SelectNoWrap(columns string) *ActiveRecord {
|
||||
return ar._select(columns, false)
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) _select(columns string, wrap bool) *ActiveRecord {
|
||||
for _, column := range strings.Split(columns, ",") {
|
||||
ar.arSelect = append(ar.arSelect, []interface{}{column, wrap})
|
||||
}
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) From(from string) *ActiveRecord {
|
||||
ar.FromAs(from, "")
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) FromAs(from, as string) *ActiveRecord {
|
||||
ar.arFrom = []string{from, as}
|
||||
if as != "" {
|
||||
ar.asTable[as] = true
|
||||
}
|
||||
return ar
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) Join(table, as, on, type_ string) *ActiveRecord {
|
||||
ar.arJoin = append(ar.arJoin, []string{table, as, on, type_})
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) Where(where map[string]interface{}) *ActiveRecord {
|
||||
if len(where) > 0 {
|
||||
ar.WhereWrap(where, "AND", "")
|
||||
}
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) WhereWrap(where map[string]interface{}, leftWrap, rightWrap string) *ActiveRecord {
|
||||
if len(where) > 0 {
|
||||
ar.arWhere = append(ar.arWhere, []interface{}{where, leftWrap, rightWrap, len(ar.arWhere)})
|
||||
}
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) GroupBy(column string) *ActiveRecord {
|
||||
for _, column_ := range strings.Split(column, ",") {
|
||||
ar.arGroupBy = append(ar.arGroupBy, strings.TrimSpace(column_))
|
||||
}
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) Having(having string) *ActiveRecord {
|
||||
ar.HavingWrap(having, "AND", "")
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) HavingWrap(having, leftWrap, rightWrap string) *ActiveRecord {
|
||||
ar.arHaving = append(ar.arHaving, []interface{}{having, leftWrap, rightWrap, len(ar.arHaving)})
|
||||
return ar
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) OrderBy(column, type_ string) *ActiveRecord {
|
||||
ar.arOrderBy[column] = type_
|
||||
return ar
|
||||
}
|
||||
|
||||
//Limit Limit(offset,count) or Limit(count)
|
||||
func (ar *ActiveRecord) Limit(limit ...int) *ActiveRecord {
|
||||
if len(limit) == 1 {
|
||||
ar.arLimit = fmt.Sprintf("%d", limit[0])
|
||||
|
||||
} else if len(limit) == 2 {
|
||||
ar.arLimit = fmt.Sprintf("%d,%d", limit[0], limit[1])
|
||||
} else {
|
||||
ar.arLimit = ""
|
||||
}
|
||||
return ar
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) Insert(table string, data map[string]interface{}) *ActiveRecord {
|
||||
ar.sqlType = "insert"
|
||||
ar.arInsert = data
|
||||
ar.From(table)
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) Replace(table string, data map[string]interface{}) *ActiveRecord {
|
||||
ar.sqlType = "replace"
|
||||
ar.arInsert = data
|
||||
ar.From(table)
|
||||
return ar
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) InsertBatch(table string, data []map[string]interface{}) *ActiveRecord {
|
||||
ar.sqlType = "insertBatch"
|
||||
ar.arInsertBatch = data
|
||||
ar.From(table)
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) ReplaceBatch(table string, data []map[string]interface{}) *ActiveRecord {
|
||||
ar.InsertBatch(table, data)
|
||||
ar.sqlType = "replaceBatch"
|
||||
return ar
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) Delete(table string, where map[string]interface{}) *ActiveRecord {
|
||||
ar.From(table)
|
||||
ar.Where(where)
|
||||
ar.sqlType = "delete"
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) Update(table string, data, where map[string]interface{}) *ActiveRecord {
|
||||
ar.From(table)
|
||||
ar.Where(where)
|
||||
for k, v := range data {
|
||||
if isBool(v) {
|
||||
value := 0
|
||||
if v.(bool) {
|
||||
value = 1
|
||||
}
|
||||
ar.Set(k, value)
|
||||
} else if v == nil {
|
||||
ar.SetNoWrap(k, "NULL")
|
||||
} else {
|
||||
ar.Set(k, v)
|
||||
}
|
||||
}
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) UpdateBatch(table string, values []map[string]interface{}, whereColumn []string) *ActiveRecord {
|
||||
ar.From(table)
|
||||
ar.sqlType = "updateBatch"
|
||||
ar.arUpdateBatch = []interface{}{values, whereColumn}
|
||||
if len(values) > 0 {
|
||||
for _, whereCol := range whereColumn {
|
||||
ids := []interface{}{}
|
||||
for _, val := range values {
|
||||
ids = append(ids, val[whereCol])
|
||||
}
|
||||
ar.Where(map[string]interface{}{whereCol: ids})
|
||||
}
|
||||
}
|
||||
return ar
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) Set(column string, value interface{}) *ActiveRecord {
|
||||
ar.sqlType = "update"
|
||||
ar.arSet[column] = []interface{}{value, true}
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) SetNoWrap(column string, value interface{}) *ActiveRecord {
|
||||
ar.sqlType = "update"
|
||||
ar.arSet[column] = []interface{}{value, false}
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) Wrap(v string) string {
|
||||
columns := strings.Split(v, ".")
|
||||
if len(columns) == 2 {
|
||||
return ar.protectIdentifier(ar.checkPrefix(columns[0])) + "." + ar.checkPrefix(columns[1])
|
||||
}
|
||||
return ar.protectIdentifier(ar.checkPrefix(columns[0]))
|
||||
}
|
||||
func (ar *ActiveRecord) Raw(sql string, values ...interface{}) *ActiveRecord {
|
||||
ar.currentSQL = sql
|
||||
if len(values) > 0 {
|
||||
ar.values = append(ar.values, values...)
|
||||
}
|
||||
return ar
|
||||
}
|
||||
func (ar *ActiveRecord) Values() []interface{} {
|
||||
return ar.values
|
||||
}
|
||||
func (ar *ActiveRecord) SQL() string {
|
||||
|
||||
if ar.currentSQL != "" {
|
||||
return ar.currentSQL
|
||||
}
|
||||
switch ar.sqlType {
|
||||
case "select":
|
||||
ar.currentSQL = ar.getSelectSQL()
|
||||
case "update":
|
||||
ar.currentSQL = ar.getUpdateSQL()
|
||||
case "updateBatch":
|
||||
ar.currentSQL = ar.getUpdateBatchSQL()
|
||||
case "insert":
|
||||
ar.currentSQL = ar.getInsertSQL()
|
||||
case "insertBatch":
|
||||
ar.currentSQL = ar.getInsertBatchSQL()
|
||||
case "replace":
|
||||
ar.currentSQL = ar.getReplaceSQL()
|
||||
case "replaceBatch":
|
||||
ar.currentSQL = ar.getReplaceBatchSQL()
|
||||
case "delete":
|
||||
ar.currentSQL = ar.getDeleteSQL()
|
||||
}
|
||||
ar.currentSQL = strings.Replace(ar.currentSQL, ar.tablePrefixSqlIdentifier, ar.tablePrefix, -1)
|
||||
return ar.currentSQL
|
||||
}
|
||||
func (ar *ActiveRecord) getUpdateSQL() string {
|
||||
SQL := []string{"UPDATE "}
|
||||
SQL = append(SQL, ar.getFrom())
|
||||
SQL = append(SQL, "\nSET")
|
||||
SQL = append(SQL, ar.compileSet())
|
||||
SQL = append(SQL, ar.getWhere())
|
||||
orderBy := strings.TrimSpace(ar.compileOrderBy())
|
||||
if orderBy != "" {
|
||||
SQL = append(SQL, fmt.Sprintf("\nORDER BY %s", orderBy))
|
||||
}
|
||||
SQL = append(SQL, ar.getLimit())
|
||||
return strings.Join(SQL, " ")
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) getUpdateBatchSQL() string {
|
||||
SQL := []string{"UPDATE "}
|
||||
SQL = append(SQL, ar.getFrom())
|
||||
SQL = append(SQL, "\nSET")
|
||||
SQL = append(SQL, ar.compileUpdateBatch())
|
||||
SQL = append(SQL, ar.getWhere())
|
||||
return strings.Join(SQL, " ")
|
||||
}
|
||||
func (ar *ActiveRecord) getInsertSQL() string {
|
||||
SQL := []string{"INSERT INTO "}
|
||||
SQL = append(SQL, ar.getFrom())
|
||||
SQL = append(SQL, ar.compileInsert())
|
||||
return strings.Join(SQL, " ")
|
||||
}
|
||||
func (ar *ActiveRecord) getReplaceSQL() string {
|
||||
SQL := []string{"REPLACE INTO "}
|
||||
SQL = append(SQL, ar.getFrom())
|
||||
SQL = append(SQL, ar.compileInsert())
|
||||
return strings.Join(SQL, " ")
|
||||
}
|
||||
func (ar *ActiveRecord) getInsertBatchSQL() string {
|
||||
SQL := []string{"INSERT INTO "}
|
||||
SQL = append(SQL, ar.getFrom())
|
||||
SQL = append(SQL, ar.compileInsertBatch())
|
||||
return strings.Join(SQL, " ")
|
||||
}
|
||||
func (ar *ActiveRecord) getReplaceBatchSQL() string {
|
||||
SQL := []string{"REPLACE INTO "}
|
||||
SQL = append(SQL, ar.getFrom())
|
||||
SQL = append(SQL, ar.compileInsertBatch())
|
||||
return strings.Join(SQL, " ")
|
||||
}
|
||||
func (ar *ActiveRecord) getDeleteSQL() string {
|
||||
SQL := []string{"DELETE FROM "}
|
||||
SQL = append(SQL, ar.getFrom())
|
||||
SQL = append(SQL, ar.getWhere())
|
||||
orderBy := strings.TrimSpace(ar.compileOrderBy())
|
||||
if orderBy != "" {
|
||||
SQL = append(SQL, fmt.Sprintf("\nORDER BY %s", orderBy))
|
||||
}
|
||||
SQL = append(SQL, ar.getLimit())
|
||||
return strings.Join(SQL, " ")
|
||||
}
|
||||
func (ar *ActiveRecord) getSelectSQL() string {
|
||||
from := ar.getFrom()
|
||||
where := ar.getWhere()
|
||||
having := ""
|
||||
for _, w := range ar.arHaving {
|
||||
having += ar.compileWhere(w[0], w[1].(string), w[2].(string), w[3].(int))
|
||||
}
|
||||
having = strings.TrimSpace(having)
|
||||
if having != "" {
|
||||
having = fmt.Sprintf("\nHAVING %s", having)
|
||||
}
|
||||
groupBy := strings.TrimSpace(ar.compileGroupBy())
|
||||
if groupBy != "" {
|
||||
groupBy = fmt.Sprintf("\nGROUP BY %s", groupBy)
|
||||
}
|
||||
orderBy := strings.TrimSpace(ar.compileOrderBy())
|
||||
if orderBy != "" {
|
||||
orderBy = fmt.Sprintf("\nORDER BY %s", orderBy)
|
||||
}
|
||||
limit := ar.getLimit()
|
||||
Select := ar.compileSelect()
|
||||
return fmt.Sprintf("SELECT %s \nFROM %s %s %s %s %s %s", Select, from, where, groupBy, having, orderBy, limit)
|
||||
}
|
||||
func (ar *ActiveRecord) compileUpdateBatch() string {
|
||||
_values, _index := ar.arUpdateBatch[0], ar.arUpdateBatch[1]
|
||||
index := _index.([]string)
|
||||
values := _values.([]map[string]interface{})
|
||||
columns := []string{}
|
||||
for k := range values[0] {
|
||||
_continue := false
|
||||
for _, v1 := range index {
|
||||
if k == v1 {
|
||||
_continue = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if _continue {
|
||||
continue
|
||||
}
|
||||
columns = append(columns, k)
|
||||
}
|
||||
str := ""
|
||||
for _, column := range columns {
|
||||
_column := column
|
||||
realColumnArr := strings.Split(column, " ")
|
||||
if len(realColumnArr) == 2 {
|
||||
_column = realColumnArr[0]
|
||||
}
|
||||
str += fmt.Sprintf("%s = CASE \n", ar.protectIdentifier(_column))
|
||||
for _, row := range values {
|
||||
_when := []string{}
|
||||
for _, col := range index {
|
||||
_when = append(_when, fmt.Sprintf("%s = ?", ar.protectIdentifier(col)))
|
||||
ar.values = append(ar.values, row[col])
|
||||
}
|
||||
_whenStr := strings.Join(_when, " AND ")
|
||||
if len(realColumnArr) == 2 {
|
||||
str += fmt.Sprintf("WHEN %s THEN %s %s ? \n", _whenStr, ar.protectIdentifier(_column), realColumnArr[1])
|
||||
} else {
|
||||
str += fmt.Sprintf("WHEN %s THEN ? \n", _whenStr)
|
||||
}
|
||||
ar.values = append(ar.values, row[column])
|
||||
}
|
||||
str += fmt.Sprintf("ELSE %s END,", ar.protectIdentifier(_column))
|
||||
}
|
||||
return strings.TrimRight(str, " ,")
|
||||
}
|
||||
func isArray(v interface{}) bool {
|
||||
if v == nil {
|
||||
return false
|
||||
}
|
||||
return reflect.TypeOf(v).Kind() == reflect.Slice || reflect.TypeOf(v).Kind() == reflect.Array
|
||||
}
|
||||
func isBool(v interface{}) bool {
|
||||
if v == nil {
|
||||
return false
|
||||
}
|
||||
return reflect.TypeOf(v).Kind() == reflect.Bool
|
||||
}
|
||||
func MapKey(v map[string]interface{}) string {
|
||||
for k := range v {
|
||||
return k
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func MapCurrent(v map[string]interface{}) interface{} {
|
||||
for _, val := range v {
|
||||
return val
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func (ar *ActiveRecord) compileInsert() string {
|
||||
var columns = []string{}
|
||||
var values = []string{}
|
||||
for k, v := range ar.arInsert {
|
||||
columns = append(columns, ar.protectIdentifier(k))
|
||||
values = append(values, "?")
|
||||
ar.values = append(ar.values, v)
|
||||
}
|
||||
if len(columns) > 0 {
|
||||
return fmt.Sprintf("(%s) \nVALUES (%s)", strings.Join(columns, ","), strings.Join(values, ","))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func (ar *ActiveRecord) compileInsertBatch() string {
|
||||
var columns []string
|
||||
var values []string
|
||||
for col := range ar.arInsertBatch[0] {
|
||||
columns = append(columns, ar.protectIdentifier(col))
|
||||
}
|
||||
for _, row := range ar.arInsertBatch {
|
||||
|
||||
_values := []string{}
|
||||
for _, col := range columns {
|
||||
_values = append(_values, "?")
|
||||
ar.values = append(ar.values, row[strings.Trim(col, "`")])
|
||||
}
|
||||
values = append(values, fmt.Sprintf("(%s)", strings.Join(_values, ",")))
|
||||
}
|
||||
return fmt.Sprintf("(%s) \nVALUES %s", strings.Join(columns, ","), strings.Join(values, ","))
|
||||
}
|
||||
func (ar *ActiveRecord) compileSet() string {
|
||||
set := []string{}
|
||||
for key, _value := range ar.arSet {
|
||||
value, wrap := _value[0], _value[1]
|
||||
_column := key
|
||||
op := ""
|
||||
realColumnArr := strings.Split(key, " ")
|
||||
if len(realColumnArr) == 2 {
|
||||
_column = realColumnArr[0]
|
||||
op = realColumnArr[1]
|
||||
}
|
||||
if wrap.(bool) {
|
||||
if op != "" {
|
||||
set = append(set, fmt.Sprintf("%s = %s %s ?", ar.protectIdentifier(_column), ar.protectIdentifier(_column), op))
|
||||
} else {
|
||||
set = append(set, fmt.Sprintf("%s = ?", ar.protectIdentifier(_column)))
|
||||
}
|
||||
ar.values = append(ar.values, value)
|
||||
} else {
|
||||
set = append(set, fmt.Sprintf("%s = %s", ar.protectIdentifier(_column), value))
|
||||
}
|
||||
}
|
||||
return strings.Join(set, ",")
|
||||
}
|
||||
func (ar *ActiveRecord) compileGroupBy() string {
|
||||
groupBy := []string{}
|
||||
for _, key := range ar.arGroupBy {
|
||||
_key := strings.Split(key, ".")
|
||||
if len(_key) == 2 {
|
||||
groupBy = append(groupBy, fmt.Sprintf("%s.%s", ar.protectIdentifier(ar.checkPrefix(_key[0])), ar.protectIdentifier(_key[1])))
|
||||
} else {
|
||||
groupBy = append(groupBy, fmt.Sprintf("%s", ar.protectIdentifier(_key[0])))
|
||||
}
|
||||
}
|
||||
return strings.Join(groupBy, ",")
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) compileOrderBy() string {
|
||||
orderBy := []string{}
|
||||
for key, Type := range ar.arOrderBy {
|
||||
Type = strings.ToUpper(Type)
|
||||
_key := strings.Split(key, ".")
|
||||
if len(_key) == 2 {
|
||||
orderBy = append(orderBy, fmt.Sprintf("%s.%s %s", ar.protectIdentifier(ar.checkPrefix(_key[0])), ar.protectIdentifier(_key[1]), Type))
|
||||
|
||||
} else {
|
||||
orderBy = append(orderBy, fmt.Sprintf("%s %s", ar.protectIdentifier(_key[0]), Type))
|
||||
}
|
||||
}
|
||||
return strings.Join(orderBy, ",")
|
||||
}
|
||||
func (ar *ActiveRecord) compileWhere(where0 interface{}, leftWrap, rightWrap string, index int) string {
|
||||
|
||||
_where := []string{}
|
||||
if index == 0 {
|
||||
str := strings.ToUpper(strings.TrimSpace(leftWrap))
|
||||
if strings.Contains(str, "AND") || strings.Contains(str, "OR") {
|
||||
leftWrap = ""
|
||||
}
|
||||
}
|
||||
if reflect.TypeOf(where0).Kind() == reflect.String {
|
||||
return fmt.Sprintf(" %s %s %s ", leftWrap, where0, rightWrap)
|
||||
}
|
||||
where := where0.(map[string]interface{})
|
||||
for key, value := range where {
|
||||
k := ""
|
||||
k = strings.TrimSpace(key)
|
||||
_key := strings.SplitN(k, " ", 2)
|
||||
op := ""
|
||||
if len(_key) == 2 {
|
||||
op = _key[1]
|
||||
}
|
||||
keys := strings.Split(_key[0], ".")
|
||||
if len(keys) == 2 {
|
||||
k = ar.protectIdentifier(ar.checkPrefix(keys[0])) + "." + ar.protectIdentifier(keys[1])
|
||||
} else {
|
||||
k = ar.protectIdentifier(keys[0])
|
||||
}
|
||||
|
||||
if isArray(value) {
|
||||
if op != "" {
|
||||
op += " IN"
|
||||
} else {
|
||||
op = "IN"
|
||||
}
|
||||
op = strings.ToUpper(op)
|
||||
l := reflect.ValueOf(value).Len()
|
||||
|
||||
_v := []string{}
|
||||
for i := 0; i < l; i++ {
|
||||
_v = append(_v, "?")
|
||||
}
|
||||
_where = append(_where, fmt.Sprintf("%s %s (%s)", k, op, strings.Join(_v, ",")))
|
||||
for _, v := range *ar.interface2Slice(value) {
|
||||
ar.values = append(ar.values, v)
|
||||
}
|
||||
} else if isBool(value) {
|
||||
if op == "" {
|
||||
op = "="
|
||||
}
|
||||
op = strings.ToUpper(op)
|
||||
_v := 0
|
||||
if value.(bool) {
|
||||
_v = 1
|
||||
}
|
||||
_where = append(_where, fmt.Sprintf("%s %s ?", k, op))
|
||||
ar.values = append(ar.values, _v)
|
||||
} else if value == nil {
|
||||
if op == "" {
|
||||
op = "IS"
|
||||
}
|
||||
op = strings.ToUpper(op)
|
||||
_where = append(_where, fmt.Sprintf("%s %s NULL", k, op))
|
||||
} else {
|
||||
if op == "" {
|
||||
op = "="
|
||||
}
|
||||
op = strings.ToUpper(op)
|
||||
_where = append(_where, fmt.Sprintf("%s %s ?", k, op))
|
||||
ar.values = append(ar.values, value)
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf(" %s %s %s ", leftWrap, strings.Join(_where, " AND "), rightWrap)
|
||||
}
|
||||
func (ar *ActiveRecord) interface2Slice(data interface{}) (arr *[]interface{}) {
|
||||
arr = &[]interface{}{}
|
||||
val := reflect.ValueOf(data)
|
||||
if val.Kind() == reflect.Array || val.Kind() == reflect.Slice {
|
||||
for i := 0; i < val.Len(); i++ {
|
||||
e := val.Index(i)
|
||||
*arr = append(*arr, e.Interface())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (ar *ActiveRecord) compileSelect() string {
|
||||
selects := ar.arSelect
|
||||
columns := []string{}
|
||||
if len(selects) == 0 {
|
||||
selects = append(selects, []interface{}{"*", true})
|
||||
}
|
||||
for _, v := range selects {
|
||||
protect := v[1].(bool)
|
||||
value := strings.TrimSpace(v[0].(string))
|
||||
if value != "*" {
|
||||
info := strings.Split(value, ".")
|
||||
if len(info) == 2 {
|
||||
_v := ar.checkPrefix(info[0])
|
||||
if protect {
|
||||
info[0] = ar.protectIdentifier(_v)
|
||||
info[1] = ar.protectIdentifier(info[1])
|
||||
} else {
|
||||
info[0] = _v
|
||||
}
|
||||
value = strings.Join(info, ".")
|
||||
} else if protect {
|
||||
value = ar.protectIdentifier(value)
|
||||
}
|
||||
}
|
||||
columns = append(columns, value)
|
||||
}
|
||||
return strings.Join(columns, ",")
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) checkPrefix(v string) string {
|
||||
if strings.Contains(v, "(") || strings.Contains(v, ")") || strings.TrimSpace(v) == "*" {
|
||||
return v
|
||||
}
|
||||
if ar.tablePrefix != "" && !strings.Contains(v, ar.tablePrefix) {
|
||||
if _, exists := ar.asTable[v]; !exists {
|
||||
return ar.tablePrefix + v
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
func (ar *ActiveRecord) protectIdentifier(v string) string {
|
||||
if strings.Contains(v, "(") || strings.Contains(v, ")") || strings.TrimSpace(v) == "*" {
|
||||
return v
|
||||
}
|
||||
values := strings.Split(v, " ")
|
||||
if len(values) == 3 && strings.ToLower(values[1]) == "as" {
|
||||
return fmt.Sprintf("`%s` AS `%s`", values[0], values[2])
|
||||
}
|
||||
return fmt.Sprintf("`%s`", v)
|
||||
}
|
||||
func (ar *ActiveRecord) compileFrom(from, as string) string {
|
||||
if as != "" {
|
||||
ar.asTable[as] = true
|
||||
as = " AS " + ar.protectIdentifier(as) + " "
|
||||
}
|
||||
return ar.protectIdentifier(ar.checkPrefix(from)) + as
|
||||
}
|
||||
func (ar *ActiveRecord) compileJoin(table, as, on, type_ string) string {
|
||||
table_ := ""
|
||||
if as != "" {
|
||||
ar.asTable[table] = true
|
||||
table_ = ar.protectIdentifier(ar.checkPrefix(table)) + " AS " + ar.protectIdentifier(as)
|
||||
} else {
|
||||
table_ = ar.protectIdentifier(ar.checkPrefix(table))
|
||||
}
|
||||
a := strings.Split(on, "=")
|
||||
if len(a) == 2 {
|
||||
left := strings.Split(a[0], ".")
|
||||
right := strings.Split(a[1], ".")
|
||||
left[0] = ar.protectIdentifier(ar.checkPrefix(left[0]))
|
||||
left[1] = ar.protectIdentifier(left[1])
|
||||
right[0] = ar.protectIdentifier(ar.checkPrefix(right[0]))
|
||||
right[1] = ar.protectIdentifier(right[1])
|
||||
on = strings.Join(left, ".") + "=" + strings.Join(right, ".")
|
||||
}
|
||||
return fmt.Sprintf(" %s JOIN %s ON %s ", type_, table_, on)
|
||||
}
|
||||
|
||||
func (ar *ActiveRecord) getFrom() string {
|
||||
table := ar.compileFrom(ar.arFrom[0], ar.arFrom[1])
|
||||
for _, v := range ar.arJoin {
|
||||
table += ar.compileJoin(v[0], v[1], v[2], v[3])
|
||||
}
|
||||
return table
|
||||
}
|
||||
func (ar *ActiveRecord) getLimit() string {
|
||||
limit := ar.arLimit
|
||||
if limit != "" {
|
||||
limit = fmt.Sprintf("\nLIMIT %s", limit)
|
||||
}
|
||||
return limit
|
||||
}
|
||||
func (ar *ActiveRecord) getWhere() string {
|
||||
where := []string{}
|
||||
hasEmptyIn := false
|
||||
|
||||
for _, v := range ar.arWhere {
|
||||
for _, value := range v[0].(map[string]interface{}) {
|
||||
if isArray(value) && reflect.ValueOf(value).Len() == 0 {
|
||||
hasEmptyIn = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasEmptyIn {
|
||||
break
|
||||
}
|
||||
where = append(where, ar.compileWhere(v[0].(map[string]interface{}), v[1].(string), v[2].(string), v[3].(int)))
|
||||
}
|
||||
if hasEmptyIn {
|
||||
return "WHERE 0"
|
||||
}
|
||||
allWhere := strings.TrimSpace(strings.Join(where, ""))
|
||||
if allWhere != "" {
|
||||
allWhere = fmt.Sprintf("\nWHERE %s", allWhere)
|
||||
}
|
||||
return allWhere
|
||||
}
|
||||
|
||||
type ResultSet struct {
|
||||
rawRows *[]map[string][]byte
|
||||
LastInsertId int64
|
||||
RowsAffected int64
|
||||
}
|
||||
|
||||
func (rs *ResultSet) Init(rawRows *[]map[string][]byte) {
|
||||
if rawRows != nil {
|
||||
rs.rawRows = rawRows
|
||||
} else {
|
||||
rs.rawRows = &([]map[string][]byte{})
|
||||
}
|
||||
}
|
||||
func (rs *ResultSet) Len() int {
|
||||
return len(*rs.rawRows)
|
||||
}
|
||||
func (rs *ResultSet) MapRows(keyColumn string) (rowsMap map[string]map[string]string) {
|
||||
rowsMap = map[string]map[string]string{}
|
||||
for _, row := range *rs.rawRows {
|
||||
newRow := map[string]string{}
|
||||
for k, v := range row {
|
||||
newRow[k] = string(v)
|
||||
}
|
||||
rowsMap[newRow[keyColumn]] = newRow
|
||||
}
|
||||
return
|
||||
}
|
||||
func (rs *ResultSet) MapStructs(keyColumn string, strucT interface{}) (structsMap map[string]interface{}, err error) {
|
||||
structsMap = map[string]interface{}{}
|
||||
for _, row := range *rs.rawRows {
|
||||
newRow := map[string]string{}
|
||||
for k, v := range row {
|
||||
newRow[k] = string(v)
|
||||
}
|
||||
var _struct interface{}
|
||||
_struct, err = rs.mapToStruct(newRow, strucT)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
structsMap[newRow[keyColumn]] = _struct
|
||||
}
|
||||
return
|
||||
}
|
||||
func (rs *ResultSet) Rows() (rows []map[string]string) {
|
||||
rows = []map[string]string{}
|
||||
for _, row := range *rs.rawRows {
|
||||
newRow := map[string]string{}
|
||||
for k, v := range row {
|
||||
newRow[k] = string(v)
|
||||
}
|
||||
rows = append(rows, newRow)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (rs *ResultSet) Structs(strucT interface{}) (structs []interface{}, err error) {
|
||||
structs = []interface{}{}
|
||||
for _, row := range *rs.rawRows {
|
||||
newRow := map[string]string{}
|
||||
for k, v := range row {
|
||||
newRow[k] = string(v)
|
||||
}
|
||||
var _struct interface{}
|
||||
_struct, err = rs.mapToStruct(newRow, strucT)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
structs = append(structs, _struct)
|
||||
}
|
||||
return structs, nil
|
||||
}
|
||||
func (rs *ResultSet) Row() (row map[string]string) {
|
||||
row = map[string]string{}
|
||||
if rs.Len() > 0 {
|
||||
row = map[string]string{}
|
||||
for k, v := range (*rs.rawRows)[0] {
|
||||
row[k] = string(v)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (rs *ResultSet) Struct(strucT interface{}) (Struct interface{}, err error) {
|
||||
if rs.Len() > 0 {
|
||||
return rs.mapToStruct(rs.Row(), strucT)
|
||||
}
|
||||
return nil, errors.New("rs is empty")
|
||||
}
|
||||
func (rs *ResultSet) Values(column string) (values []string) {
|
||||
values = []string{}
|
||||
for _, row := range *rs.rawRows {
|
||||
values = append(values, string(row[column]))
|
||||
}
|
||||
return
|
||||
}
|
||||
func (rs *ResultSet) MapValues(keyColumn, valueColumn string) (values map[string]string) {
|
||||
values = map[string]string{}
|
||||
for _, row := range *rs.rawRows {
|
||||
values[string(row[keyColumn])] = string(row[valueColumn])
|
||||
}
|
||||
return
|
||||
}
|
||||
func (rs *ResultSet) Value(column string) (value string) {
|
||||
row := rs.Row()
|
||||
if row != nil {
|
||||
value, _ = row[column]
|
||||
}
|
||||
return
|
||||
}
|
||||
func (rs *ResultSet) mapToStruct(mapData map[string]string, Struct interface{}) (struCt interface{}, err error) {
|
||||
rv := reflect.New(reflect.TypeOf(Struct)).Elem()
|
||||
if reflect.TypeOf(Struct).Kind() != reflect.Struct {
|
||||
return nil, errors.New("v must be struct")
|
||||
}
|
||||
fieldType := rv.Type()
|
||||
for i, fieldCount := 0, rv.NumField(); i < fieldCount; i++ {
|
||||
fieldVal := rv.Field(i)
|
||||
if !fieldVal.CanSet() {
|
||||
continue
|
||||
}
|
||||
|
||||
structField := fieldType.Field(i)
|
||||
structTag := structField.Tag
|
||||
name := structTag.Get("column")
|
||||
|
||||
if _, ok := mapData[name]; !ok {
|
||||
continue
|
||||
}
|
||||
switch structField.Type.Kind() {
|
||||
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr:
|
||||
if val, err := strconv.ParseUint(mapData[name], 10, 64); err == nil {
|
||||
fieldVal.SetUint(val)
|
||||
}
|
||||
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
|
||||
if val, err := strconv.ParseInt(mapData[name], 10, 64); err == nil {
|
||||
fieldVal.SetInt(val)
|
||||
}
|
||||
case reflect.String:
|
||||
fieldVal.SetString(mapData[name])
|
||||
case reflect.Bool:
|
||||
val := false
|
||||
if mapData[name] == "1" {
|
||||
val = true
|
||||
}
|
||||
fieldVal.SetBool(val)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
if val, err := strconv.ParseFloat(mapData[name], 64); err == nil {
|
||||
fieldVal.SetFloat(val)
|
||||
}
|
||||
case reflect.Struct:
|
||||
if structField.Type.Name() == "Time" {
|
||||
local, _ := time.LoadLocation("Local")
|
||||
val, err := time.ParseInLocation("2006-01-02 15:04:05", mapData[name], local)
|
||||
if err == nil {
|
||||
fieldVal.Set(reflect.ValueOf(val))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv.Interface(), err
|
||||
}
|
||||
|
||||
type Cache interface {
|
||||
Set(key string, val []byte, expire uint) (err error)
|
||||
Get(key string) (data []byte, err error)
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
# mini-logger
|
||||
mini but flexible and powerful logger for go
|
||||
# Notice
|
||||
1.Do not call runtime.Goexit() in main , it will be blocking logger.Flush().
|
||||
# Features
|
||||
<ul>
|
||||
<li>Console</li>
|
||||
<li>File,supoort rotate base size</li>
|
||||
</ul>
|
||||
# Usage Example
|
||||
<pre>
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/snail007/mini-logger"
|
||||
"github.com/snail007/mini-logger/writers/console"
|
||||
"github.com/snail007/mini-logger/writers/files"
|
||||
)
|
||||
|
||||
var log logger.MiniLogger
|
||||
var accessLog logger.MiniLogger
|
||||
|
||||
//initLog
|
||||
func initLog() {
|
||||
var level uint8
|
||||
switch cfg.GetString("log.console-level") {
|
||||
case "debug":
|
||||
level = logger.AllLevels
|
||||
case "info":
|
||||
level = logger.InfoLevel | logger.WarnLevel | logger.ErrorLevel | logger.FatalLevel
|
||||
case "warn":
|
||||
level = logger.WarnLevel | logger.ErrorLevel | logger.FatalLevel
|
||||
case "error":
|
||||
level = logger.ErrorLevel | logger.FatalLevel
|
||||
case "fatal":
|
||||
level = logger.FatalLevel
|
||||
default:
|
||||
level = 0
|
||||
}
|
||||
log = logger.New(false, nil)
|
||||
log.AddWriter(console.NewDefault(), level)
|
||||
cfgF := files.GetDefaultFileConfig()
|
||||
cfgF.LogPath = cfg.GetString("log.dir")
|
||||
cfgF.MaxBytes = cfg.GetInt64("log.FileMaxSize")
|
||||
cfgF.MaxCount = cfg.GetInt("log.MaxCount")
|
||||
cfgLevels := cfg.GetStringSlice("log.level")
|
||||
if ok, _ := inArray("debug", cfgLevels); ok {
|
||||
cfgF.FileNameSet["debug"] = logger.AllLevels
|
||||
}
|
||||
if ok, _ := inArray("info", cfgLevels); ok {
|
||||
cfgF.FileNameSet["info"] = logger.InfoLevel
|
||||
}
|
||||
if ok, _ := inArray("error", cfgLevels); ok {
|
||||
cfgF.FileNameSet["error"] = logger.WarnLevel | logger.ErrorLevel | logger.FatalLevel
|
||||
}
|
||||
log.AddWriter(files.New(cfgF), logger.AllLevels)
|
||||
|
||||
accessLog = logger.New(false, nil)
|
||||
//accessLog.AddWriter(console.NewDefault(), logger.AllLevels)
|
||||
if cfg.GetBool("log.access") {
|
||||
accessCfg := files.GetDefaultFileConfig()
|
||||
accessCfg.LogPath = cfg.GetString("log.dir")
|
||||
accessCfg.MaxBytes = cfg.GetInt64("log.FileMaxSize")
|
||||
accessCfg.MaxCount = cfg.GetInt("log.MaxCount")
|
||||
accessCfg.FileNameSet = map[string]uint8{"access": logger.InfoLevel}
|
||||
accessLog.AddWriter(files.New(accessCfg), logger.InfoLevel)
|
||||
}
|
||||
|
||||
log.With(logger.Fields{"func": "getMqConnection", "call": "pools.Get"}).Errorf("fail,%s", err)
|
||||
}
|
||||
|
||||
//MiniLogger is a interface below:
|
||||
type MiniLogger interface {
|
||||
Debug(v ...interface{}) MiniLogger
|
||||
Info(v ...interface{}) MiniLogger
|
||||
Warn(v ...interface{}) MiniLogger
|
||||
Error(v ...interface{}) MiniLogger
|
||||
Fatal(v ...interface{})
|
||||
Debugf(format string, v ...interface{}) MiniLogger
|
||||
Infof(format string, v ...interface{}) MiniLogger
|
||||
Warnf(format string, v ...interface{}) MiniLogger
|
||||
Errorf(format string, v ...interface{}) MiniLogger
|
||||
Fatalf(format string, v ...interface{})
|
||||
Debugln(v ...interface{}) MiniLogger
|
||||
Infoln(v ...interface{}) MiniLogger
|
||||
Warnln(v ...interface{}) MiniLogger
|
||||
Errorln(v ...interface{}) MiniLogger
|
||||
Fatalln(v ...interface{})
|
||||
AddWriter(w Writer, levels uint8) MiniLogger
|
||||
Safe() MiniLogger
|
||||
Unsafe() MiniLogger
|
||||
With(fields Fields) MiniLogger
|
||||
}
|
||||
</pre>
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
DebugLevel uint8 = 1
|
||||
InfoLevel uint8 = 1 << 1
|
||||
WarnLevel uint8 = 1 << 2
|
||||
ErrorLevel uint8 = 1 << 3
|
||||
FatalLevel uint8 = 1 << 4
|
||||
AllLevels uint8 = byte(DebugLevel | InfoLevel | WarnLevel | ErrorLevel | FatalLevel)
|
||||
)
|
||||
|
||||
var (
|
||||
flush = &sync.WaitGroup{}
|
||||
exitchn = make(chan bool, 1)
|
||||
)
|
||||
|
||||
type Fields map[string]string
|
||||
type Writer interface {
|
||||
Write(e Entry)
|
||||
Init() error
|
||||
}
|
||||
|
||||
type Logger struct {
|
||||
writersMap *map[int][]*WrappedWriter
|
||||
mu sync.Mutex
|
||||
modeSafe bool
|
||||
wait sync.WaitGroup
|
||||
fields Fields
|
||||
fieldsString string
|
||||
}
|
||||
|
||||
type WrappedWriter struct {
|
||||
lock *sync.Mutex
|
||||
chn chan Entry
|
||||
writer Writer
|
||||
wait sync.WaitGroup
|
||||
}
|
||||
type Entry struct {
|
||||
Content string
|
||||
Timestamp int64
|
||||
Milliseconds int64
|
||||
TimestampMilliseconds int64
|
||||
Level uint8
|
||||
LevelString string
|
||||
Fields map[string]string
|
||||
FieldsString string
|
||||
}
|
||||
type MiniLogger interface {
|
||||
Debug(v ...interface{}) MiniLogger
|
||||
Info(v ...interface{}) MiniLogger
|
||||
Warn(v ...interface{}) MiniLogger
|
||||
Error(v ...interface{}) MiniLogger
|
||||
Fatal(v ...interface{})
|
||||
Debugf(format string, v ...interface{}) MiniLogger
|
||||
Infof(format string, v ...interface{}) MiniLogger
|
||||
Warnf(format string, v ...interface{}) MiniLogger
|
||||
Errorf(format string, v ...interface{}) MiniLogger
|
||||
Fatalf(format string, v ...interface{})
|
||||
Debugln(v ...interface{}) MiniLogger
|
||||
Infoln(v ...interface{}) MiniLogger
|
||||
Warnln(v ...interface{}) MiniLogger
|
||||
Errorln(v ...interface{}) MiniLogger
|
||||
Fatalln(v ...interface{})
|
||||
AddWriter(w Writer, levels uint8) MiniLogger
|
||||
Safe() MiniLogger
|
||||
Unsafe() MiniLogger
|
||||
With(fields Fields) MiniLogger
|
||||
}
|
||||
|
||||
func getLevelString(level uint8) string {
|
||||
switch level {
|
||||
case DebugLevel:
|
||||
return "DEBUG"
|
||||
case InfoLevel:
|
||||
return "INFO"
|
||||
case WarnLevel:
|
||||
return "WARN"
|
||||
case ErrorLevel:
|
||||
return "ERROR"
|
||||
case FatalLevel:
|
||||
return "FATAL"
|
||||
}
|
||||
return "UNKOWN"
|
||||
}
|
||||
|
||||
// New returns a new logger
|
||||
//modeSafe when false : must call logger.Flush() in main defer
|
||||
//if not do that, may be lost message,but this mode has a highest performance
|
||||
//when true : each message can be processed , but this mode may be has a little lower performance
|
||||
//beacuse of logger must wait for all writers process done with each messsage.
|
||||
//note: if you do logging before call os.Exit(), you had better to set safeMode to true before call os.Exit().
|
||||
//fields same as With()'s args,more about fields to see With().
|
||||
func New(modeSafe bool, fields Fields) MiniLogger {
|
||||
if fields == nil {
|
||||
fields = Fields{}
|
||||
}
|
||||
return &Logger{
|
||||
fields: fields,
|
||||
fieldsString: "",
|
||||
mu: sync.Mutex{},
|
||||
modeSafe: modeSafe,
|
||||
wait: sync.WaitGroup{},
|
||||
writersMap: &map[int][]*WrappedWriter{
|
||||
int(DebugLevel): []*WrappedWriter{},
|
||||
int(InfoLevel): []*WrappedWriter{},
|
||||
int(WarnLevel): []*WrappedWriter{},
|
||||
int(ErrorLevel): []*WrappedWriter{},
|
||||
int(FatalLevel): []*WrappedWriter{},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
//Flush wait for process all left entry
|
||||
func Flush() {
|
||||
exitchn <- true
|
||||
flush.Wait()
|
||||
}
|
||||
|
||||
//With return a new MiniLogger,which it's modeSafe inited same as caller MiniLogger,
|
||||
//and revecived levels same as caller MiniLogger,
|
||||
//and set it's fields.
|
||||
//you can use it as a standard MiniLogger.
|
||||
func (l *Logger) With(fields Fields) MiniLogger {
|
||||
for k, v := range l.fields {
|
||||
fields[k] = v
|
||||
}
|
||||
s, _ := json.Marshal(fields)
|
||||
return &Logger{
|
||||
mu: sync.Mutex{},
|
||||
modeSafe: l.modeSafe,
|
||||
wait: sync.WaitGroup{},
|
||||
writersMap: l.writersMap,
|
||||
fields: fields,
|
||||
fieldsString: string(s),
|
||||
}
|
||||
}
|
||||
|
||||
//Unsafe : if you call Unsafe() , then you must call logger.Flush() in main defer
|
||||
//if not do that, may be lost message,but this mode has a highest performance
|
||||
//note: if you do logging before call os.Exit(), you had better to call Safe() before call os.Exit().
|
||||
//you call call func Safe() or Unsafe() in any where any time to switch safe mode.
|
||||
|
||||
func (l *Logger) Unsafe() MiniLogger {
|
||||
l.modeSafe = false
|
||||
return l
|
||||
}
|
||||
|
||||
//Safe : if you call Safe(), each message can be processed immediately,
|
||||
//but this mode may be has lower performance,beacuse of logger must wait for
|
||||
//all writers process done with each messsage.
|
||||
//note: if you do logging before call os.Exit(), you had better to call Safe() before call os.Exit().
|
||||
//you call func Safe() or Unsafe() in any where any time to switch safe mode.
|
||||
func (l *Logger) Safe() MiniLogger {
|
||||
l.modeSafe = true
|
||||
return l
|
||||
}
|
||||
func (l *Logger) AddWriter(writer Writer, levels byte) MiniLogger {
|
||||
w := &WrappedWriter{
|
||||
lock: &sync.Mutex{},
|
||||
writer: writer,
|
||||
chn: make(chan Entry, 1024),
|
||||
}
|
||||
m := *l.writersMap
|
||||
if DebugLevel&levels == DebugLevel {
|
||||
m[int(DebugLevel)] = append(m[int(DebugLevel)], w)
|
||||
}
|
||||
if InfoLevel&levels == InfoLevel {
|
||||
m[int(InfoLevel)] = append(m[int(InfoLevel)], w)
|
||||
}
|
||||
if WarnLevel&levels == WarnLevel {
|
||||
m[int(WarnLevel)] = append(m[int(WarnLevel)], w)
|
||||
}
|
||||
if ErrorLevel&levels == ErrorLevel {
|
||||
m[int(ErrorLevel)] = append(m[int(ErrorLevel)], w)
|
||||
}
|
||||
if FatalLevel&levels == FatalLevel {
|
||||
m[int(FatalLevel)] = append(m[int(FatalLevel)], w)
|
||||
}
|
||||
flush.Add(1)
|
||||
go func() {
|
||||
defer func() {
|
||||
_ = recover()
|
||||
flush.Done()
|
||||
}()
|
||||
if err := w.writer.Init(); err != nil {
|
||||
fmt.Printf("init writer fail,%s", err)
|
||||
return
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case entry, ok := <-w.chn:
|
||||
if ok {
|
||||
w.writer.Write(entry)
|
||||
if l.modeSafe {
|
||||
l.wait.Done()
|
||||
}
|
||||
if entry.Level == FatalLevel {
|
||||
os.Exit(0)
|
||||
}
|
||||
} else {
|
||||
return
|
||||
}
|
||||
case exit := <-exitchn:
|
||||
if exit {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return l
|
||||
}
|
||||
func (l *Logger) callWriter(level byte, t, foramt string, v ...interface{}) {
|
||||
if level == FatalLevel {
|
||||
l.Safe()
|
||||
}
|
||||
c := ""
|
||||
if t == "f" && len(v) == 0 {
|
||||
v = append(v, foramt)
|
||||
foramt = "%s"
|
||||
}
|
||||
switch t {
|
||||
case "ln":
|
||||
c = fmt.Sprintln(v...)
|
||||
case "f":
|
||||
c = fmt.Sprintf(foramt, v...)
|
||||
default:
|
||||
c = fmt.Sprint(v...)
|
||||
}
|
||||
m := *l.writersMap
|
||||
for _, w := range m[int(level)] {
|
||||
now := time.Now().UnixNano()
|
||||
nowUnix := time.Now().Unix()
|
||||
mili := (now / 1000000) - nowUnix*1000
|
||||
w.chn <- Entry{
|
||||
Timestamp: nowUnix,
|
||||
TimestampMilliseconds: now / 10000000,
|
||||
Milliseconds: mili,
|
||||
Content: c,
|
||||
Level: level,
|
||||
LevelString: getLevelString(level),
|
||||
Fields: l.fields,
|
||||
FieldsString: l.fieldsString,
|
||||
}
|
||||
if l.modeSafe {
|
||||
l.wait.Add(1)
|
||||
}
|
||||
}
|
||||
if l.modeSafe {
|
||||
l.wait.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Logger) Fatal(v ...interface{}) {
|
||||
l.callWriter(FatalLevel, "", "", v...)
|
||||
}
|
||||
|
||||
func (l *Logger) Error(v ...interface{}) MiniLogger {
|
||||
l.callWriter(ErrorLevel, "", "", v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Warn(v ...interface{}) MiniLogger {
|
||||
l.callWriter(WarnLevel, "", "", v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Info(v ...interface{}) MiniLogger {
|
||||
l.callWriter(InfoLevel, "", "", v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Debug(v ...interface{}) MiniLogger {
|
||||
l.callWriter(DebugLevel, "", "", v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Fatalf(format string, v ...interface{}) {
|
||||
l.callWriter(FatalLevel, "f", format, v...)
|
||||
}
|
||||
|
||||
func (l *Logger) Errorf(format string, v ...interface{}) MiniLogger {
|
||||
l.callWriter(ErrorLevel, "f", format, v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Warnf(format string, v ...interface{}) MiniLogger {
|
||||
l.callWriter(WarnLevel, "f", format, v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Infof(format string, v ...interface{}) MiniLogger {
|
||||
l.callWriter(InfoLevel, "f", format, v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Debugf(format string, v ...interface{}) MiniLogger {
|
||||
l.callWriter(DebugLevel, "f", format, v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Fatalln(v ...interface{}) {
|
||||
l.callWriter(FatalLevel, "ln", "", v...)
|
||||
}
|
||||
|
||||
func (l *Logger) Errorln(v ...interface{}) MiniLogger {
|
||||
l.callWriter(ErrorLevel, "ln", "", v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Warnln(v ...interface{}) MiniLogger {
|
||||
l.callWriter(WarnLevel, "ln", "", v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Infoln(v ...interface{}) MiniLogger {
|
||||
l.callWriter(InfoLevel, "ln", "", v...)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) Debugln(v ...interface{}) MiniLogger {
|
||||
l.callWriter(DebugLevel, "ln", "", v...)
|
||||
return l
|
||||
}
|
||||
Generated
Vendored
Executable
+75
@@ -0,0 +1,75 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"encoding/json"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/snail007/mini-logger"
|
||||
)
|
||||
|
||||
const (
|
||||
T_JSON = iota
|
||||
T_TEXT
|
||||
)
|
||||
|
||||
type ConsoleWriterConfig struct {
|
||||
Format string
|
||||
Type int
|
||||
}
|
||||
type ConsoleWriter struct {
|
||||
c ConsoleWriterConfig
|
||||
}
|
||||
|
||||
func New(config ConsoleWriterConfig) *ConsoleWriter {
|
||||
return &ConsoleWriter{
|
||||
c: config,
|
||||
}
|
||||
}
|
||||
func NewDefault() *ConsoleWriter {
|
||||
return &ConsoleWriter{
|
||||
c: ConsoleWriterConfig{
|
||||
Format: "[{level}] [{date} {time}.{mili}] {fields} {text}",
|
||||
Type: T_TEXT,
|
||||
},
|
||||
}
|
||||
}
|
||||
func (w *ConsoleWriter) Init() (err error) {
|
||||
return
|
||||
}
|
||||
func (w *ConsoleWriter) Write(e logger.Entry) {
|
||||
fg := color.New(color.FgHiWhite).SprintFunc()
|
||||
switch e.Level {
|
||||
case logger.InfoLevel:
|
||||
fg = color.New(color.FgHiGreen).SprintFunc()
|
||||
case logger.WarnLevel:
|
||||
fg = color.New(color.FgHiYellow).SprintFunc()
|
||||
case logger.ErrorLevel:
|
||||
fg = color.New(color.FgHiRed).SprintFunc()
|
||||
case logger.FatalLevel:
|
||||
fg = color.New(color.FgHiRed, color.FgHiMagenta).SprintFunc()
|
||||
}
|
||||
date := time.Unix(e.Timestamp, 0).Format("2006/01/02")
|
||||
time := time.Unix(e.Timestamp, 0).Format("15:04:05")
|
||||
var c string
|
||||
if w.c.Type == T_TEXT {
|
||||
c = strings.Replace(w.c.Format, "{level}", fmt.Sprintf("%-5s", e.LevelString), -1)
|
||||
c = strings.Replace(c, "{date}", date, -1)
|
||||
c = strings.Replace(c, "{time}", time, -1)
|
||||
c = strings.Replace(c, "{fields}", e.FieldsString, -1)
|
||||
c = strings.Replace(c, "{mili}", fmt.Sprintf("%03d", e.Milliseconds), -1)
|
||||
c = strings.Replace(c, "{text}", e.Content, -1)
|
||||
} else if w.c.Type == T_JSON {
|
||||
e.LevelString = strings.TrimRight(e.LevelString, " ")
|
||||
e.FieldsString = ""
|
||||
v, _ := json.Marshal(e)
|
||||
c = string(v)
|
||||
} else {
|
||||
return
|
||||
}
|
||||
fmt.Fprintln(os.Stdout, fg(c))
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bufio"
|
||||
|
||||
"os"
|
||||
|
||||
"path"
|
||||
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"strconv"
|
||||
|
||||
"path/filepath"
|
||||
|
||||
"github.com/snail007/mini-logger"
|
||||
)
|
||||
|
||||
const (
|
||||
T_JSON = iota
|
||||
T_TEXT
|
||||
)
|
||||
|
||||
type FileConfig struct {
|
||||
IsRotate bool
|
||||
MaxBytes int64
|
||||
MaxCount int
|
||||
LogPath string
|
||||
FileNameSet map[string]uint8
|
||||
IsCompress bool
|
||||
Type int
|
||||
Format string
|
||||
}
|
||||
type bufWriter struct {
|
||||
file *os.File
|
||||
writer *bufio.Writer
|
||||
}
|
||||
type FileWriter struct {
|
||||
filePtrMap map[string]*bufWriter
|
||||
c FileConfig
|
||||
}
|
||||
|
||||
func New(config FileConfig) *FileWriter {
|
||||
return &FileWriter{
|
||||
c: config,
|
||||
filePtrMap: map[string]*bufWriter{},
|
||||
}
|
||||
}
|
||||
|
||||
func NewDefault() *FileWriter {
|
||||
return &FileWriter{
|
||||
filePtrMap: map[string]*bufWriter{},
|
||||
c: GetDefaultFileConfig(),
|
||||
}
|
||||
}
|
||||
|
||||
//GetDefaultFileConfig config for new FileWriter
|
||||
//IsRotate : whether to rotate log file.
|
||||
//MaxBytes : when RotateType is file.T_SIZE ,this need to be set.
|
||||
//MaxCount : how many log files can be remain.
|
||||
//LogPath : the folder which store log files,must be exists.
|
||||
//FileNameSet : key is filename of log file,no extesion.value is levels
|
||||
//IsCompress : whether to compress rotate log file.
|
||||
//Type:output format,should be files.T_JSON or files.T_TEXT
|
||||
//Format:when Type is files.T_TEXT,this can setting output text format,
|
||||
// default is : [{level}] [{date} {time}.{mili}] {text} {fields}
|
||||
func GetDefaultFileConfig() FileConfig {
|
||||
return FileConfig{
|
||||
IsRotate: true,
|
||||
MaxBytes: 100 * 1024 * 1024,
|
||||
MaxCount: 10,
|
||||
LogPath: "log",
|
||||
FileNameSet: map[string]uint8{
|
||||
"info": logger.InfoLevel,
|
||||
"error": logger.WarnLevel | logger.ErrorLevel | logger.FatalLevel,
|
||||
},
|
||||
IsCompress: true,
|
||||
Type: T_JSON,
|
||||
Format: "[{level}] [{date} {time}.{mili}] {text} {fields}",
|
||||
}
|
||||
}
|
||||
func getFilePath(logPath, filename string) string {
|
||||
|
||||
return path.Join(logPath, filename+".log")
|
||||
|
||||
}
|
||||
func (w *FileWriter) Init() (err error) {
|
||||
if _, err := os.Stat(w.c.LogPath); os.IsNotExist(err) {
|
||||
os.Mkdir(w.c.LogPath, 0700)
|
||||
}
|
||||
for filename := range w.c.FileNameSet {
|
||||
f, err := os.OpenFile(getFilePath(w.c.LogPath, filename), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bf := bufio.NewWriter(f)
|
||||
w.filePtrMap[filename] = &bufWriter{
|
||||
file: f,
|
||||
writer: bf,
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (w *FileWriter) Write(e logger.Entry) {
|
||||
for filename, levels := range w.c.FileNameSet {
|
||||
if e.Level&levels == e.Level {
|
||||
date := time.Unix(e.Timestamp, 0).Format("2006/01/02")
|
||||
time := time.Unix(e.Timestamp, 0).Format("15:04:05")
|
||||
var c string
|
||||
if w.c.Type == T_TEXT {
|
||||
c = strings.Replace(w.c.Format, "{level}", fmt.Sprintf("%-5s", e.LevelString), -1)
|
||||
c = strings.Replace(c, "{date}", date, -1)
|
||||
c = strings.Replace(c, "{time}", time, -1)
|
||||
c = strings.Replace(c, "{fields}", e.FieldsString, -1)
|
||||
c = strings.Replace(c, "{mili}", fmt.Sprintf("%03d", e.Milliseconds), -1)
|
||||
c = strings.Replace(c, "{text}", e.Content, -1)
|
||||
} else if w.c.Type == T_JSON {
|
||||
e.LevelString = strings.TrimRight(e.LevelString, " ")
|
||||
e.FieldsString = ""
|
||||
v, _ := json.Marshal(e)
|
||||
c = string(v)
|
||||
} else {
|
||||
return
|
||||
}
|
||||
w.filePtrMap[filename].writer.WriteString(fmt.Sprintln(c))
|
||||
w.filePtrMap[filename].writer.Flush()
|
||||
if w.c.IsRotate {
|
||||
var filepath = getFilePath(w.c.LogPath, filename)
|
||||
if stat, err := os.Stat(filepath); err == nil {
|
||||
if stat.Size() > w.c.MaxBytes {
|
||||
w.filePtrMap[filename].file.Close()
|
||||
var i = findI(w, filename)
|
||||
var p = ""
|
||||
if w.c.IsCompress {
|
||||
p = path.Join(w.c.LogPath, fmt.Sprintf("%s.%d", filename, i)+".log.gz")
|
||||
} else {
|
||||
p = path.Join(w.c.LogPath, fmt.Sprintf("%s.%d", filename, i)+".log")
|
||||
}
|
||||
if ok, err := exists(p); (err == nil && !ok) || err != nil {
|
||||
if err != nil {
|
||||
fmt.Printf("ERROR fail to get stat of log file,%s", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for k := i - w.c.MaxCount; k >= 0; k-- {
|
||||
p1 := getFilePath(w.c.LogPath, fmt.Sprintf("%s.%d", filename, k))
|
||||
p2 := p1 + ".gz"
|
||||
p1e, _ := exists(p1)
|
||||
p2e, _ := exists(p2)
|
||||
os.Remove(p1)
|
||||
os.Remove(p2)
|
||||
if !p1e && !p2e {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
newfilepath := getFilePath(w.c.LogPath, fmt.Sprintf("%s.%d", filename, i))
|
||||
e := os.Rename(filepath, newfilepath)
|
||||
if e != nil {
|
||||
fmt.Printf("ERROR fail to Rename log file,%s", e)
|
||||
return
|
||||
}
|
||||
if w.c.IsCompress {
|
||||
go func() {
|
||||
f, _ := os.OpenFile(newfilepath+".gz", os.O_CREATE|os.O_WRONLY, 0600)
|
||||
rf, _ := os.OpenFile(newfilepath, os.O_RDONLY, 0600)
|
||||
gz, err := gzip.NewWriterLevel(f, gzip.BestCompression)
|
||||
b, _ := ioutil.ReadAll(rf)
|
||||
if err == nil {
|
||||
gz.Write(b)
|
||||
gz.Flush()
|
||||
gz.Close()
|
||||
f.Close()
|
||||
rf.Close()
|
||||
os.Remove(newfilepath)
|
||||
} else {
|
||||
fmt.Printf("ERROR fail to compress log file,%s", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
f, e := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
|
||||
if e != nil {
|
||||
fmt.Println("ERROR fail to create log file")
|
||||
return
|
||||
}
|
||||
bf := bufio.NewWriter(f)
|
||||
w.filePtrMap[filename] = &bufWriter{
|
||||
file: f,
|
||||
writer: bf,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func exists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return true, err
|
||||
}
|
||||
func findI(w *FileWriter, filename string) int {
|
||||
subfix := ""
|
||||
if w.c.IsCompress {
|
||||
subfix = ".gz"
|
||||
}
|
||||
p := w.c.LogPath + "/" + filename + ".*.log" + subfix
|
||||
files, _ := filepath.Glob(p)
|
||||
l := len(files)
|
||||
if l == 0 {
|
||||
return 0
|
||||
}
|
||||
re := regexp.MustCompile(filename + "\\.(\\d+)\\.log" + subfix)
|
||||
matched := re.FindStringSubmatch(files[l-1])
|
||||
if len(matched) == 2 {
|
||||
i, _ := strconv.Atoi(matched[1])
|
||||
return i + 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
Reference in New Issue
Block a user