diff --git a/LICENSE b/LICENSE index d22d0ed..a1e477e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,232 +1,21 @@ -GNU GENERAL PUBLIC LICENSE -Version 3, 29 June 2007 - -Copyright © 2007 Free Software Foundation, Inc. - -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. - - appcore - Copyright (C) 2025 go - - 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 . - -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: - - appcore Copyright (C) 2025 go - 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 . - -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 . +The MIT License (Expat) + +Copyright (c) Patial Tech + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/crypto/argon2.go b/crypto/argon2.go new file mode 100644 index 0000000..6b492ba --- /dev/null +++ b/crypto/argon2.go @@ -0,0 +1,59 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package crypto + +import ( + "bytes" + "encoding/base64" + + "golang.org/x/crypto/argon2" +) + +const ( + a2KeyMem = 19456 // 1024*19 + a2KeyLen = 32 +) + +func argon2Hash(pwd, salt []byte) []byte { + // https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + // m=19456 (19 MiB), t=2, p=1 + return argon2.IDKey(pwd, salt, 2, a2KeyMem, 1, a2KeyLen) +} + +// PasswordHash using Argon2id +// +// https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#argon2id +func PasswordHash(pwd string) (hash, salt string, err error) { + var sl []byte + sl, err = RandomBytes(a2KeyLen) + if err != nil { + return + } + + // Generate hash + h := argon2Hash([]byte(pwd), sl) + hash = base64.StdEncoding.EncodeToString(h) + salt = base64.StdEncoding.EncodeToString(sl) + return +} + +func ComparePasswordHash(pwd, hash, salt string) (bool, error) { + var h, s []byte + var err error + + if h, err = base64.StdEncoding.DecodeString(hash); err != nil { + return false, err + } + + if s, err = base64.StdEncoding.DecodeString(salt); err != nil { + return false, err + } + + // Generate hash for comparison. + ph := argon2Hash([]byte(pwd), s) + + // Compare the generated hash with the stored hash. + // If they don't match return error. + return bytes.Equal(h, ph), nil +} diff --git a/crypto/argon2_test.go b/crypto/argon2_test.go new file mode 100644 index 0000000..193f682 --- /dev/null +++ b/crypto/argon2_test.go @@ -0,0 +1,27 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package crypto + +import "testing" + +func TestPasswordHash(t *testing.T) { + pwd := "MY Bingo pwd" + hash, salt, err := PasswordHash(pwd) + if err != nil { + t.Error(err) + return + } + + if hash == "" || salt == "" { + t.Error("either hash or password is empty") + return + } + + if ok, err := ComparePasswordHash(pwd, string(hash), string(salt)); err != nil { + t.Error(err) + } else if !ok { + t.Error("supposed to match") + } + +} diff --git a/crypto/ed25519.go b/crypto/ed25519.go new file mode 100644 index 0000000..7132809 --- /dev/null +++ b/crypto/ed25519.go @@ -0,0 +1,102 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package crypto + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "encoding/pem" + "errors" +) + +// NewPersistedED25519 public & private keys +func NewPersistedED25519() ([]byte, []byte, error) { + pub, prv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return nil, nil, err + } + + // marshal public key + pubB, err := marshalEdPublicKey(pub) + if err != nil { + return nil, nil, err + } + + // marshal private key + prvB, err := marshalEdPrivateKey(prv) + if err != nil { + return nil, nil, err + } + + // done + return pubB, prvB, nil +} + +func marshalEdPrivateKey(key ed25519.PrivateKey) ([]byte, error) { + b, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + return nil, err + } + enc := pem.EncodeToMemory( + &pem.Block{ + Type: "PRIVATE KEY", + Bytes: b, + }, + ) + return enc, nil +} + +func ParseEdPrivateKey(d []byte) (ed25519.PrivateKey, error) { + block, _ := pem.Decode(d) + if block == nil { + return nil, errors.New("failed to parse PEM block containing the key") + } + + b, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, err + } + + switch pub := b.(type) { + case ed25519.PrivateKey: + return pub, nil + default: + return nil, errors.New("key type is not RSA") + } + +} + +func marshalEdPublicKey(key ed25519.PublicKey) ([]byte, error) { + b, err := x509.MarshalPKIXPublicKey(key) + if err != nil { + return nil, err + } + enc := pem.EncodeToMemory( + &pem.Block{ + Type: "PUBLIC KEY", + Bytes: b, + }, + ) + return enc, nil +} + +func ParseEdPublicKey(d []byte) (ed25519.PublicKey, error) { + block, _ := pem.Decode(d) + if block == nil { + return nil, errors.New("failed to parse PEM block containing the key") + } + + b, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return nil, err + } + + switch pub := b.(type) { + case ed25519.PublicKey: + return pub, nil + default: + return nil, errors.New("key type is not RSA") + } +} diff --git a/crypto/ed25519_test.go b/crypto/ed25519_test.go new file mode 100644 index 0000000..2e150b9 --- /dev/null +++ b/crypto/ed25519_test.go @@ -0,0 +1,19 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package crypto + +import ( + "testing" +) + +func TestGenerate(t *testing.T) { + public, private, err := NewPersistedED25519() + if err != nil { + t.Error(err) + } else { + println(string(public)) + println(string(private)) + } + +} diff --git a/crypto/encryption.go b/crypto/encryption.go new file mode 100644 index 0000000..49f2bc3 --- /dev/null +++ b/crypto/encryption.go @@ -0,0 +1,96 @@ +package crypto + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "fmt" + "io" +) + +// NewEncryptionKey will generate new key as base64 encoded string +// +// should be of 16, 24 or 32 bytes in length +func NewEncryptionKey(size uint8) (string, error) { + b, err := RandomBytes(size) + if err != nil { + return "", err + } + + return base64.StdEncoding.EncodeToString(b), nil +} + +func decodeEncryptionKey(str string) ([]byte, error) { + return base64.StdEncoding.DecodeString(str) +} + +// Encrypt text using the encyption key +func Encrypt(key, text string) (string, error) { + b, err := decodeEncryptionKey(key) + if err != nil { + return "", fmt.Errorf("decrypted base64 string: %w", err) + } + + gcm, err := getGCM(b) + if err != nil { + return "", err + } + + // create a nonce. Nonce should be from GCM + nonce := make([]byte, gcm.NonceSize()) + if _, err = io.ReadFull(rand.Reader, nonce); err != nil { + return "", err + } + + // encrypt the data using gcm.Seal + ciphertext := gcm.Seal(nonce, nonce, []byte(text), nil) // prefix nonce to the ciphertext + return fmt.Sprintf("%x", ciphertext), nil +} + +// Decrypt text using the encryption key +func Decrypt(key, text string) (string, error) { + b, err := decodeEncryptionKey(key) + if err != nil { + return "", fmt.Errorf("decrypted base64 string: %w", err) + } + + // create a new Cipher Block from the key + gcm, err := getGCM(b) + if err != nil { + return "", err + } + + nonceSize := gcm.NonceSize() + enc, err := hex.DecodeString(text) + if err != nil { + return "", err + } + nonce, ciphertext := enc[:nonceSize], enc[nonceSize:] + + // decrypt + plaintext, err := gcm.Open(nil, nonce, ciphertext, nil) + if err != nil { + return "", err + } + + return string(plaintext), nil +} + +func getGCM(key []byte) (gcm cipher.AEAD, err error) { + // cipher block from the key + b, err := aes.NewCipher(key) + if err != nil { + return gcm, err + } + + // GCM - https://en.wikipedia.org/wiki/Galois/Counter_Mode + // https://golang.org/pkg/crypto/cipher/#NewGCM + gcm, err = cipher.NewGCM(b) + if err != nil { + return gcm, err + } + + return gcm, nil +} diff --git a/crypto/encryption_test.go b/crypto/encryption_test.go new file mode 100644 index 0000000..c96fd8f --- /dev/null +++ b/crypto/encryption_test.go @@ -0,0 +1,35 @@ +package crypto + +import ( + "fmt" + "testing" +) + +func TestNewEncryptionKey(t *testing.T) { + if key, err := NewEncryptionKey(32); err != nil { + t.Error(err) + } else { + fmt.Println(key) + } +} + +func TestEncryptDecrypt(t *testing.T) { + text := "Hellp World!" + key := "Laumw6mvWwrc8Q1SZQYCdiVr/dDBpjDdpaI6v4WvWSw=" + + // crypt + crypted, err := Encrypt(key, text) + if err != nil { + t.Errorf("Encrypt failed: %v", err) + } + + decrypted, err := Decrypt(key, crypted) + if err != nil { + t.Errorf("Decrypt failed: %v", err) + } + + if string(decrypted) != text { + t.Errorf("Decrypted text does not match original") + } + +} diff --git a/crypto/hash.go b/crypto/hash.go new file mode 100644 index 0000000..6c64109 --- /dev/null +++ b/crypto/hash.go @@ -0,0 +1,27 @@ +package crypto + +import ( + "crypto/md5" + "crypto/sha256" + "encoding/hex" +) + +// MD5 is generally faster to compute than SHA-256 +func MD5(b []byte) string { + hash := md5.Sum(b) + return hex.EncodeToString(hash[:]) +} + +/* +func MD5Int(b []byte) uint64 { + n := new(big.Int) + n.SetString(MD5(b), 16) + return n.Uint64() +} +*/ + +// SHA256 Sum256 is generally preferred over md5.hash due to its superior security and resistance to collision attacks +func SHA256(b []byte) string { + hash := sha256.Sum256(b) + return hex.EncodeToString(hash[:]) +} diff --git a/crypto/hash_test.go b/crypto/hash_test.go new file mode 100644 index 0000000..9e53c42 --- /dev/null +++ b/crypto/hash_test.go @@ -0,0 +1,25 @@ +package crypto + +import "testing" + +func TestMD5(t *testing.T) { + b := []byte("hello there") + h := MD5(b) + if h == "" { + t.Error("failed to hasg") + return + } + + println(h) +} + +func TestSha256(t *testing.T) { + b := []byte("hello there") + h := SHA256(b) + if h == "" { + t.Error("failed to hasg") + return + } + + println(h) +} diff --git a/crypto/random.go b/crypto/random.go new file mode 100644 index 0000000..e08c83d --- /dev/null +++ b/crypto/random.go @@ -0,0 +1,24 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package crypto + +import ( + "crypto/rand" + "encoding/hex" +) + +// RandomBytes generates totally random bytes, each byte is generated by [0,255] range +func RandomBytes(length uint8) ([]byte, error) { + buf := make([]byte, length) + _, err := rand.Read(buf) + return buf, err +} + +func RandomBytesHex(length uint8) (string, error) { + if b, err := RandomBytes(length); err != nil { + return "", err + } else { + return hex.EncodeToString(b), nil + } +} diff --git a/crypto/random_test.go b/crypto/random_test.go new file mode 100644 index 0000000..bde7e44 --- /dev/null +++ b/crypto/random_test.go @@ -0,0 +1,26 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package crypto + +import ( + "encoding/base64" + "fmt" + "testing" +) + +func TestRandomBytes(t *testing.T) { + if key, err := RandomBytes(32); err != nil { + t.Error(err) + } else { + fmt.Println(base64.StdEncoding.EncodeToString(key)) + } +} + +func TestRandomBytesHex(t *testing.T) { + if key, err := RandomBytesHex(32); err != nil { + t.Error(err) + } else { + fmt.Println(key) + } +} diff --git a/dotenv/parser.go b/dotenv/parser.go new file mode 100644 index 0000000..1d68e21 --- /dev/null +++ b/dotenv/parser.go @@ -0,0 +1,282 @@ +package dotenv + +import ( + "bytes" + "errors" + "fmt" + "os" + "regexp" + "strings" + "unicode" +) + +// +// ported from https://github.com/joho/godotenv/blob/main/parser.go +// + +const ( + charComment = '#' + prefixSingleQuote = '\'' + prefixDoubleQuote = '"' + + exportPrefix = "export" +) + +func parseBytes(src []byte, out map[string]string) error { + src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1) + cutset := src + for { + cutset = getStatementStart(cutset) + if cutset == nil { + // reached end of file + break + } + + key, left, err := locateKeyName(cutset) + if err != nil { + return err + } + + value, left, err := extractVarValue(left, out) + if err != nil { + return err + } + + out[key] = value + cutset = left + } + + return nil +} + +// getStatementPosition returns position of statement begin. +// +// It skips any comment line or non-whitespace character. +func getStatementStart(src []byte) []byte { + pos := indexOfNonSpaceChar(src) + if pos == -1 { + return nil + } + + src = src[pos:] + if src[0] != charComment { + return src + } + + // skip comment section + pos = bytes.IndexFunc(src, isCharFunc('\n')) + if pos == -1 { + return nil + } + + return getStatementStart(src[pos:]) +} + +// locateKeyName locates and parses key name and returns rest of slice +func locateKeyName(src []byte) (key string, cutset []byte, err error) { + // trim "export" and space at beginning + src = bytes.TrimLeftFunc(src, isSpace) + if bytes.HasPrefix(src, []byte(exportPrefix)) { + trimmed := bytes.TrimPrefix(src, []byte(exportPrefix)) + if bytes.IndexFunc(trimmed, isSpace) == 0 { + src = bytes.TrimLeftFunc(trimmed, isSpace) + } + } + + // locate key name end and validate it in single loop + offset := 0 +loop: + for i, char := range src { + rchar := rune(char) + if isSpace(rchar) { + continue + } + + switch char { + case '=', ':': + // library also supports yaml-style value declaration + key = string(src[0:i]) + offset = i + 1 + break loop + case '_': + default: + // variable name should match [A-Za-z0-9_.] + if unicode.IsLetter(rchar) || unicode.IsNumber(rchar) || rchar == '.' { + continue + } + + return "", nil, fmt.Errorf( + `unexpected character %q in variable name near %q`, + string(char), string(src)) + } + } + + if len(src) == 0 { + return "", nil, errors.New("zero length string") + } + + // trim whitespace + key = strings.TrimRightFunc(key, unicode.IsSpace) + cutset = bytes.TrimLeftFunc(src[offset:], isSpace) + return key, cutset, nil +} + +// extractVarValue extracts variable value and returns rest of slice +func extractVarValue(src []byte, vars map[string]string) (value string, rest []byte, err error) { + quote, hasPrefix := hasQuotePrefix(src) + if !hasPrefix { + // unquoted value - read until end of line + endOfLine := bytes.IndexFunc(src, isLineEnd) + + // Hit EOF without a trailing newline + if endOfLine == -1 { + endOfLine = len(src) + + if endOfLine == 0 { + return "", nil, nil + } + } + + // Convert line to rune away to do accurate countback of runes + line := []rune(string(src[0:endOfLine])) + + // Assume end of line is end of var + endOfVar := len(line) + if endOfVar == 0 { + return "", src[endOfLine:], nil + } + + // Work backwards to check if the line ends in whitespace then + // a comment (ie asdasd # some comment) + for i := endOfVar - 1; i >= 0; i-- { + if line[i] == charComment && i > 0 { + if isSpace(line[i-1]) { + endOfVar = i + break + } + } + } + + trimmed := strings.TrimFunc(string(line[0:endOfVar]), isSpace) + + return expandVariables(trimmed, vars), src[endOfLine:], nil + } + + // lookup quoted string terminator + for i := 1; i < len(src); i++ { + if char := src[i]; char != quote { + continue + } + + // skip escaped quote symbol (\" or \', depends on quote) + if prevChar := src[i-1]; prevChar == '\\' { + continue + } + + // trim quotes + trimFunc := isCharFunc(rune(quote)) + value = string(bytes.TrimLeftFunc(bytes.TrimRightFunc(src[0:i], trimFunc), trimFunc)) + if quote == prefixDoubleQuote { + // unescape newlines for double quote (this is compat feature) + // and expand environment variables + value = expandVariables(expandEscapes(value), vars) + } + + return value, src[i+1:], nil + } + + // return formatted error if quoted string is not terminated + valEndIndex := bytes.IndexFunc(src, isCharFunc('\n')) + if valEndIndex == -1 { + valEndIndex = len(src) + } + + return "", nil, fmt.Errorf("unterminated quoted value %s", src[:valEndIndex]) +} + +func expandEscapes(str string) string { + out := escapeRegex.ReplaceAllStringFunc(str, func(match string) string { + c := strings.TrimPrefix(match, `\`) + switch c { + case "n": + return "\n" + case "r": + return "\r" + default: + return match + } + }) + return unescapeCharsRegex.ReplaceAllString(out, "$1") +} + +func indexOfNonSpaceChar(src []byte) int { + return bytes.IndexFunc(src, func(r rune) bool { + return !unicode.IsSpace(r) + }) +} + +// hasQuotePrefix reports whether charset starts with single or double quote and returns quote character +func hasQuotePrefix(src []byte) (prefix byte, isQuored bool) { + if len(src) == 0 { + return 0, false + } + + switch prefix := src[0]; prefix { + case prefixDoubleQuote, prefixSingleQuote: + return prefix, true + default: + return 0, false + } +} + +func isCharFunc(char rune) func(rune) bool { + return func(v rune) bool { + return v == char + } +} + +// isSpace reports whether the rune is a space character but not line break character +// +// this differs from unicode.IsSpace, which also applies line break as space +func isSpace(r rune) bool { + switch r { + case '\t', '\v', '\f', '\r', ' ', 0x85, 0xA0: + return true + } + return false +} + +func isLineEnd(r rune) bool { + if r == '\n' || r == '\r' { + return true + } + return false +} + +var ( + escapeRegex = regexp.MustCompile(`\\.`) + expandVarRegex = regexp.MustCompile(`(\\)?(\$)(\()?\{?([A-Z0-9_]+)?\}?`) + unescapeCharsRegex = regexp.MustCompile(`\\([^$])`) +) + +func expandVariables(v string, m map[string]string) string { + return expandVarRegex.ReplaceAllStringFunc(v, func(s string) string { + submatch := expandVarRegex.FindStringSubmatch(s) + + if submatch == nil { + return s + } + if submatch[1] == "\\" || submatch[2] == "(" { + return submatch[0][1:] + } else if submatch[4] != "" { + if val, ok := m[submatch[4]]; ok { + return val + } + if val, ok := os.LookupEnv(submatch[4]); ok { + return val + } + return m[submatch[4]] + } + return s + }) +} diff --git a/dotenv/read.go b/dotenv/read.go new file mode 100644 index 0000000..d8595c8 --- /dev/null +++ b/dotenv/read.go @@ -0,0 +1,101 @@ +package dotenv + +import ( + "bytes" + "io" + "log/slog" + "maps" + "os" + "path/filepath" + "strings" +) + +// +// ported from https://github.com/joho/godotenv/blob/main/godotenv.go +// + +// Read all env (with same file loading semantics as Load) but return values as +// a map rather than automatically writing values into env +func Read(dir string, filenames ...string) (envMap map[string]string, err error) { + filenames = filenamesOrDefault(filenames) + envMap = make(map[string]string) + + for _, filename := range filenames { + slog.Info("read .env", slog.String("file", filepath.Join(dir, filename))) + individualEnvMap, individualErr := readFile(filepath.Join(dir, filename)) + + if individualErr != nil { + err = individualErr + return + } + + maps.Copy(envMap, individualEnvMap) + } + + return +} + +// LoadFile env file value to app env +// +// overload = true will replace env value even if they already there in process env +func LoadFile(filename string, overload bool) error { + envMap, err := readFile(filename) + if err != nil { + if os.IsNotExist(err) { + slog.Info(".env not found", slog.String("file", filename)) + return nil + } + return err + } + + currentEnv := map[string]bool{} + rawEnv := os.Environ() + for _, rawEnvLine := range rawEnv { + key := strings.Split(rawEnvLine, "=")[0] + currentEnv[key] = true + } + + for key, value := range envMap { + if !currentEnv[key] || overload { + _ = os.Setenv(key, value) + } + } + + return nil +} + +func filenamesOrDefault(filenames []string) []string { + if len(filenames) == 0 { + return []string{".env"} + } + return filenames +} + +func readFile(filename string) (envMap map[string]string, err error) { + file, err := os.Open(filename) + if err != nil { + return + } + defer file.Close() + + return parse(file) +} + +// parse reads an env file from io.Reader, returning a map of keys and values. +func parse(r io.Reader) (map[string]string, error) { + var buf bytes.Buffer + _, err := io.Copy(&buf, r) + if err != nil { + return nil, err + } + + return unmarshal(buf.Bytes()) +} + +// unmarshal parses env file from byte slice of chars, returning a map of keys and values. +func unmarshal(src []byte) (map[string]string, error) { + out := make(map[string]string) + err := parseBytes(src, out) + + return out, err +} diff --git a/dotenv/write.go b/dotenv/write.go new file mode 100644 index 0000000..14f454d --- /dev/null +++ b/dotenv/write.go @@ -0,0 +1,62 @@ +package dotenv + +import ( + "fmt" + "os" + "sort" + "strconv" + "strings" +) + +// +// ported from https://github.com/joho/godotenv/blob/main/godotenv.go +// + +const doubleQuoteSpecialChars = "\\\n\r\"!$`" + +// Write serializes the given environment and writes it to a file. +func Write(envMap map[string]string, filename string) error { + content, err := marshal(envMap) + if err != nil { + return err + } + file, err := os.Create(filename) + if err != nil { + return err + } + defer file.Close() + _, err = file.WriteString(content + "\n") + if err != nil { + return err + } + return file.Sync() +} + +// marshal outputs the given environment as a dotenv-formatted environment file. +// Each line is in the format: KEY="VALUE" where VALUE is backslash-escaped. +func marshal(envMap map[string]string) (string, error) { + lines := make([]string, 0, len(envMap)) + for k, v := range envMap { + if d, err := strconv.Atoi(v); err == nil { + lines = append(lines, fmt.Sprintf(`%s=%d`, k, d)) + } else { + lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v))) + } + } + sort.Strings(lines) + return strings.Join(lines, "\n"), nil +} + +func doubleQuoteEscape(line string) string { + for _, c := range doubleQuoteSpecialChars { + toReplace := "\\" + string(c) + if c == '\n' { + toReplace = `\n` + } + if c == '\r' { + toReplace = `\r` + } + line = strings.Replace(line, string(c), toReplace, -1) + } + return line +} diff --git a/email/gomail/LICENSE b/email/gomail/LICENSE new file mode 100644 index 0000000..5f5c12a --- /dev/null +++ b/email/gomail/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Alexandre Cesaro + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/email/gomail/README.md b/email/gomail/README.md new file mode 100644 index 0000000..a5c5e3e --- /dev/null +++ b/email/gomail/README.md @@ -0,0 +1,85 @@ +# Gomail + +[![Build Status](https://travis-ci.org/go-gomail/gomail.svg?branch=v2)](https://travis-ci.org/go-gomail/gomail) [![Code Coverage](http://gocover.io/_badge/gopkg.in/gomail.v2)](http://gocover.io/gopkg.in/gomail.v2) [![Documentation](https://godoc.org/gopkg.in/gomail.v2?status.svg)](https://godoc.org/gopkg.in/gomail.v2) + +## Introduction + +Gomail is a simple and efficient package to send emails. It is well tested and +documented. + +Gomail can only send emails using an SMTP server. But the API is flexible and it +is easy to implement other methods for sending emails using a local Postfix, an +API, etc. + +It is versioned using [gopkg.in](https://gopkg.in) so I promise +there will never be backward incompatible changes within each version. + +It requires Go 1.2 or newer. With Go 1.5, no external dependencies are used. + +## Features + +Gomail supports: + +- Attachments +- Embedded images +- HTML and text templates +- Automatic encoding of special characters +- SSL and TLS +- Sending multiple emails with the same SMTP connection + +## Documentation + +https://godoc.org/gopkg.in/gomail.v2 + +## Download + + go get gopkg.in/gomail.v2 + +## Examples + +See the [examples in the documentation](https://godoc.org/gopkg.in/gomail.v2#example-package). + +## FAQ + +### x509: certificate signed by unknown authority + +If you get this error it means the certificate used by the SMTP server is not +considered valid by the client running Gomail. As a quick workaround you can +bypass the verification of the server's certificate chain and host name by using +`SetTLSConfig`: + + package main + + import ( + "crypto/tls" + + "gopkg.in/gomail.v2" + ) + + func main() { + d := gomail.NewDialer("smtp.example.com", 587, "user", "123456") + d.TLSConfig = &tls.Config{InsecureSkipVerify: true} + + // Send emails using d. + } + +Note, however, that this is insecure and should not be used in production. + +## Contribute + +Contributions are more than welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for +more info. + +## Change log + +See [CHANGELOG.md](CHANGELOG.md). + +## License + +[MIT](LICENSE) + +## Contact + +You can ask questions on the [Gomail +thread](https://groups.google.com/d/topic/golang-nuts/jMxZHzvvEVg/discussion) +in the Go mailing-list. diff --git a/email/gomail/auth.go b/email/gomail/auth.go new file mode 100644 index 0000000..7308a20 --- /dev/null +++ b/email/gomail/auth.go @@ -0,0 +1,46 @@ +package gomail + +import ( + "bytes" + "errors" + "fmt" + "net/smtp" + "slices" +) + +// loginAuth is an smtp.Auth that implements the LOGIN authentication mechanism. +type loginAuth struct { + username string + password string + host string +} + +func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) { + if !server.TLS { + advertised := slices.Contains(server.Auth, "LOGIN") + if !advertised { + return "", nil, errors.New("gomail: unencrypted connection") + } + } + + if server.Name != a.host { + return "", nil, errors.New("gomail: wrong host name") + } + + return "LOGIN", nil, nil +} + +func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) { + if !more { + return nil, nil + } + + switch { + case bytes.Equal(fromServer, []byte("Username:")): + return []byte(a.username), nil + case bytes.Equal(fromServer, []byte("Password:")): + return []byte(a.password), nil + default: + return nil, fmt.Errorf("gomail: unexpected server challenge: %s", fromServer) + } +} diff --git a/email/gomail/auth_test.go b/email/gomail/auth_test.go new file mode 100644 index 0000000..1b0e5e7 --- /dev/null +++ b/email/gomail/auth_test.go @@ -0,0 +1,100 @@ +package gomail + +import ( + "net/smtp" + "testing" +) + +const ( + testUser = "user" + testPwd = "pwd" + testHost = "smtp.example.com" +) + +type authTest struct { + auths []string + challenges []string + wantData []string + tls bool + wantError bool +} + +func TestNoAdvertisement(t *testing.T) { + testLoginAuth(t, &authTest{ + auths: []string{}, + tls: false, + wantError: true, + }) +} + +func TestNoAdvertisementTLS(t *testing.T) { + testLoginAuth(t, &authTest{ + auths: []string{}, + challenges: []string{"Username:", "Password:"}, + tls: true, + wantData: []string{"", testUser, testPwd}, + }) +} + +func TestLogin(t *testing.T) { + testLoginAuth(t, &authTest{ + auths: []string{"PLAIN", "LOGIN"}, + challenges: []string{"Username:", "Password:"}, + tls: false, + wantData: []string{"", testUser, testPwd}, + }) +} + +func TestLoginTLS(t *testing.T) { + testLoginAuth(t, &authTest{ + auths: []string{"LOGIN"}, + challenges: []string{"Username:", "Password:"}, + tls: true, + wantData: []string{"", testUser, testPwd}, + }) +} + +func testLoginAuth(t *testing.T, test *authTest) { + auth := &loginAuth{ + username: testUser, + password: testPwd, + host: testHost, + } + server := &smtp.ServerInfo{ + Name: testHost, + TLS: test.tls, + Auth: test.auths, + } + proto, toServer, err := auth.Start(server) + if err != nil && !test.wantError { + t.Fatalf("loginAuth.Start(): %v", err) + } + if err != nil && test.wantError { + return + } + if proto != "LOGIN" { + t.Errorf("invalid protocol, got %q, want LOGIN", proto) + } + + i := 0 + got := string(toServer) + if got != test.wantData[i] { + t.Errorf("Invalid response, got %q, want %q", got, test.wantData[i]) + } + + for _, challenge := range test.challenges { + i++ + if i >= len(test.wantData) { + t.Fatalf("unexpected challenge: %q", challenge) + } + + toServer, err = auth.Next([]byte(challenge), true) + if err != nil { + t.Fatalf("loginAuth.Auth(): %v", err) + } + got = string(toServer) + if got != test.wantData[i] { + t.Errorf("Invalid response, got %q, want %q", got, test.wantData[i]) + } + } +} diff --git a/email/gomail/example_test.go b/email/gomail/example_test.go new file mode 100644 index 0000000..996ae68 --- /dev/null +++ b/email/gomail/example_test.go @@ -0,0 +1,225 @@ +package gomail_test + +import ( + "fmt" + "html/template" + "io" + "log" + "time" + + "code.patial.tech/go/appcore/email/gomail" +) + +func Example() { + m := gomail.NewMessage() + m.SetHeader("From", "alex@example.com") + m.SetHeader("To", "bob@example.com", "cora@example.com") + m.SetAddressHeader("Cc", "dan@example.com", "Dan") + m.SetHeader("Subject", "Hello!") + m.SetBody("text/html", "Hello Bob and Cora!") + m.Attach("/home/Alex/lolcat.jpg") + + d := gomail.NewDialer("smtp.example.com", 587, "user", "123456") + + // Send the email to Bob, Cora and Dan. + if err := d.DialAndSend(m); err != nil { + panic(err) + } +} + +// A daemon that listens to a channel and sends all incoming messages. +func Example_daemon() { + ch := make(chan *gomail.Message) + + go func() { + d := gomail.NewDialer("smtp.example.com", 587, "user", "123456") + + var s gomail.SendCloser + var err error + open := false + for { + select { + case m, ok := <-ch: + if !ok { + return + } + if !open { + if s, err = d.Dial(); err != nil { + panic(err) + } + open = true + } + if err := gomail.Send(s, m); err != nil { + log.Print(err) + } + // Close the connection to the SMTP server if no email was sent in + // the last 30 seconds. + case <-time.After(30 * time.Second): + if open { + if err := s.Close(); err != nil { + panic(err) + } + open = false + } + } + } + }() + + // Use the channel in your program to send emails. + + // Close the channel to stop the mail daemon. + close(ch) +} + +// Efficiently send a customized newsletter to a list of recipients. +func Example_newsletter() { + // The list of recipients. + list := []struct { + Name string + Address string + }{ + {"John Doe", "john@example.com"}, + } + + d := gomail.NewDialer("smtp.example.com", 587, "user", "123456") + s, err := d.Dial() + if err != nil { + panic(err) + } + + m := gomail.NewMessage() + for _, r := range list { + m.SetHeader("From", "no-reply@example.com") + m.SetAddressHeader("To", r.Address, r.Name) + m.SetHeader("Subject", "Newsletter #1") + m.SetBody("text/html", fmt.Sprintf("Hello %s!", r.Name)) + + if err := gomail.Send(s, m); err != nil { + log.Printf("Could not send email to %q: %v", r.Address, err) + } + m.Reset() + } +} + +// Send an email using a local SMTP server. +func Example_noAuth() { + m := gomail.NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetHeader("Subject", "Hello!") + m.SetBody("text/plain", "Hello!") + + d := gomail.Dialer{Host: "localhost", Port: 587} + if err := d.DialAndSend(m); err != nil { + panic(err) + } +} + +// Send an email using an API or postfix. +func Example_noSMTP() { + m := gomail.NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetHeader("Subject", "Hello!") + m.SetBody("text/plain", "Hello!") + + s := gomail.SendFunc(func(from string, to []string, msg io.WriterTo) error { + // Implements you email-sending function, for example by calling + // an API, or running postfix, etc. + fmt.Println("From:", from) + fmt.Println("To:", to) + return nil + }) + + if err := gomail.Send(s, m); err != nil { + panic(err) + } + // Output: + // From: from@example.com + // To: [to@example.com] +} + +var m *gomail.Message + +func ExampleSetCopyFunc() { + m.Attach("foo.txt", gomail.SetCopyFunc(func(w io.Writer) error { + _, err := w.Write([]byte("Content of foo.txt")) + return err + })) +} + +func ExampleSetHeader() { + h := map[string][]string{"Content-ID": {""}} + m.Attach("foo.jpg", gomail.SetHeader(h)) +} + +func ExampleRename() { + m.Attach("/tmp/0000146.jpg", gomail.Rename("picture.jpg")) +} + +func ExampleMessage_AddAlternative() { + m.SetBody("text/plain", "Hello!") + m.AddAlternative("text/html", "

Hello!

") +} + +func ExampleMessage_AddAlternativeWriter() { + t := template.Must(template.New("example").Parse("Hello {{.}}!")) + m.AddAlternativeWriter("text/plain", func(w io.Writer) error { + return t.Execute(w, "Bob") + }) +} + +func ExampleMessage_Attach() { + m.Attach("/tmp/image.jpg") +} + +func ExampleMessage_Embed() { + m.Embed("/tmp/image.jpg") + m.SetBody("text/html", `My image`) +} + +func ExampleMessage_FormatAddress() { + m.SetHeader("To", m.FormatAddress("bob@example.com", "Bob"), m.FormatAddress("cora@example.com", "Cora")) +} + +func ExampleMessage_FormatDate() { + m.SetHeaders(map[string][]string{ + "X-Date": {m.FormatDate(time.Now())}, + }) +} + +func ExampleMessage_SetAddressHeader() { + m.SetAddressHeader("To", "bob@example.com", "Bob") +} + +func ExampleMessage_SetBody() { + m.SetBody("text/plain", "Hello!") +} + +func ExampleMessage_SetDateHeader() { + m.SetDateHeader("X-Date", time.Now()) +} + +func ExampleMessage_SetHeader() { + m.SetHeader("Subject", "Hello!") +} + +func ExampleMessage_SetHeaders() { + m.SetHeaders(map[string][]string{ + "From": {m.FormatAddress("alex@example.com", "Alex")}, + "To": {"bob@example.com", "cora@example.com"}, + "Subject": {"Hello"}, + }) +} + +func ExampleSetCharset() { + m = gomail.NewMessage(gomail.SetCharset("ISO-8859-1")) +} + +func ExampleSetEncoding() { + m = gomail.NewMessage(gomail.SetEncoding(gomail.Base64)) +} + +func ExampleSetPartEncoding() { + m.SetBody("text/plain", "Hello!", gomail.SetPartEncoding(gomail.Unencoded)) +} diff --git a/email/gomail/message.go b/email/gomail/message.go new file mode 100644 index 0000000..be2e204 --- /dev/null +++ b/email/gomail/message.go @@ -0,0 +1,321 @@ +package gomail + +import ( + "bytes" + "io" + "maps" + "os" + "path/filepath" + "time" +) + +// Message represents an email. +type Message struct { + header header + parts []*part + attachments []*file + embedded []*file + charset string + encoding Encoding + buf bytes.Buffer + hEncoder mimeEncoder +} + +type header map[string][]string + +type part struct { + contentType string + copier func(io.Writer) error + encoding Encoding +} + +// NewMessage creates a new message. It uses UTF-8 and quoted-printable encoding +// by default. +func NewMessage(settings ...MessageSetting) *Message { + m := &Message{ + header: make(header), + charset: "UTF-8", + encoding: QuotedPrintable, + } + + m.applySettings(settings) + + if m.encoding == Base64 { + m.hEncoder = bEncoding + } else { + m.hEncoder = qEncoding + } + + return m +} + +// Reset resets the message so it can be reused. The message keeps its previous +// settings so it is in the same state that after a call to NewMessage. +func (m *Message) Reset() { + for k := range m.header { + delete(m.header, k) + } + m.parts = nil + m.attachments = nil + m.embedded = nil +} + +func (m *Message) applySettings(settings []MessageSetting) { + for _, s := range settings { + s(m) + } +} + +// A MessageSetting can be used as an argument in NewMessage to configure an +// email. +type MessageSetting func(m *Message) + +// SetCharset is a message setting to set the charset of the email. +func SetCharset(charset string) MessageSetting { + return func(m *Message) { + m.charset = charset + } +} + +// SetEncoding is a message setting to set the encoding of the email. +func SetEncoding(enc Encoding) MessageSetting { + return func(m *Message) { + m.encoding = enc + } +} + +// Encoding represents a MIME encoding scheme like quoted-printable or base64. +type Encoding string + +const ( + // QuotedPrintable represents the quoted-printable encoding as defined in + // RFC 2045. + QuotedPrintable Encoding = "quoted-printable" + // Base64 represents the base64 encoding as defined in RFC 2045. + Base64 Encoding = "base64" + // Unencoded can be used to avoid encoding the body of an email. The headers + // will still be encoded using quoted-printable encoding. + Unencoded Encoding = "8bit" +) + +// SetHeader sets a value to the given header field. +func (m *Message) SetHeader(field string, value ...string) { + m.encodeHeader(value) + m.header[field] = value +} + +func (m *Message) encodeHeader(values []string) { + for i := range values { + values[i] = m.encodeString(values[i]) + } +} + +func (m *Message) encodeString(value string) string { + return m.hEncoder.Encode(m.charset, value) +} + +// SetHeaders sets the message headers. +func (m *Message) SetHeaders(h map[string][]string) { + for k, v := range h { + m.SetHeader(k, v...) + } +} + +// SetAddressHeader sets an address to the given header field. +func (m *Message) SetAddressHeader(field, address, name string) { + m.header[field] = []string{m.FormatAddress(address, name)} +} + +// FormatAddress formats an address and a name as a valid RFC 5322 address. +func (m *Message) FormatAddress(address, name string) string { + if name == "" { + return address + } + + enc := m.encodeString(name) + if enc == name { + m.buf.WriteByte('"') + for i := 0; i < len(name); i++ { + b := name[i] + if b == '\\' || b == '"' { + m.buf.WriteByte('\\') + } + m.buf.WriteByte(b) + } + m.buf.WriteByte('"') + } else if hasSpecials(name) { + m.buf.WriteString(bEncoding.Encode(m.charset, name)) + } else { + m.buf.WriteString(enc) + } + m.buf.WriteString(" <") + m.buf.WriteString(address) + m.buf.WriteByte('>') + + addr := m.buf.String() + m.buf.Reset() + return addr +} + +func hasSpecials(text string) bool { + for i := 0; i < len(text); i++ { + switch c := text[i]; c { + case '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"': + return true + } + } + + return false +} + +// SetDateHeader sets a date to the given header field. +func (m *Message) SetDateHeader(field string, date time.Time) { + m.header[field] = []string{m.FormatDate(date)} +} + +// FormatDate formats a date as a valid RFC 5322 date. +func (m *Message) FormatDate(date time.Time) string { + return date.Format(time.RFC1123Z) +} + +// GetHeader gets a header field. +func (m *Message) GetHeader(field string) []string { + return m.header[field] +} + +// SetBody sets the body of the message. It replaces any content previously set +// by SetBody, AddAlternative or AddAlternativeWriter. +func (m *Message) SetBody(contentType, body string, settings ...PartSetting) { + m.parts = []*part{m.newPart(contentType, newCopier(body), settings)} +} + +// AddAlternative adds an alternative part to the message. +// +// It is commonly used to send HTML emails that default to the plain text +// version for backward compatibility. AddAlternative appends the new part to +// the end of the message. So the plain text part should be added before the +// HTML part. See http://en.wikipedia.org/wiki/MIME#Alternative +func (m *Message) AddAlternative(contentType, body string, settings ...PartSetting) { + m.AddAlternativeWriter(contentType, newCopier(body), settings...) +} + +func newCopier(s string) func(io.Writer) error { + return func(w io.Writer) error { + _, err := io.WriteString(w, s) + return err + } +} + +// AddAlternativeWriter adds an alternative part to the message. It can be +// useful with the text/template or html/template packages. +func (m *Message) AddAlternativeWriter(contentType string, f func(io.Writer) error, settings ...PartSetting) { + m.parts = append(m.parts, m.newPart(contentType, f, settings)) +} + +func (m *Message) newPart(contentType string, f func(io.Writer) error, settings []PartSetting) *part { + p := &part{ + contentType: contentType, + copier: f, + encoding: m.encoding, + } + + for _, s := range settings { + s(p) + } + + return p +} + +// A PartSetting can be used as an argument in Message.SetBody, +// Message.AddAlternative or Message.AddAlternativeWriter to configure the part +// added to a message. +type PartSetting func(*part) + +// SetPartEncoding sets the encoding of the part added to the message. By +// default, parts use the same encoding than the message. +func SetPartEncoding(e Encoding) PartSetting { + return PartSetting(func(p *part) { + p.encoding = e + }) +} + +type file struct { + Header map[string][]string + CopyFunc func(w io.Writer) error + Name string +} + +func (f *file) setHeader(field, value string) { + f.Header[field] = []string{value} +} + +// A FileSetting can be used as an argument in Message.Attach or Message.Embed. +type FileSetting func(*file) + +// SetHeader is a file setting to set the MIME header of the message part that +// contains the file content. +// +// Mandatory headers are automatically added if they are not set when sending +// the email. +func SetHeader(h map[string][]string) FileSetting { + return func(f *file) { + maps.Copy(f.Header, h) + } +} + +// Rename is a file setting to set the name of the attachment if the name is +// different than the filename on disk. +func Rename(name string) FileSetting { + return func(f *file) { + f.Name = name + } +} + +// SetCopyFunc is a file setting to replace the function that runs when the +// message is sent. It should copy the content of the file to the io.Writer. +// +// The default copy function opens the file with the given filename, and copy +// its content to the io.Writer. +func SetCopyFunc(f func(io.Writer) error) FileSetting { + return func(fi *file) { + fi.CopyFunc = f + } +} + +func (m *Message) appendFile(list []*file, name string, settings []FileSetting) []*file { + f := &file{ + Name: filepath.Base(name), + Header: make(map[string][]string), + CopyFunc: func(w io.Writer) error { + h, err := os.Open(name) + if err != nil { + return err + } + if _, err := io.Copy(w, h); err != nil { + h.Close() + return err + } + return h.Close() + }, + } + + for _, s := range settings { + s(f) + } + + if list == nil { + return []*file{f} + } + + return append(list, f) +} + +// Attach attaches the files to the email. +func (m *Message) Attach(filename string, settings ...FileSetting) { + m.attachments = m.appendFile(m.attachments, filename, settings) +} + +// Embed embeds the images to the email. +func (m *Message) Embed(filename string, settings ...FileSetting) { + m.embedded = m.appendFile(m.embedded, filename, settings) +} diff --git a/email/gomail/message_test.go b/email/gomail/message_test.go new file mode 100644 index 0000000..5926992 --- /dev/null +++ b/email/gomail/message_test.go @@ -0,0 +1,744 @@ +package gomail + +import ( + "bytes" + "encoding/base64" + "io" + "path/filepath" + "regexp" + "strconv" + "strings" + "testing" + "time" +) + +func init() { + now = func() time.Time { + return time.Date(2014, 06, 25, 17, 46, 0, 0, time.UTC) + } +} + +type message struct { + from string + content string + to []string +} + +func TestMessage(t *testing.T) { + m := NewMessage() + m.SetAddressHeader("From", "from@example.com", "Señor From") + m.SetHeader("To", m.FormatAddress("to@example.com", "Señor To"), "tobis@example.com") + m.SetAddressHeader("Cc", "cc@example.com", "A, B") + m.SetAddressHeader("X-To", "ccbis@example.com", "à, b") + m.SetDateHeader("X-Date", now()) + m.SetHeader("X-Date-2", m.FormatDate(now())) + m.SetHeader("Subject", "¡Hola, señor!") + m.SetHeaders(map[string][]string{ + "X-Headers": {"Test", "Café"}, + }) + m.SetBody("text/plain", "¡Hola, señor!") + + want := &message{ + from: "from@example.com", + to: []string{ + "to@example.com", + "tobis@example.com", + "cc@example.com", + }, + content: "From: =?UTF-8?q?Se=C3=B1or_From?= \r\n" + + "To: =?UTF-8?q?Se=C3=B1or_To?= , tobis@example.com\r\n" + + "Cc: \"A, B\" \r\n" + + "X-To: =?UTF-8?b?w6AsIGI=?= \r\n" + + "X-Date: Wed, 25 Jun 2014 17:46:00 +0000\r\n" + + "X-Date-2: Wed, 25 Jun 2014 17:46:00 +0000\r\n" + + "X-Headers: Test, =?UTF-8?q?Caf=C3=A9?=\r\n" + + "Subject: =?UTF-8?q?=C2=A1Hola,_se=C3=B1or!?=\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "=C2=A1Hola, se=C3=B1or!", + } + + testMessage(t, m, 0, want) +} + +func TestCustomMessage(t *testing.T) { + m := NewMessage(SetCharset("ISO-8859-1"), SetEncoding(Base64)) + m.SetHeaders(map[string][]string{ + "From": {"from@example.com"}, + "To": {"to@example.com"}, + "Subject": {"Café"}, + }) + m.SetBody("text/html", "¡Hola, señor!") + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Subject: =?ISO-8859-1?b?Q2Fmw6k=?=\r\n" + + "Content-Type: text/html; charset=ISO-8859-1\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + "wqFIb2xhLCBzZcOxb3Ih", + } + + testMessage(t, m, 0, want) +} + +func TestUnencodedMessage(t *testing.T) { + m := NewMessage(SetEncoding(Unencoded)) + m.SetHeaders(map[string][]string{ + "From": {"from@example.com"}, + "To": {"to@example.com"}, + "Subject": {"Café"}, + }) + m.SetBody("text/html", "¡Hola, señor!") + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Subject: =?UTF-8?q?Caf=C3=A9?=\r\n" + + "Content-Type: text/html; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: 8bit\r\n" + + "\r\n" + + "¡Hola, señor!", + } + + testMessage(t, m, 0, want) +} + +func TestRecipients(t *testing.T) { + m := NewMessage() + m.SetHeaders(map[string][]string{ + "From": {"from@example.com"}, + "To": {"to@example.com"}, + "Cc": {"cc@example.com"}, + "Bcc": {"bcc1@example.com", "bcc2@example.com"}, + "Subject": {"Hello!"}, + }) + m.SetBody("text/plain", "Test message") + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com", "cc@example.com", "bcc1@example.com", "bcc2@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Cc: cc@example.com\r\n" + + "Subject: Hello!\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "Test message", + } + + testMessage(t, m, 0, want) +} + +func TestAlternative(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetBody("text/plain", "¡Hola, señor!") + m.AddAlternative("text/html", "¡Hola, señor!") + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: multipart/alternative;\r\n" + + " boundary=_BOUNDARY_1_\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "=C2=A1Hola, se=C3=B1or!\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/html; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "=C2=A1Hola, se=C3=B1or!\r\n" + + "--_BOUNDARY_1_--\r\n", + } + + testMessage(t, m, 1, want) +} + +func TestPartSetting(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetBody("text/plain; format=flowed", "¡Hola, señor!", SetPartEncoding(Unencoded)) + m.AddAlternative("text/html", "¡Hola, señor!") + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: multipart/alternative;\r\n" + + " boundary=_BOUNDARY_1_\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/plain; format=flowed; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: 8bit\r\n" + + "\r\n" + + "¡Hola, señor!\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/html; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "=C2=A1Hola, se=C3=B1or!\r\n" + + "--_BOUNDARY_1_--\r\n", + } + + testMessage(t, m, 1, want) +} + +func TestBodyWriter(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.AddAlternativeWriter("text/plain", func(w io.Writer) error { + _, err := w.Write([]byte("Test message")) + return err + }) + m.AddAlternativeWriter("text/html", func(w io.Writer) error { + _, err := w.Write([]byte("Test HTML")) + return err + }) + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: multipart/alternative;\r\n" + + " boundary=_BOUNDARY_1_\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "Test message\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/html; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "Test HTML\r\n" + + "--_BOUNDARY_1_--\r\n", + } + + testMessage(t, m, 1, want) +} + +func TestAttachmentOnly(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.Attach(mockCopyFile("/tmp/test.pdf")) + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: application/pdf; name=\"test.pdf\"\r\n" + + "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")), + } + + testMessage(t, m, 0, want) +} + +func TestAttachment(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetBody("text/plain", "Test") + m.Attach(mockCopyFile("/tmp/test.pdf")) + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: multipart/mixed;\r\n" + + " boundary=_BOUNDARY_1_\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "Test\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: application/pdf; name=\"test.pdf\"\r\n" + + "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")) + "\r\n" + + "--_BOUNDARY_1_--\r\n", + } + + testMessage(t, m, 1, want) +} + +func TestRename(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetBody("text/plain", "Test") + name, copy := mockCopyFile("/tmp/test.pdf") + rename := Rename("another.pdf") + m.Attach(name, copy, rename) + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: multipart/mixed;\r\n" + + " boundary=_BOUNDARY_1_\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "Test\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: application/pdf; name=\"another.pdf\"\r\n" + + "Content-Disposition: attachment; filename=\"another.pdf\"\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")) + "\r\n" + + "--_BOUNDARY_1_--\r\n", + } + + testMessage(t, m, 1, want) +} + +func TestAttachmentsOnly(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.Attach(mockCopyFile("/tmp/test.pdf")) + m.Attach(mockCopyFile("/tmp/test.zip")) + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: multipart/mixed;\r\n" + + " boundary=_BOUNDARY_1_\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: application/pdf; name=\"test.pdf\"\r\n" + + "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")) + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: application/zip; name=\"test.zip\"\r\n" + + "Content-Disposition: attachment; filename=\"test.zip\"\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of test.zip")) + "\r\n" + + "--_BOUNDARY_1_--\r\n", + } + + testMessage(t, m, 1, want) +} + +func TestAttachments(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetBody("text/plain", "Test") + m.Attach(mockCopyFile("/tmp/test.pdf")) + m.Attach(mockCopyFile("/tmp/test.zip")) + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: multipart/mixed;\r\n" + + " boundary=_BOUNDARY_1_\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "Test\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: application/pdf; name=\"test.pdf\"\r\n" + + "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")) + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: application/zip; name=\"test.zip\"\r\n" + + "Content-Disposition: attachment; filename=\"test.zip\"\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of test.zip")) + "\r\n" + + "--_BOUNDARY_1_--\r\n", + } + + testMessage(t, m, 1, want) +} + +func TestEmbedded(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.Embed(mockCopyFileWithHeader(m, "image1.jpg", map[string][]string{"Content-ID": {""}})) + m.Embed(mockCopyFile("image2.jpg")) + m.SetBody("text/plain", "Test") + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: multipart/related;\r\n" + + " boundary=_BOUNDARY_1_\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "Test\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: image/jpeg; name=\"image1.jpg\"\r\n" + + "Content-Disposition: inline; filename=\"image1.jpg\"\r\n" + + "Content-ID: \r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of image1.jpg")) + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: image/jpeg; name=\"image2.jpg\"\r\n" + + "Content-Disposition: inline; filename=\"image2.jpg\"\r\n" + + "Content-ID: \r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of image2.jpg")) + "\r\n" + + "--_BOUNDARY_1_--\r\n", + } + + testMessage(t, m, 1, want) +} + +func TestFullMessage(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetBody("text/plain", "¡Hola, señor!") + m.AddAlternative("text/html", "¡Hola, señor!") + m.Attach(mockCopyFile("test.pdf")) + m.Embed(mockCopyFile("image.jpg")) + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: multipart/mixed;\r\n" + + " boundary=_BOUNDARY_1_\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: multipart/related;\r\n" + + " boundary=_BOUNDARY_2_\r\n" + + "\r\n" + + "--_BOUNDARY_2_\r\n" + + "Content-Type: multipart/alternative;\r\n" + + " boundary=_BOUNDARY_3_\r\n" + + "\r\n" + + "--_BOUNDARY_3_\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "=C2=A1Hola, se=C3=B1or!\r\n" + + "--_BOUNDARY_3_\r\n" + + "Content-Type: text/html; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "=C2=A1Hola, se=C3=B1or!\r\n" + + "--_BOUNDARY_3_--\r\n" + + "\r\n" + + "--_BOUNDARY_2_\r\n" + + "Content-Type: image/jpeg; name=\"image.jpg\"\r\n" + + "Content-Disposition: inline; filename=\"image.jpg\"\r\n" + + "Content-ID: \r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of image.jpg")) + "\r\n" + + "--_BOUNDARY_2_--\r\n" + + "\r\n" + + "--_BOUNDARY_1_\r\n" + + "Content-Type: application/pdf; name=\"test.pdf\"\r\n" + + "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")) + "\r\n" + + "--_BOUNDARY_1_--\r\n", + } + + testMessage(t, m, 3, want) + + want = &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + "Test reset", + } + m.Reset() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetBody("text/plain", "Test reset") + testMessage(t, m, 0, want) +} + +func TestQpLineLength(t *testing.T) { + m := NewMessage() + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetBody("text/plain", + strings.Repeat("0", 76)+"\r\n"+ + strings.Repeat("0", 75)+"à\r\n"+ + strings.Repeat("0", 74)+"à\r\n"+ + strings.Repeat("0", 73)+"à\r\n"+ + strings.Repeat("0", 72)+"à\r\n"+ + strings.Repeat("0", 75)+"\r\n"+ + strings.Repeat("0", 76)+"\n") + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + strings.Repeat("0", 75) + "=\r\n0\r\n" + + strings.Repeat("0", 75) + "=\r\n=C3=A0\r\n" + + strings.Repeat("0", 74) + "=\r\n=C3=A0\r\n" + + strings.Repeat("0", 73) + "=\r\n=C3=A0\r\n" + + strings.Repeat("0", 72) + "=C3=\r\n=A0\r\n" + + strings.Repeat("0", 75) + "\r\n" + + strings.Repeat("0", 75) + "=\r\n0\r\n", + } + + testMessage(t, m, 0, want) +} + +func TestBase64LineLength(t *testing.T) { + m := NewMessage(SetCharset("UTF-8"), SetEncoding(Base64)) + m.SetHeader("From", "from@example.com") + m.SetHeader("To", "to@example.com") + m.SetBody("text/plain", strings.Repeat("0", 58)) + + want := &message{ + from: "from@example.com", + to: []string{"to@example.com"}, + content: "From: from@example.com\r\n" + + "To: to@example.com\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "\r\n" + + strings.Repeat("MDAw", 19) + "\r\nMA==", + } + + testMessage(t, m, 0, want) +} + +func TestEmptyName(t *testing.T) { + m := NewMessage() + m.SetAddressHeader("From", "from@example.com", "") + + want := &message{ + from: "from@example.com", + content: "From: from@example.com\r\n", + } + + testMessage(t, m, 0, want) +} + +func TestEmptyHeader(t *testing.T) { + m := NewMessage() + m.SetHeaders(map[string][]string{ + "From": {"from@example.com"}, + "X-Empty": nil, + }) + + want := &message{ + from: "from@example.com", + content: "From: from@example.com\r\n" + + "X-Empty:\r\n", + } + + testMessage(t, m, 0, want) +} + +func testMessage(t *testing.T, m *Message, bCount int, want *message) { + err := Send(stubSendMail(t, bCount, want), m) + if err != nil { + t.Error(err) + } +} + +func stubSendMail(t *testing.T, bCount int, want *message) SendFunc { + return func(from string, to []string, m io.WriterTo) error { + if from != want.from { + t.Fatalf("Invalid from, got %q, want %q", from, want.from) + } + + if len(to) != len(want.to) { + t.Fatalf("Invalid recipient count, \ngot %d: %q\nwant %d: %q", + len(to), to, + len(want.to), want.to, + ) + } + for i := range want.to { + if to[i] != want.to[i] { + t.Fatalf("Invalid recipient, got %q, want %q", + to[i], want.to[i], + ) + } + } + + buf := new(bytes.Buffer) + _, err := m.WriteTo(buf) + if err != nil { + t.Error(err) + } + got := buf.String() + wantMsg := string("MIME-Version: 1.0\r\n" + + "Date: Wed, 25 Jun 2014 17:46:00 +0000\r\n" + + want.content) + if bCount > 0 { + boundaries := getBoundaries(t, bCount, got) + for i, b := range boundaries { + wantMsg = strings.Replace(wantMsg, "_BOUNDARY_"+strconv.Itoa(i+1)+"_", b, -1) + } + } + + compareBodies(t, got, wantMsg) + + return nil + } +} + +func compareBodies(t *testing.T, got, want string) { + // We cannot do a simple comparison since the ordering of headers' fields + // is random. + gotLines := strings.Split(got, "\r\n") + wantLines := strings.Split(want, "\r\n") + + // We only test for too many lines, missing lines are tested after + if len(gotLines) > len(wantLines) { + t.Fatalf("Message has too many lines, \ngot %d:\n%s\nwant %d:\n%s", len(gotLines), got, len(wantLines), want) + } + + isInHeader := true + headerStart := 0 + for i, line := range wantLines { + if line == gotLines[i] { + if line == "" { + isInHeader = false + } else if !isInHeader && len(line) > 2 && line[:2] == "--" { + isInHeader = true + headerStart = i + 1 + } + continue + } + + if !isInHeader { + missingLine(t, line, got, want) + } + + isMissing := true + for j := headerStart; j < len(gotLines); j++ { + if gotLines[j] == "" { + break + } + if gotLines[j] == line { + isMissing = false + break + } + } + if isMissing { + missingLine(t, line, got, want) + } + } +} + +func missingLine(t *testing.T, line, got, want string) { + t.Fatalf("Missing line %q\ngot:\n%s\nwant:\n%s", line, got, want) +} + +func getBoundaries(t *testing.T, count int, m string) []string { + if matches := boundaryRegExp.FindAllStringSubmatch(m, count); matches != nil { + boundaries := make([]string, count) + for i, match := range matches { + boundaries[i] = match[1] + } + return boundaries + } + + t.Fatal("Boundary not found in body") + return []string{""} +} + +var boundaryRegExp = regexp.MustCompile(`boundary=(\\w+)`) + +func mockCopyFile(name string) (string, FileSetting) { + return name, SetCopyFunc(func(w io.Writer) error { + _, err := w.Write([]byte("Content of " + filepath.Base(name))) + return err + }) +} + +func mockCopyFileWithHeader(_ *Message, name string, h map[string][]string) (string, FileSetting, FileSetting) { + name, f := mockCopyFile(name) + return name, f, SetHeader(h) +} + +func BenchmarkFull(b *testing.B) { + discardFunc := SendFunc(func(from string, to []string, m io.WriterTo) error { + _, err := m.WriteTo(io.Discard) + return err + }) + + m := NewMessage() + b.ResetTimer() + for n := 0; n < b.N; n++ { + m.SetAddressHeader("From", "from@example.com", "Señor From") + m.SetHeaders(map[string][]string{ + "To": {"to@example.com"}, + "Cc": {"cc@example.com"}, + "Bcc": {"bcc1@example.com", "bcc2@example.com"}, + "Subject": {"¡Hola, señor!"}, + }) + m.SetBody("text/plain", "¡Hola, señor!") + m.AddAlternative("text/html", "

¡Hola, señor!

") + m.Attach(mockCopyFile("benchmark.txt")) + m.Embed(mockCopyFile("benchmark.jpg")) + + if err := Send(discardFunc, m); err != nil { + panic(err) + } + m.Reset() + } +} diff --git a/email/gomail/mime.go b/email/gomail/mime.go new file mode 100644 index 0000000..cdaa349 --- /dev/null +++ b/email/gomail/mime.go @@ -0,0 +1,19 @@ +package gomail + +import ( + "mime" + "mime/quotedprintable" + "strings" +) + +var newQPWriter = quotedprintable.NewWriter + +type mimeEncoder struct { + mime.WordEncoder +} + +var ( + bEncoding = mimeEncoder{mime.BEncoding} + qEncoding = mimeEncoder{mime.QEncoding} + lastIndexByte = strings.LastIndexByte +) diff --git a/email/gomail/send.go b/email/gomail/send.go new file mode 100644 index 0000000..9115ebe --- /dev/null +++ b/email/gomail/send.go @@ -0,0 +1,116 @@ +package gomail + +import ( + "errors" + "fmt" + "io" + "net/mail" +) + +// Sender is the interface that wraps the Send method. +// +// Send sends an email to the given addresses. +type Sender interface { + Send(from string, to []string, msg io.WriterTo) error +} + +// SendCloser is the interface that groups the Send and Close methods. +type SendCloser interface { + Sender + Close() error +} + +// A SendFunc is a function that sends emails to the given addresses. +// +// The SendFunc type is an adapter to allow the use of ordinary functions as +// email senders. If f is a function with the appropriate signature, SendFunc(f) +// is a Sender object that calls f. +type SendFunc func(from string, to []string, msg io.WriterTo) error + +// Send calls f(from, to, msg). +func (f SendFunc) Send(from string, to []string, msg io.WriterTo) error { + return f(from, to, msg) +} + +// Send sends emails using the given Sender. +func Send(s Sender, msg ...*Message) error { + for i, m := range msg { + if err := send(s, m); err != nil { + return fmt.Errorf("gomail: could not send email %d: %v", i+1, err) + } + } + + return nil +} + +func send(s Sender, m *Message) error { + from, err := m.getFrom() + if err != nil { + return err + } + + to, err := m.getRecipients() + if err != nil { + return err + } + + if err := s.Send(from, to, m); err != nil { + return err + } + + return nil +} + +func (m *Message) getFrom() (string, error) { + from := m.header["Sender"] + if len(from) == 0 { + from = m.header["From"] + if len(from) == 0 { + return "", errors.New(`gomail: invalid message, "From" field is absent`) + } + } + + return parseAddress(from[0]) +} + +func (m *Message) getRecipients() ([]string, error) { + n := 0 + for _, field := range []string{"To", "Cc", "Bcc"} { + if addresses, ok := m.header[field]; ok { + n += len(addresses) + } + } + list := make([]string, 0, n) + + for _, field := range []string{"To", "Cc", "Bcc"} { + if addresses, ok := m.header[field]; ok { + for _, a := range addresses { + addr, err := parseAddress(a) + if err != nil { + return nil, err + } + list = addAddress(list, addr) + } + } + } + + return list, nil +} + +func addAddress(list []string, addr string) []string { + for _, a := range list { + if addr == a { + return list + } + } + + return append(list, addr) +} + +func parseAddress(field string) (string, error) { + addr, err := mail.ParseAddress(field) + if err != nil { + return "", fmt.Errorf("gomail: invalid address %q: %v", field, err) + } + return addr.Address, nil +} diff --git a/email/gomail/send_test.go b/email/gomail/send_test.go new file mode 100644 index 0000000..dbd175d --- /dev/null +++ b/email/gomail/send_test.go @@ -0,0 +1,80 @@ +package gomail + +import ( + "bytes" + "io" + "reflect" + "testing" +) + +const ( + testTo1 = "to1@example.com" + testTo2 = "to2@example.com" + testFrom = "from@example.com" + testBody = "Test message" + testMsg = "To: " + testTo1 + ", " + testTo2 + "\r\n" + + "From: " + testFrom + "\r\n" + + "MIME-Version: 1.0\r\n" + + "Date: Wed, 25 Jun 2014 17:46:00 +0000\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "\r\n" + + testBody +) + +type mockSender SendFunc + +func (s mockSender) Send(from string, to []string, msg io.WriterTo) error { + return s(from, to, msg) +} + +type mockSendCloser struct { + mockSender + close func() error +} + +func (s *mockSendCloser) Close() error { + return s.close() +} + +func TestSend(t *testing.T) { + s := &mockSendCloser{ + mockSender: stubSend(t, testFrom, []string{testTo1, testTo2}, testMsg), + close: func() error { + t.Error("Close() should not be called in Send()") + return nil + }, + } + if err := Send(s, getTestMessage()); err != nil { + t.Errorf("Send(): %v", err) + } +} + +func getTestMessage() *Message { + m := NewMessage() + m.SetHeader("From", testFrom) + m.SetHeader("To", testTo1, testTo2) + m.SetBody("text/plain", testBody) + + return m +} + +func stubSend(t *testing.T, wantFrom string, wantTo []string, wantBody string) mockSender { + return func(from string, to []string, msg io.WriterTo) error { + if from != wantFrom { + t.Errorf("invalid from, got %q, want %q", from, wantFrom) + } + if !reflect.DeepEqual(to, wantTo) { + t.Errorf("invalid to, got %v, want %v", to, wantTo) + } + + buf := new(bytes.Buffer) + _, err := msg.WriteTo(buf) + if err != nil { + t.Fatal(err) + } + compareBodies(t, buf.String(), wantBody) + + return nil + } +} diff --git a/email/gomail/smtp.go b/email/gomail/smtp.go new file mode 100644 index 0000000..5deaaef --- /dev/null +++ b/email/gomail/smtp.go @@ -0,0 +1,189 @@ +package gomail + +import ( + "crypto/tls" + "fmt" + "io" + "net" + "net/smtp" + "strings" + "time" +) + +// A Dialer is a dialer to an SMTP server. +type Dialer struct { + Auth smtp.Auth + TLSConfig *tls.Config + Host string + Username string + Password string + LocalName string + Port int + SSL bool +} + +// NewDialer returns a new SMTP Dialer. The given parameters are used to connect +// to the SMTP server. +func NewDialer(host string, port int, username, password string) *Dialer { + return &Dialer{ + Host: host, + Port: port, + Username: username, + Password: password, + SSL: port == 465, + } +} + +// NewPlainDialer returns a new SMTP Dialer. The given parameters are used to +// connect to the SMTP server. +// +// Deprecated: Use NewDialer instead. +func NewPlainDialer(host string, port int, username, password string) *Dialer { + return NewDialer(host, port, username, password) +} + +// Dial dials and authenticates to an SMTP server. The returned SendCloser +// should be closed when done using it. +func (d *Dialer) Dial() (SendCloser, error) { + conn, err := netDialTimeout("tcp", addr(d.Host, d.Port), 10*time.Second) + if err != nil { + return nil, err + } + + if d.SSL { + conn = tlsClient(conn, d.tlsConfig()) + } + + c, err := smtpNewClient(conn, d.Host) + if err != nil { + return nil, err + } + + if d.LocalName != "" { + if err := c.Hello(d.LocalName); err != nil { + return nil, err + } + } + + if !d.SSL { + if ok, _ := c.Extension("STARTTLS"); ok { + if err := c.StartTLS(d.tlsConfig()); err != nil { + c.Close() + return nil, err + } + } + } + + if d.Auth == nil && d.Username != "" { + if ok, auths := c.Extension("AUTH"); ok { + if strings.Contains(auths, "CRAM-MD5") { + d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password) + } else if strings.Contains(auths, "LOGIN") && + !strings.Contains(auths, "PLAIN") { + d.Auth = &loginAuth{ + username: d.Username, + password: d.Password, + host: d.Host, + } + } else { + d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host) + } + } + } + + if d.Auth != nil { + if err = c.Auth(d.Auth); err != nil { + c.Close() + return nil, err + } + } + + return &smtpSender{c, d}, nil +} + +func (d *Dialer) tlsConfig() *tls.Config { + if d.TLSConfig == nil { + return &tls.Config{ServerName: d.Host} + } + return d.TLSConfig +} + +func addr(host string, port int) string { + return fmt.Sprintf("%s:%d", host, port) +} + +// DialAndSend opens a connection to the SMTP server, sends the given emails and +// closes the connection. +func (d *Dialer) DialAndSend(m ...*Message) error { + s, err := d.Dial() + if err != nil { + return err + } + defer s.Close() + + return Send(s, m...) +} + +type smtpSender struct { + smtpClient + d *Dialer +} + +func (c *smtpSender) Send(from string, to []string, msg io.WriterTo) error { + if err := c.Mail(from); err != nil { + if err == io.EOF { + // This is probably due to a timeout, so reconnect and try again. + sc, derr := c.d.Dial() + if derr == nil { + if s, ok := sc.(*smtpSender); ok { + *c = *s + return c.Send(from, to, msg) + } + } + } + return err + } + + for _, addr := range to { + if err := c.Rcpt(addr); err != nil { + return err + } + } + + w, err := c.Data() + if err != nil { + return err + } + + if _, err = msg.WriteTo(w); err != nil { + w.Close() + return err + } + + return w.Close() +} + +func (c *smtpSender) Close() error { + return c.Quit() +} + +// Stubbed out for tests. +var ( + netDialTimeout = net.DialTimeout + tlsClient = tls.Client + smtpNewClient = func(conn net.Conn, host string) (smtpClient, error) { + return smtp.NewClient(conn, host) + } +) + +type smtpClient interface { + Hello(string) error + Extension(string) (bool, string) + StartTLS(*tls.Config) error + Auth(smtp.Auth) error + Mail(string) error + Rcpt(string) error + Data() (io.WriteCloser, error) + Quit() error + Close() error +} diff --git a/email/gomail/smtp_test.go b/email/gomail/smtp_test.go new file mode 100644 index 0000000..5554ef3 --- /dev/null +++ b/email/gomail/smtp_test.go @@ -0,0 +1,292 @@ +package gomail + +import ( + "bytes" + "crypto/tls" + "io" + "net" + "net/smtp" + "reflect" + "testing" + "time" +) + +const ( + testPort = 587 + testSSLPort = 465 +) + +var ( + testConn = &net.TCPConn{} + testTLSConn = &tls.Conn{} + testConfig = &tls.Config{InsecureSkipVerify: true} + testAuth = smtp.PlainAuth("", testUser, testPwd, testHost) +) + +func TestDialer(t *testing.T) { + d := NewDialer(testHost, testPort, "user", "pwd") + testSendMail(t, d, []string{ + "Extension STARTTLS", + "StartTLS", + "Extension AUTH", + "Auth", + "Mail " + testFrom, + "Rcpt " + testTo1, + "Rcpt " + testTo2, + "Data", + "Write message", + "Close writer", + "Quit", + "Close", + }) +} + +func TestDialerSSL(t *testing.T) { + d := NewDialer(testHost, testSSLPort, "user", "pwd") + testSendMail(t, d, []string{ + "Extension AUTH", + "Auth", + "Mail " + testFrom, + "Rcpt " + testTo1, + "Rcpt " + testTo2, + "Data", + "Write message", + "Close writer", + "Quit", + "Close", + }) +} + +func TestDialerConfig(t *testing.T) { + d := NewDialer(testHost, testPort, "user", "pwd") + d.LocalName = "test" + d.TLSConfig = testConfig + testSendMail(t, d, []string{ + "Hello test", + "Extension STARTTLS", + "StartTLS", + "Extension AUTH", + "Auth", + "Mail " + testFrom, + "Rcpt " + testTo1, + "Rcpt " + testTo2, + "Data", + "Write message", + "Close writer", + "Quit", + "Close", + }) +} + +func TestDialerSSLConfig(t *testing.T) { + d := NewDialer(testHost, testSSLPort, "user", "pwd") + d.LocalName = "test" + d.TLSConfig = testConfig + testSendMail(t, d, []string{ + "Hello test", + "Extension AUTH", + "Auth", + "Mail " + testFrom, + "Rcpt " + testTo1, + "Rcpt " + testTo2, + "Data", + "Write message", + "Close writer", + "Quit", + "Close", + }) +} + +func TestDialerNoAuth(t *testing.T) { + d := &Dialer{ + Host: testHost, + Port: testPort, + } + testSendMail(t, d, []string{ + "Extension STARTTLS", + "StartTLS", + "Mail " + testFrom, + "Rcpt " + testTo1, + "Rcpt " + testTo2, + "Data", + "Write message", + "Close writer", + "Quit", + "Close", + }) +} + +func TestDialerTimeout(t *testing.T) { + d := &Dialer{ + Host: testHost, + Port: testPort, + } + testSendMailTimeout(t, d, []string{ + "Extension STARTTLS", + "StartTLS", + "Mail " + testFrom, + "Extension STARTTLS", + "StartTLS", + "Mail " + testFrom, + "Rcpt " + testTo1, + "Rcpt " + testTo2, + "Data", + "Write message", + "Close writer", + "Quit", + "Close", + }) +} + +type mockClient struct { + t *testing.T + config *tls.Config + addr string + want []string + i int + timeout bool +} + +func (c *mockClient) Hello(localName string) error { + c.do("Hello " + localName) + return nil +} + +func (c *mockClient) Extension(ext string) (bool, string) { + c.do("Extension " + ext) + return true, "" +} + +func (c *mockClient) StartTLS(config *tls.Config) error { + assertConfig(c.t, config, c.config) + c.do("StartTLS") + return nil +} + +func (c *mockClient) Auth(a smtp.Auth) error { + if !reflect.DeepEqual(a, testAuth) { + c.t.Errorf("Invalid auth, got %#v, want %#v", a, testAuth) + } + c.do("Auth") + return nil +} + +func (c *mockClient) Mail(from string) error { + c.do("Mail " + from) + if c.timeout { + c.timeout = false + return io.EOF + } + return nil +} + +func (c *mockClient) Rcpt(to string) error { + c.do("Rcpt " + to) + return nil +} + +func (c *mockClient) Data() (io.WriteCloser, error) { + c.do("Data") + return &mockWriter{c: c, want: testMsg}, nil +} + +func (c *mockClient) Quit() error { + c.do("Quit") + return nil +} + +func (c *mockClient) Close() error { + c.do("Close") + return nil +} + +func (c *mockClient) do(cmd string) { + if c.i >= len(c.want) { + c.t.Fatalf("Invalid command %q", cmd) + } + + if cmd != c.want[c.i] { + c.t.Fatalf("Invalid command, got %q, want %q", cmd, c.want[c.i]) + } + c.i++ +} + +type mockWriter struct { + want string + c *mockClient + buf bytes.Buffer +} + +func (w *mockWriter) Write(p []byte) (int, error) { + if w.buf.Len() == 0 { + w.c.do("Write message") + } + w.buf.Write(p) + return len(p), nil +} + +func (w *mockWriter) Close() error { + compareBodies(w.c.t, w.buf.String(), w.want) + w.c.do("Close writer") + return nil +} + +func testSendMail(t *testing.T, d *Dialer, want []string) { + doTestSendMail(t, d, want, false) +} + +func testSendMailTimeout(t *testing.T, d *Dialer, want []string) { + doTestSendMail(t, d, want, true) +} + +func doTestSendMail(t *testing.T, d *Dialer, want []string, timeout bool) { + testClient := &mockClient{ + t: t, + want: want, + addr: addr(d.Host, d.Port), + config: d.TLSConfig, + timeout: timeout, + } + + netDialTimeout = func(network, address string, _ time.Duration) (net.Conn, error) { + if network != "tcp" { + t.Errorf("Invalid network, got %q, want tcp", network) + } + if address != testClient.addr { + t.Errorf("Invalid address, got %q, want %q", + address, testClient.addr) + } + return testConn, nil + } + + tlsClient = func(conn net.Conn, config *tls.Config) *tls.Conn { + if conn != testConn { + t.Errorf("Invalid conn, got %#v, want %#v", conn, testConn) + } + assertConfig(t, config, testClient.config) + return testTLSConn + } + + smtpNewClient = func(_ net.Conn, host string) (smtpClient, error) { + if host != testHost { + t.Errorf("Invalid host, got %q, want %q", host, testHost) + } + return testClient, nil + } + + if err := d.DialAndSend(getTestMessage()); err != nil { + t.Error(err) + } +} + +func assertConfig(t *testing.T, got, want *tls.Config) { + if want == nil { + want = &tls.Config{ServerName: testHost} + } + if got.ServerName != want.ServerName { + t.Errorf("Invalid field ServerName in config, got %q, want %q", got.ServerName, want.ServerName) + } + if got.InsecureSkipVerify != want.InsecureSkipVerify { + t.Errorf("Invalid field InsecureSkipVerify in config, got %v, want %v", got.InsecureSkipVerify, want.InsecureSkipVerify) + } +} diff --git a/email/gomail/writeto.go b/email/gomail/writeto.go new file mode 100644 index 0000000..a336177 --- /dev/null +++ b/email/gomail/writeto.go @@ -0,0 +1,306 @@ +package gomail + +import ( + "encoding/base64" + "errors" + "io" + "mime" + "mime/multipart" + "path/filepath" + "strings" + "time" +) + +// WriteTo implements io.WriterTo. It dumps the whole message into w. +func (m *Message) WriteTo(w io.Writer) (int64, error) { + mw := &messageWriter{w: w} + mw.writeMessage(m) + return mw.n, mw.err +} + +func (w *messageWriter) writeMessage(m *Message) { + if _, ok := m.header["MIME-Version"]; !ok { + w.writeString("MIME-Version: 1.0\r\n") + } + if _, ok := m.header["Date"]; !ok { + w.writeHeader("Date", m.FormatDate(now())) + } + w.writeHeaders(m.header) + + if m.hasMixedPart() { + w.openMultipart("mixed") + } + + if m.hasRelatedPart() { + w.openMultipart("related") + } + + if m.hasAlternativePart() { + w.openMultipart("alternative") + } + for _, part := range m.parts { + w.writePart(part, m.charset) + } + if m.hasAlternativePart() { + w.closeMultipart() + } + + w.addFiles(m.embedded, false) + if m.hasRelatedPart() { + w.closeMultipart() + } + + w.addFiles(m.attachments, true) + if m.hasMixedPart() { + w.closeMultipart() + } +} + +func (m *Message) hasMixedPart() bool { + return (len(m.parts) > 0 && len(m.attachments) > 0) || len(m.attachments) > 1 +} + +func (m *Message) hasRelatedPart() bool { + return (len(m.parts) > 0 && len(m.embedded) > 0) || len(m.embedded) > 1 +} + +func (m *Message) hasAlternativePart() bool { + return len(m.parts) > 1 +} + +type messageWriter struct { + writers [3]*multipart.Writer + w io.Writer + partWriter io.Writer + err error + n int64 + depth uint8 +} + +func (w *messageWriter) openMultipart(mimeType string) { + mw := multipart.NewWriter(w) + contentType := "multipart/" + mimeType + ";\r\n boundary=" + mw.Boundary() + w.writers[w.depth] = mw + + if w.depth == 0 { + w.writeHeader("Content-Type", contentType) + w.writeString("\r\n") + } else { + w.createPart(map[string][]string{ + "Content-Type": {contentType}, + }) + } + w.depth++ +} + +func (w *messageWriter) createPart(h map[string][]string) { + w.partWriter, w.err = w.writers[w.depth-1].CreatePart(h) +} + +func (w *messageWriter) closeMultipart() { + if w.depth > 0 { + w.writers[w.depth-1].Close() + w.depth-- + } +} + +func (w *messageWriter) writePart(p *part, charset string) { + w.writeHeaders(map[string][]string{ + "Content-Type": {p.contentType + "; charset=" + charset}, + "Content-Transfer-Encoding": {string(p.encoding)}, + }) + w.writeBody(p.copier, p.encoding) +} + +func (w *messageWriter) addFiles(files []*file, isAttachment bool) { + for _, f := range files { + if _, ok := f.Header["Content-Type"]; !ok { + mediaType := mime.TypeByExtension(filepath.Ext(f.Name)) + if mediaType == "" { + mediaType = "application/octet-stream" + } + f.setHeader("Content-Type", mediaType+`; name="`+f.Name+`"`) + } + + if _, ok := f.Header["Content-Transfer-Encoding"]; !ok { + f.setHeader("Content-Transfer-Encoding", string(Base64)) + } + + if _, ok := f.Header["Content-Disposition"]; !ok { + var disp string + if isAttachment { + disp = "attachment" + } else { + disp = "inline" + } + f.setHeader("Content-Disposition", disp+`; filename="`+f.Name+`"`) + } + + if !isAttachment { + if _, ok := f.Header["Content-ID"]; !ok { + f.setHeader("Content-ID", "<"+f.Name+">") + } + } + w.writeHeaders(f.Header) + w.writeBody(f.CopyFunc, Base64) + } +} + +func (w *messageWriter) Write(p []byte) (int, error) { + if w.err != nil { + return 0, errors.New("gomail: cannot write as writer is in error") + } + + var n int + n, w.err = w.w.Write(p) + w.n += int64(n) + return n, w.err +} + +func (w *messageWriter) writeString(s string) { + n, _ := io.WriteString(w.w, s) + w.n += int64(n) +} + +func (w *messageWriter) writeHeader(k string, v ...string) { + w.writeString(k) + if len(v) == 0 { + w.writeString(":\r\n") + return + } + w.writeString(": ") + + // Max header line length is 78 characters in RFC 5322 and 76 characters + // in RFC 2047. So for the sake of simplicity we use the 76 characters + // limit. + charsLeft := 76 - len(k) - len(": ") + + for i, s := range v { + // If the line is already too long, insert a newline right away. + if charsLeft < 1 { + if i == 0 { + w.writeString("\r\n ") + } else { + w.writeString(",\r\n ") + } + charsLeft = 75 + } else if i != 0 { + w.writeString(", ") + charsLeft -= 2 + } + + // While the header content is too long, fold it by inserting a newline. + for len(s) > charsLeft { + s = w.writeLine(s, charsLeft) + charsLeft = 75 + } + w.writeString(s) + if i := lastIndexByte(s, '\n'); i != -1 { + charsLeft = 75 - (len(s) - i - 1) + } else { + charsLeft -= len(s) + } + } + w.writeString("\r\n") +} + +func (w *messageWriter) writeLine(s string, charsLeft int) string { + // If there is already a newline before the limit. Write the line. + if i := strings.IndexByte(s, '\n'); i != -1 && i < charsLeft { + w.writeString(s[:i+1]) + return s[i+1:] + } + + for i := charsLeft - 1; i >= 0; i-- { + if s[i] == ' ' { + w.writeString(s[:i]) + w.writeString("\r\n ") + return s[i+1:] + } + } + + // We could not insert a newline cleanly so look for a space or a newline + // even if it is after the limit. + for i := 75; i < len(s); i++ { + if s[i] == ' ' { + w.writeString(s[:i]) + w.writeString("\r\n ") + return s[i+1:] + } + if s[i] == '\n' { + w.writeString(s[:i+1]) + return s[i+1:] + } + } + + // Too bad, no space or newline in the whole string. Just write everything. + w.writeString(s) + return "" +} + +func (w *messageWriter) writeHeaders(h map[string][]string) { + if w.depth == 0 { + for k, v := range h { + if k != "Bcc" { + w.writeHeader(k, v...) + } + } + } else { + w.createPart(h) + } +} + +func (w *messageWriter) writeBody(f func(io.Writer) error, enc Encoding) { + var subWriter io.Writer + if w.depth == 0 { + w.writeString("\r\n") + subWriter = w.w + } else { + subWriter = w.partWriter + } + + if enc == Base64 { + wc := base64.NewEncoder(base64.StdEncoding, newBase64LineWriter(subWriter)) + w.err = f(wc) + wc.Close() + } else if enc == Unencoded { + w.err = f(subWriter) + } else { + wc := newQPWriter(subWriter) + w.err = f(wc) + wc.Close() + } +} + +// As required by RFC 2045, 6.7. (page 21) for quoted-printable, and +// RFC 2045, 6.8. (page 25) for base64. +const maxLineLen = 76 + +// base64LineWriter limits text encoded in base64 to 76 characters per line +type base64LineWriter struct { + w io.Writer + lineLen int +} + +func newBase64LineWriter(w io.Writer) *base64LineWriter { + return &base64LineWriter{w: w} +} + +func (w *base64LineWriter) Write(p []byte) (int, error) { + n := 0 + for len(p)+w.lineLen > maxLineLen { + w.w.Write(p[:maxLineLen-w.lineLen]) + w.w.Write([]byte("\r\n")) + p = p[maxLineLen-w.lineLen:] + n += maxLineLen - w.lineLen + w.lineLen = 0 + } + + w.w.Write(p) + w.lineLen += len(p) + + return n + len(p), nil +} + +// Stubbed out for testing. +var now = time.Now diff --git a/email/message.go b/email/message.go new file mode 100644 index 0000000..e8b21e1 --- /dev/null +++ b/email/message.go @@ -0,0 +1,44 @@ +package email + +import ( + "errors" + "net/mail" +) + +type Message struct { + ReplyTo *mail.Address `json:"replyTo"` + + ID string + From string `json:"from"` + Subject string `json:"subject"` + HtmlBody string `json:"htmlBody"` + TxtBody string `json:"txtBody"` + + To []mail.Address `json:"to"` + Cc []mail.Address `json:"cc"` + Bcc []mail.Address `json:"bcc"` +} + +func (m *Message) Validate() error { + if m == nil { + return errors.New("email: message is nil") + } + + if len(m.To) == 0 { + return errors.New("email: message must have at least one recipient") + } + + if len(m.From) == 0 { + return errors.New("email: message must have a sender") + } + + if len(m.Subject) == 0 { + return errors.New("email: message must have a subject") + } + + if len(m.HtmlBody) == 0 && len(m.TxtBody) == 0 { + return errors.New("email: message must have a body") + } + + return nil +} diff --git a/email/render.go b/email/render.go new file mode 100644 index 0000000..2502647 --- /dev/null +++ b/email/render.go @@ -0,0 +1,45 @@ +package email + +import ( + "bytes" + "html/template" + txt "text/template" +) + +func RenderHTMLTemplate(layout, content string, data map[string]any) (string, error) { + // layout + tpl, err := template.New("layout").Parse(layout) + if err != nil { + return "", err + } + + // content + _, err = tpl.New("content").Parse(content) + if err != nil { + return "", err + } + + // execute layout + content template and RenderHTML data + buf := new(bytes.Buffer) + err = tpl.ExecuteTemplate(buf, "layout", data) + if err != nil { + return "", err + } + + return buf.String(), nil +} + +func RenderTxtTemplate(content string, data map[string]any) (string, error) { + tpl, err := txt.New("content").Parse(content) + if err != nil { + return "", err + } + + buf := new(bytes.Buffer) + err = tpl.ExecuteTemplate(buf, "content", data) + if err != nil { + return "", err + } + + return buf.String(), nil +} diff --git a/email/transport.go b/email/transport.go new file mode 100644 index 0000000..58bfe7e --- /dev/null +++ b/email/transport.go @@ -0,0 +1,35 @@ +package email + +import ( + "os" + "path/filepath" + "time" + + "code.patial.tech/go/appcore/open" +) + +type Transport interface { + Send(*Message) error +} + +// DumpToTemp transport is for development environment to ensure emails are renderd as HTML ok +// +// once dump operation is done it will try to open the html with default app for html +type DumpToTemp struct{} + +func (DumpToTemp) Send(msg *Message) error { + // validate msg first + if err := msg.Validate(); err != nil { + return err + } + + dir := os.TempDir() + id := time.Now().Format("20060102T150405999") + file := filepath.Join(dir, id+".html") + + if err := os.WriteFile(file, []byte(msg.HtmlBody), 0440); err != nil { + return err + } + + return open.WithDefaultApp(file) +} diff --git a/email/transport_smtp.go b/email/transport_smtp.go new file mode 100644 index 0000000..0badd2b --- /dev/null +++ b/email/transport_smtp.go @@ -0,0 +1,89 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package email + +import ( + "fmt" + "log/slog" + "strings" + + "code.patial.tech/go/appcore/email/gomail" + "code.patial.tech/go/appcore/uid" +) + +// SMTP mailer +type SMTP struct { + Host string + Port int + Username string + Password string + // Domain name for smtp + Domain string +} + +func (t SMTP) Send(msg *Message) error { + slog.Info("sending mail", slog.String("smtp", t.Host)) + // validate msg + if err := msg.Validate(); err != nil { + return err + } + + toCount := len(msg.To) + m := gomail.NewMessage() + if msg.ID != "" { + m.SetHeader("Message-ID", fmt.Sprintf("<%s>", msg.ID)) + } else { + uid, err := uid.NewUUID() + if err != nil { + return err + } + + id := strings.Replace(uid, "-", "", -1) + msgID := fmt.Sprintf("", id, t.Domain) + m.SetHeader("Message-ID", msgID) + } + + m.SetHeader("From", msg.From) + + // TO + to := make([]string, toCount) + for i, address := range msg.To { + to[i] = address.String() + } + m.SetHeader("To", to...) + + // subject + m.SetHeader("Subject", msg.Subject) + + // CC + ccCount := len(msg.Cc) + if ccCount > 0 { + cc := make([]string, ccCount) + for i, address := range msg.Cc { + cc[i] = address.String() + } + m.SetHeader("Cc", cc...) + } + + // BCC + bccCount := len(msg.Bcc) + if bccCount > 0 { + bcc := make([]string, bccCount) + for i, address := range msg.Bcc { + bcc[i] = address.String() + } + m.SetHeader("Bcc", bcc...) + } + + m.SetBody("text/html", msg.HtmlBody) + + slog.Info("dialing...", slog.String("host", t.Host), slog.Int("port", t.Port)) + d := gomail.NewDialer(t.Host, t.Port, t.Username, t.Password) + if err := d.DialAndSend(m); err != nil { + return err + } + + slog.Info("sent email %s" + msg.Subject) + return nil +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e345951 --- /dev/null +++ b/go.mod @@ -0,0 +1,21 @@ +module code.patial.tech/go/appcore + +go 1.24.4 + +require ( + github.com/go-playground/validator/v10 v10.26.0 + github.com/golang-jwt/jwt/v5 v5.2.2 + github.com/google/uuid v1.6.0 + github.com/sqids/sqids-go v0.4.1 + golang.org/x/crypto v0.39.0 +) + +require ( + github.com/gabriel-vasile/mimetype v1.4.8 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + golang.org/x/net v0.34.0 // indirect + golang.org/x/sys v0.33.0 // indirect + golang.org/x/text v0.26.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5db0534 --- /dev/null +++ b/go.sum @@ -0,0 +1,34 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= +github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k= +github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo= +github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= +github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sqids/sqids-go v0.4.1 h1:eQKYzmAZbLlRwHeHYPF35QhgxwZHLnlmVj9AkIj/rrw= +github.com/sqids/sqids-go v0.4.1/go.mod h1:EMwHuPQgSNFS0A49jESTfIQS+066XQTVhukrzEPScl8= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= +golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= +golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= +golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= +golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/jwt/jwt.go b/jwt/jwt.go new file mode 100644 index 0000000..9926027 --- /dev/null +++ b/jwt/jwt.go @@ -0,0 +1,48 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package jwt + +import ( + "crypto/ed25519" + "errors" + "log" + "maps" + "time" + + "github.com/golang-jwt/jwt/v5" +) + +func Sign(key ed25519.PrivateKey, claims map[string]any, issuer string, d time.Duration) (string, error) { + cl := jwt.MapClaims{ + "iss": issuer, + "iat": jwt.NewNumericDate(time.Now().UTC()), + "exp": jwt.NewNumericDate(time.Now().Add(d)), + } + maps.Copy(cl, claims) + + t := jwt.NewWithClaims(jwt.SigningMethodEdDSA, cl) + return t.SignedString(key) +} + +func Parse(key ed25519.PrivateKey, tokenString string, issuer string) (jwt.MapClaims, error) { + token, err := jwt.Parse( + tokenString, + func(token *jwt.Token) (any, error) { + return key.Public(), nil + }, + jwt.WithValidMethods([]string{jwt.SigningMethodEdDSA.Alg()}), + jwt.WithIssuer(issuer), + jwt.WithIssuedAt(), + jwt.WithExpirationRequired(), + ) + if err != nil { + log.Fatal(err) + } + + if claims, ok := token.Claims.(jwt.MapClaims); ok { + return claims, nil + } else { + return nil, errors.New("no claims found") + } +} diff --git a/jwt/jwt_test.go b/jwt/jwt_test.go new file mode 100644 index 0000000..84c5f52 --- /dev/null +++ b/jwt/jwt_test.go @@ -0,0 +1,57 @@ +package jwt + +import ( + "fmt" + "testing" + "time" + + "code.patial.tech/go/appcore/crypto" +) + +/* +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEA9JTCYl3OQwuVTSf0PsBkmgJSt7e5Tbk3jKnB90vDqXA= +-----END PUBLIC KEY----- + +-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIMMkYUKJ9P0gp+Rm9mR4i0KUBT9nFUzxzxjH7sC0xq/F +-----END PRIVATE KEY----- +*/ + +func TestSign2(t *testing.T) { + key, err := crypto.ParseEdPrivateKey([]byte(`-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIMMkYUKJ9P0gp+Rm9mR4i0KUBT9nFUzxzxjH7sC0xq/F +-----END PRIVATE KEY-----`)) + if err != nil { + t.Fatal(err) + } + + s, err := Sign(key, map[string]any{"name": "ankit", "age": 25}, "blackdu", time.Second) + if err != nil { + t.Fatal(err) + } + + println(s) +} + +func TestExprired(t *testing.T) { + privKey, err := crypto.ParseEdPrivateKey([]byte(`-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIMMkYUKJ9P0gp+Rm9mR4i0KUBT9nFUzxzxjH7sC0xq/F +-----END PRIVATE KEY-----`)) + if err != nil { + t.Error(err) + } + + // payload := "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJhZ2UiOjI1LCJleHAiOjE3NDQxMjAxNzUsImlhdCI6MTc0NDEyMDE3NCwiaXNzIjoiYmxhY2tkdSIsIm5hbWUiOiJhbmtpdCJ9.W6OQHMRdcRiPS398p8u0vLjpq34oxYPDengillXSFEDXJVXOkzl0ncCpju0yuMOhrQLRRG0EJLKfoFcAxsbpDA" + payload, err := Sign(privKey, map[string]any{"name": "ankit", "age": 25}, "blackdu", time.Second) + if err != nil { + t.Fatal(err) + } + + claims, err := Parse(privKey, payload, "blackdu") + if err != nil { + t.Fatal(err) + } + + fmt.Printf("%v", claims) +} diff --git a/mime/mime.go b/mime/mime.go new file mode 100644 index 0000000..95b4ffa --- /dev/null +++ b/mime/mime.go @@ -0,0 +1,1137 @@ +// Copyright 2024 Patial Tech. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mime + +import "strings" + +var mimeTypes = map[string]string{ + "123": "application/vnd.lotus-1-2-3", + "3dml": "text/vnd.in3d.3dml", + "3ds": "image/x-3ds", + "3g2": "video/3gpp2", + "3gp": "video/3gpp", + "3gpp": "video/3gpp", + "7z": "application/x-7z-compressed", + "aab": "application/x-authorware-bin", + "aac": "audio/x-aac", + "aam": "application/x-authorware-map", + "aas": "application/x-authorware-seg", + "abw": "application/x-abiword", + "ac": "application/pkix-attr-cert", + "acc": "application/vnd.americandynamics.acc", + "ace": "application/x-ace-compressed", + "acu": "application/vnd.acucobol", + "acutc": "application/vnd.acucorp", + "adp": "audio/adpcm", + "aep": "application/vnd.audiograph", + "afm": "application/x-font-type1", + "afp": "application/vnd.ibm.modcap", + "ahead": "application/vnd.ahead.space", + "ai": "application/postscript", + "aif": "audio/x-aiff", + "aifc": "audio/x-aiff", + "aiff": "audio/x-aiff", + "air": "application/vnd.adobe.air-application-installer-package+zip", + "ait": "application/vnd.dvb.ait", + "ami": "application/vnd.amiga.ami", + "apk": "application/vnd.android.package-archive", + "apng": "image/apng", + "appcache": "text/cache-manifest", + "application": "application/x-ms-application", + "apr": "application/vnd.lotus-approach", + "arc": "application/x-freearc", + "arj": "application/x-arj", + "arw": "image/x-sony-arw", + "asc": "application/pgp-signature", + "asf": "video/x-ms-asf", + "asm": "text/x-asm", + "aso": "application/vnd.accpac.simply.aso", + "asx": "video/x-ms-asf", + "atc": "application/vnd.acucorp", + "atom": "application/atom+xml", + "atomcat": "application/atomcat+xml", + "atomsvc": "application/atomsvc+xml", + "atx": "application/vnd.antix.game-component", + "au": "audio/basic", + "avi": "video/x-msvideo", + "aw": "application/applixware", + "azf": "application/vnd.airzip.filesecure.azf", + "azs": "application/vnd.airzip.filesecure.azs", + "azv": "image/vnd.airzip.accelerator.azv", + "azw": "application/vnd.amazon.ebook", + "bat": "application/x-msdownload", + "bcpio": "application/x-bcpio", + "bdf": "application/x-font-bdf", + "bdm": "application/vnd.syncml.dm+wbxml", + "bdoc": "application/x-bdoc", + "bed": "application/vnd.realvnc.bed", + "bh2": "application/vnd.fujitsu.oasysprs", + "bin": "application/octet-stream", + "blb": "application/x-blorb", + "blorb": "application/x-blorb", + "bmi": "application/vnd.bmi", + "bmp": "image/x-ms-bmp", + "book": "application/vnd.framemaker", + "box": "application/vnd.previewsystems.box", + "boz": "application/x-bzip2", + "bpk": "application/octet-stream", + "btif": "image/prs.btif", + "buffer": "application/octet-stream", + "bz": "application/x-bzip", + "bz2": "application/x-bzip2", + "c": "text/x-c", + "c11amc": "application/vnd.cluetrust.cartomobile-config", + "c11amz": "application/vnd.cluetrust.cartomobile-config-pkg", + "c4d": "application/vnd.clonk.c4group", + "c4f": "application/vnd.clonk.c4group", + "c4g": "application/vnd.clonk.c4group", + "c4p": "application/vnd.clonk.c4group", + "c4u": "application/vnd.clonk.c4group", + "cab": "application/vnd.ms-cab-compressed", + "caf": "audio/x-caf", + "cap": "application/vnd.tcpdump.pcap", + "car": "application/vnd.curl.car", + "cat": "application/vnd.ms-pki.seccat", + "cb7": "application/x-cbr", + "cba": "application/x-cbr", + "cbr": "application/x-cbr", + "cbt": "application/x-cbr", + "cbz": "application/x-cbr", + "cc": "text/x-c", + "cco": "application/x-cocoa", + "cct": "application/x-director", + "ccxml": "application/ccxml+xml", + "cdbcmsg": "application/vnd.contact.cmsg", + "cdf": "application/x-netcdf", + "cdkey": "application/vnd.mediastation.cdkey", + "cdmia": "application/cdmi-capability", + "cdmic": "application/cdmi-container", + "cdmid": "application/cdmi-domain", + "cdmio": "application/cdmi-object", + "cdmiq": "application/cdmi-queue", + "cdx": "chemical/x-cdx", + "cdxml": "application/vnd.chemdraw+xml", + "cdy": "application/vnd.cinderella", + "cer": "application/pkix-cert", + "cfs": "application/x-cfs-compressed", + "cgm": "image/cgm", + "chat": "application/x-chat", + "chm": "application/vnd.ms-htmlhelp", + "chrt": "application/vnd.kde.kchart", + "cif": "chemical/x-cif", + "cii": "application/vnd.anser-web-certificate-issue-initiation", + "cil": "application/vnd.ms-artgalry", + "cla": "application/vnd.claymore", + "class": "application/java-vm", + "clkk": "application/vnd.crick.clicker.keyboard", + "clkp": "application/vnd.crick.clicker.palette", + "clkt": "application/vnd.crick.clicker.template", + "clkw": "application/vnd.crick.clicker.wordbank", + "clkx": "application/vnd.crick.clicker", + "clp": "application/x-msclip", + "cmc": "application/vnd.cosmocaller", + "cmdf": "chemical/x-cmdf", + "cml": "chemical/x-cml", + "cmp": "application/vnd.yellowriver-custom-menu", + "cmx": "image/x-cmx", + "cod": "application/vnd.rim.cod", + "coffee": "text/coffeescript", + "com": "application/x-msdownload", + "conf": "text/plain", + "cpio": "application/x-cpio", + "cpp": "text/x-c", + "cpt": "application/mac-compactpro", + "cr2": "image/x-canon-cr2", + "crd": "application/x-mscardfile", + "crl": "application/pkix-crl", + "crt": "application/x-x509-ca-cert", + "crw": "image/x-canon-crw", + "crx": "application/x-chrome-extension", + "cryptonote": "application/vnd.rig.cryptonote", + "csh": "application/x-csh", + "csl": "application/vnd.citationstyles.style+xml", + "csml": "chemical/x-csml", + "csp": "application/vnd.commonspace", + "css": "text/css", + "cst": "application/x-director", + "csv": "text/csv", + "cu": "application/cu-seeme", + "curl": "text/vnd.curl", + "cww": "application/prs.cww", + "cxt": "application/x-director", + "cxx": "text/x-c", + "dae": "model/vnd.collada+xml", + "daf": "application/vnd.mobius.daf", + "dart": "application/vnd.dart", + "dataless": "application/vnd.fdsn.seed", + "davmount": "application/davmount+xml", + "dbk": "application/docbook+xml", + "dcr": "application/x-director", + "dcurl": "text/vnd.curl.dcurl", + "dd2": "application/vnd.oma.dd2+xml", + "ddd": "application/vnd.fujixerox.ddd", + "deb": "application/x-debian-package", + "def": "text/plain", + "deploy": "application/octet-stream", + "der": "application/x-x509-ca-cert", + "dfac": "application/vnd.dreamfactory", + "dgc": "application/x-dgc-compressed", + "dic": "text/x-c", + "dir": "application/x-director", + "dis": "application/vnd.mobius.dis", + "disposition-notification": "message/disposition-notification", + "dist": "application/octet-stream", + "distz": "application/octet-stream", + "djv": "image/vnd.djvu", + "djvu": "image/vnd.djvu", + "dll": "application/x-msdownload", + "dmg": "application/x-apple-diskimage", + "dmp": "application/vnd.tcpdump.pcap", + "dms": "application/octet-stream", + "dna": "application/vnd.dna", + "dng": "image/x-adobe-dng", + "doc": "application/msword", + "docm": "application/vnd.ms-word.document.macroenabled.12", + "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "dot": "application/msword", + "dotm": "application/vnd.ms-word.template.macroenabled.12", + "dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template", + "dp": "application/vnd.osgi.dp", + "dpg": "application/vnd.dpgraph", + "dra": "audio/vnd.dra", + "drle": "image/dicom-rle", + "dsc": "text/prs.lines.tag", + "dssc": "application/dssc+der", + "dtb": "application/x-dtbook+xml", + "dtd": "application/xml-dtd", + "dts": "audio/vnd.dts", + "dtshd": "audio/vnd.dts.hd", + "dump": "application/octet-stream", + "dvb": "video/vnd.dvb.file", + "dvi": "application/x-dvi", + "dwf": "model/vnd.dwf", + "dwg": "image/vnd.dwg", + "dxf": "image/vnd.dxf", + "dxp": "application/vnd.spotfire.dxp", + "dxr": "application/x-director", + "ear": "application/java-archive", + "ecelp4800": "audio/vnd.nuera.ecelp4800", + "ecelp7470": "audio/vnd.nuera.ecelp7470", + "ecelp9600": "audio/vnd.nuera.ecelp9600", + "ecma": "application/ecmascript", + "edm": "application/vnd.novadigm.edm", + "edx": "application/vnd.novadigm.edx", + "efif": "application/vnd.picsel", + "ei6": "application/vnd.pg.osasli", + "elc": "application/octet-stream", + "emf": "image/emf", + "eml": "message/rfc822", + "emma": "application/emma+xml", + "emz": "application/x-msmetafile", + "eol": "audio/vnd.digital-winds", + "eot": "application/vnd.ms-fontobject", + "eps": "application/postscript", + "epub": "application/epub+zip", + "erf": "image/x-epson-erf", + "es": "application/ecmascript", + "es3": "application/vnd.eszigno3+xml", + "esa": "application/vnd.osgi.subsystem", + "esf": "application/vnd.epson.esf", + "et3": "application/vnd.eszigno3+xml", + "etx": "text/x-setext", + "eva": "application/x-eva", + "evy": "application/x-envoy", + "exe": "application/x-msdownload", + "exi": "application/exi", + "exr": "image/aces", + "ext": "application/vnd.novadigm.ext", + "ez": "application/andrew-inset", + "ez2": "application/vnd.ezpix-album", + "ez3": "application/vnd.ezpix-package", + "f": "text/x-fortran", + "f4v": "video/x-f4v", + "f77": "text/x-fortran", + "f90": "text/x-fortran", + "fbs": "image/vnd.fastbidsheet", + "fcdt": "application/vnd.adobe.formscentral.fcdt", + "fcs": "application/vnd.isac.fcs", + "fdf": "application/vnd.fdf", + "fe_launch": "application/vnd.denovo.fcselayout-link", + "fg5": "application/vnd.fujitsu.oasysgp", + "fgd": "application/x-director", + "fh": "image/x-freehand", + "fh4": "image/x-freehand", + "fh5": "image/x-freehand", + "fh7": "image/x-freehand", + "fhc": "image/x-freehand", + "fig": "application/x-xfig", + "fits": "image/fits", + "flac": "audio/x-flac", + "fli": "video/x-fli", + "flo": "application/vnd.micrografx.flo", + "flv": "video/x-flv", + "flw": "application/vnd.kde.kivio", + "flx": "text/vnd.fmi.flexstor", + "fly": "text/vnd.fly", + "fm": "application/vnd.framemaker", + "fnc": "application/vnd.frogans.fnc", + "for": "text/x-fortran", + "fpx": "image/vnd.fpx", + "frame": "application/vnd.framemaker", + "fsc": "application/vnd.fsc.weblaunch", + "fst": "image/vnd.fst", + "ftc": "application/vnd.fluxtime.clip", + "fti": "application/vnd.anser-web-funds-transfer-initiation", + "fvt": "video/vnd.fvt", + "fxp": "application/vnd.adobe.fxp", + "fxpl": "application/vnd.adobe.fxp", + "fzs": "application/vnd.fuzzysheet", + "g2w": "application/vnd.geoplan", + "g3": "image/g3fax", + "g3w": "application/vnd.geospace", + "gac": "application/vnd.groove-account", + "gam": "application/x-tads", + "gbr": "application/rpki-ghostbusters", + "gca": "application/x-gca-compressed", + "gdl": "model/vnd.gdl", + "gdoc": "application/vnd.google-apps.document", + "geo": "application/vnd.dynageo", + "geojson": "application/geo+json", + "gex": "application/vnd.geometry-explorer", + "ggb": "application/vnd.geogebra.file", + "ggt": "application/vnd.geogebra.tool", + "ghf": "application/vnd.groove-help", + "gif": "image/gif", + "gim": "application/vnd.groove-identity-message", + "glb": "model/gltf-binary", + "gltf": "model/gltf+json", + "gml": "application/gml+xml", + "gmx": "application/vnd.gmx", + "gnumeric": "application/x-gnumeric", + "gph": "application/vnd.flographit", + "gpx": "application/gpx+xml", + "gqf": "application/vnd.grafeq", + "gqs": "application/vnd.grafeq", + "gram": "application/srgs", + "gramps": "application/x-gramps-xml", + "gre": "application/vnd.geometry-explorer", + "grv": "application/vnd.groove-injector", + "grxml": "application/srgs+xml", + "gsf": "application/x-font-ghostscript", + "gsheet": "application/vnd.google-apps.spreadsheet", + "gslides": "application/vnd.google-apps.presentation", + "gtar": "application/x-gtar", + "gtm": "application/vnd.groove-tool-message", + "gtw": "model/vnd.gtw", + "gv": "text/vnd.graphviz", + "gxf": "application/gxf", + "gxt": "application/vnd.geonext", + "gz": "application/gzip", + "h": "text/x-c", + "h261": "video/h261", + "h263": "video/h263", + "h264": "video/h264", + "hal": "application/vnd.hal+xml", + "hbci": "application/vnd.hbci", + "hbs": "text/x-handlebars-template", + "hdd": "application/x-virtualbox-hdd", + "hdf": "application/x-hdf", + "heic": "image/heic", + "heics": "image/heic-sequence", + "heif": "image/heif", + "heifs": "image/heif-sequence", + "hh": "text/x-c", + "hjson": "application/hjson", + "hlp": "application/winhlp", + "hpgl": "application/vnd.hp-hpgl", + "hpid": "application/vnd.hp-hpid", + "hps": "application/vnd.hp-hps", + "hqx": "application/mac-binhex40", + "htc": "text/x-component", + "htke": "application/vnd.kenameaapp", + "htm": "text/html", + "html": "text/html", + "hvd": "application/vnd.yamaha.hv-dic", + "hvp": "application/vnd.yamaha.hv-voice", + "hvs": "application/vnd.yamaha.hv-script", + "i2g": "application/vnd.intergeo", + "icc": "application/vnd.iccprofile", + "ice": "x-conference/x-cooltalk", + "icm": "application/vnd.iccprofile", + "ico": "image/x-icon", + "ics": "text/calendar", + "ief": "image/ief", + "ifb": "text/calendar", + "ifm": "application/vnd.shana.informed.formdata", + "iges": "model/iges", + "igl": "application/vnd.igloader", + "igm": "application/vnd.insors.igm", + "igs": "model/iges", + "igx": "application/vnd.micrografx.igx", + "iif": "application/vnd.shana.informed.interchange", + "img": "application/octet-stream", + "imp": "application/vnd.accpac.simply.imp", + "ims": "application/vnd.ms-ims", + "in": "text/plain", + "ini": "text/plain", + "ink": "application/inkml+xml", + "inkml": "application/inkml+xml", + "install": "application/x-install-instructions", + "iota": "application/vnd.astraea-software.iota", + "ipfix": "application/ipfix", + "ipk": "application/vnd.shana.informed.package", + "irm": "application/vnd.ibm.rights-management", + "irp": "application/vnd.irepository.package+xml", + "iso": "application/x-iso9660-image", + "itp": "application/vnd.shana.informed.formtemplate", + "ivp": "application/vnd.immervision-ivp", + "ivu": "application/vnd.immervision-ivu", + "jad": "text/vnd.sun.j2me.app-descriptor", + "jade": "text/jade", + "jam": "application/vnd.jam", + "jar": "application/java-archive", + "jardiff": "application/x-java-archive-diff", + "java": "text/x-java-source", + "jisp": "application/vnd.jisp", + "jls": "image/jls", + "jlt": "application/vnd.hp-jlyt", + "jng": "image/x-jng", + "jnlp": "application/x-java-jnlp-file", + "joda": "application/vnd.joost.joda-archive", + "jp2": "image/jp2", + "jpe": "image/jpeg", + "jpeg": "image/jpeg", + "jpf": "image/jpx", + "jpg": "image/jpeg", + "jpg2": "image/jp2", + "jpgm": "video/jpm", + "jpgv": "video/jpeg", + "jpm": "video/jpm", + "jpx": "image/jpx", + "js": "application/javascript", + "json": "application/json", + "json5": "application/json5", + "jsonld": "application/ld+json", + "jsonml": "application/jsonml+json", + "jsx": "text/jsx", + "k25": "image/x-kodak-k25", + "kar": "audio/midi", + "karbon": "application/vnd.kde.karbon", + "kdc": "image/x-kodak-kdc", + "keynote": "application/vnd.apple.keynote", + "kfo": "application/vnd.kde.kformula", + "kia": "application/vnd.kidspiration", + "kml": "application/vnd.google-earth.kml+xml", + "kmz": "application/vnd.google-earth.kmz", + "kne": "application/vnd.kinar", + "knp": "application/vnd.kinar", + "kon": "application/vnd.kde.kontour", + "kpr": "application/vnd.kde.kpresenter", + "kpt": "application/vnd.kde.kpresenter", + "kpxx": "application/vnd.ds-keypoint", + "ksp": "application/vnd.kde.kspread", + "ktr": "application/vnd.kahootz", + "ktx": "image/ktx", + "ktz": "application/vnd.kahootz", + "kwd": "application/vnd.kde.kword", + "kwt": "application/vnd.kde.kword", + "lasxml": "application/vnd.las.las+xml", + "latex": "application/x-latex", + "lbd": "application/vnd.llamagraphics.life-balance.desktop", + "lbe": "application/vnd.llamagraphics.life-balance.exchange+xml", + "les": "application/vnd.hhe.lesson-player", + "less": "text/less", + "lha": "application/x-lzh-compressed", + "link66": "application/vnd.route66.link66+xml", + "list": "text/plain", + "list3820": "application/vnd.ibm.modcap", + "listafp": "application/vnd.ibm.modcap", + "litcoffee": "text/coffeescript", + "lnk": "application/x-ms-shortcut", + "log": "text/plain", + "lostxml": "application/lost+xml", + "lrf": "application/octet-stream", + "lrm": "application/vnd.ms-lrm", + "ltf": "application/vnd.frogans.ltf", + "lua": "text/x-lua", + "luac": "application/x-lua-bytecode", + "lvp": "audio/vnd.lucent.voice", + "lwp": "application/vnd.lotus-wordpro", + "lzh": "application/x-lzh-compressed", + "m13": "application/x-msmediaview", + "m14": "application/x-msmediaview", + "m1v": "video/mpeg", + "m21": "application/mp21", + "m2a": "audio/mpeg", + "m2v": "video/mpeg", + "m3a": "audio/mpeg", + "m3u": "audio/x-mpegurl", + "m3u8": "application/vnd.apple.mpegurl", + "m4a": "audio/x-m4a", + "m4p": "application/mp4", + "m4u": "video/vnd.mpegurl", + "m4v": "video/x-m4v", + "ma": "application/mathematica", + "mads": "application/mads+xml", + "mag": "application/vnd.ecowin.chart", + "maker": "application/vnd.framemaker", + "man": "text/troff", + "manifest": "text/cache-manifest", + "map": "application/json", + "mar": "application/octet-stream", + "markdown": "text/markdown", + "mathml": "application/mathml+xml", + "mb": "application/mathematica", + "mbk": "application/vnd.mobius.mbk", + "mbox": "application/mbox", + "mc1": "application/vnd.medcalcdata", + "mcd": "application/vnd.mcd", + "mcurl": "text/vnd.curl.mcurl", + "md": "text/markdown", + "mdb": "application/x-msaccess", + "mdi": "image/vnd.ms-modi", + "me": "text/troff", + "mesh": "model/mesh", + "meta4": "application/metalink4+xml", + "metalink": "application/metalink+xml", + "mets": "application/mets+xml", + "mfm": "application/vnd.mfmp", + "mft": "application/rpki-manifest", + "mgp": "application/vnd.osgeo.mapguide.package", + "mgz": "application/vnd.proteus.magazine", + "mid": "audio/midi", + "midi": "audio/midi", + "mie": "application/x-mie", + "mif": "application/vnd.mif", + "mime": "message/rfc822", + "mj2": "video/mj2", + "mjp2": "video/mj2", + "mjs": "application/javascript", + "mk3d": "video/x-matroska", + "mka": "audio/x-matroska", + "mkd": "text/x-markdown", + "mks": "video/x-matroska", + "mkv": "video/x-matroska", + "mlp": "application/vnd.dolby.mlp", + "mmd": "application/vnd.chipnuts.karaoke-mmd", + "mmf": "application/vnd.smaf", + "mml": "text/mathml", + "mmr": "image/vnd.fujixerox.edmics-mmr", + "mng": "video/x-mng", + "mny": "application/x-msmoney", + "mobi": "application/x-mobipocket-ebook", + "mods": "application/mods+xml", + "mov": "video/quicktime", + "movie": "video/x-sgi-movie", + "mp2": "audio/mpeg", + "mp21": "application/mp21", + "mp2a": "audio/mpeg", + "mp3": "audio/mpeg", + "mp4": "video/mp4", + "mp4a": "audio/mp4", + "mp4s": "application/mp4", + "mp4v": "video/mp4", + "mpc": "application/vnd.mophun.certificate", + "mpd": "application/dash+xml", + "mpe": "video/mpeg", + "mpeg": "video/mpeg", + "mpg": "video/mpeg", + "mpg4": "video/mp4", + "mpga": "audio/mpeg", + "mpkg": "application/vnd.apple.installer+xml", + "mpm": "application/vnd.blueice.multipass", + "mpn": "application/vnd.mophun.application", + "mpp": "application/vnd.ms-project", + "mpt": "application/vnd.ms-project", + "mpy": "application/vnd.ibm.minipay", + "mqy": "application/vnd.mobius.mqy", + "mrc": "application/marc", + "mrcx": "application/marcxml+xml", + "mrw": "image/x-minolta-mrw", + "ms": "text/troff", + "mscml": "application/mediaservercontrol+xml", + "mseed": "application/vnd.fdsn.mseed", + "mseq": "application/vnd.mseq", + "msf": "application/vnd.epson.msf", + "msg": "application/vnd.ms-outlook", + "msh": "model/mesh", + "msi": "application/x-msdownload", + "msl": "application/vnd.mobius.msl", + "msm": "application/octet-stream", + "msp": "application/octet-stream", + "msty": "application/vnd.muvee.style", + "mts": "model/vnd.mts", + "mus": "application/vnd.musician", + "musicxml": "application/vnd.recordare.musicxml+xml", + "mvb": "application/x-msmediaview", + "mwf": "application/vnd.mfer", + "mxf": "application/mxf", + "mxl": "application/vnd.recordare.musicxml", + "mxml": "application/xv+xml", + "mxs": "application/vnd.triscape.mxs", + "mxu": "video/vnd.mpegurl", + "n-gage": "application/vnd.nokia.n-gage.symbian.install", + "n3": "text/n3", + "nb": "application/mathematica", + "nbp": "application/vnd.wolfram.player", + "nc": "application/x-netcdf", + "ncx": "application/x-dtbncx+xml", + "nef": "image/x-nikon-nef", + "nfo": "text/x-nfo", + "ngdat": "application/vnd.nokia.n-gage.data", + "nitf": "application/vnd.nitf", + "nlu": "application/vnd.neurolanguage.nlu", + "nml": "application/vnd.enliven", + "nnd": "application/vnd.noblenet-directory", + "nns": "application/vnd.noblenet-sealer", + "nnw": "application/vnd.noblenet-web", + "npx": "image/vnd.net-fpx", + "nsc": "application/x-conference", + "nsf": "application/vnd.lotus-notes", + "ntf": "application/vnd.nitf", + "numbers": "application/vnd.apple.numbers", + "nzb": "application/x-nzb", + "oa2": "application/vnd.fujitsu.oasys2", + "oa3": "application/vnd.fujitsu.oasys3", + "oas": "application/vnd.fujitsu.oasys", + "obd": "application/x-msbinder", + "obj": "application/x-tgif", + "oda": "application/oda", + "odb": "application/vnd.oasis.opendocument.database", + "odc": "application/vnd.oasis.opendocument.chart", + "odf": "application/vnd.oasis.opendocument.formula", + "odft": "application/vnd.oasis.opendocument.formula-template", + "odg": "application/vnd.oasis.opendocument.graphics", + "odi": "application/vnd.oasis.opendocument.image", + "odm": "application/vnd.oasis.opendocument.text-master", + "odp": "application/vnd.oasis.opendocument.presentation", + "ods": "application/vnd.oasis.opendocument.spreadsheet", + "odt": "application/vnd.oasis.opendocument.text", + "oga": "audio/ogg", + "ogg": "audio/ogg", + "ogv": "video/ogg", + "ogx": "application/ogg", + "omdoc": "application/omdoc+xml", + "onepkg": "application/onenote", + "onetmp": "application/onenote", + "onetoc": "application/onenote", + "onetoc2": "application/onenote", + "opf": "application/oebps-package+xml", + "opml": "text/x-opml", + "oprc": "application/vnd.palm", + "orf": "image/x-olympus-orf", + "org": "text/x-org", + "osf": "application/vnd.yamaha.openscoreformat", + "osfpvg": "application/vnd.yamaha.openscoreformat.osfpvg+xml", + "otc": "application/vnd.oasis.opendocument.chart-template", + "otf": "font/otf", + "otg": "application/vnd.oasis.opendocument.graphics-template", + "oth": "application/vnd.oasis.opendocument.text-web", + "oti": "application/vnd.oasis.opendocument.image-template", + "otp": "application/vnd.oasis.opendocument.presentation-template", + "ots": "application/vnd.oasis.opendocument.spreadsheet-template", + "ott": "application/vnd.oasis.opendocument.text-template", + "ova": "application/x-virtualbox-ova", + "ovf": "application/x-virtualbox-ovf", + "owl": "application/rdf+xml", + "oxps": "application/oxps", + "oxt": "application/vnd.openofficeorg.extension", + "p": "text/x-pascal", + "p10": "application/pkcs10", + "p12": "application/x-pkcs12", + "p7b": "application/x-pkcs7-certificates", + "p7c": "application/pkcs7-mime", + "p7m": "application/pkcs7-mime", + "p7r": "application/x-pkcs7-certreqresp", + "p7s": "application/pkcs7-signature", + "p8": "application/pkcs8", + "pac": "application/x-ns-proxy-autoconfig", + "pages": "application/vnd.apple.pages", + "pas": "text/x-pascal", + "paw": "application/vnd.pawaafile", + "pbd": "application/vnd.powerbuilder6", + "pbm": "image/x-portable-bitmap", + "pcap": "application/vnd.tcpdump.pcap", + "pcf": "application/x-font-pcf", + "pcl": "application/vnd.hp-pcl", + "pclxl": "application/vnd.hp-pclxl", + "pct": "image/x-pict", + "pcurl": "application/vnd.curl.pcurl", + "pcx": "image/x-pcx", + "pdb": "application/x-pilot", + "pde": "text/x-processing", + "pdf": "application/pdf", + "pef": "image/x-pentax-pef", + "pem": "application/x-x509-ca-cert", + "pfa": "application/x-font-type1", + "pfb": "application/x-font-type1", + "pfm": "application/x-font-type1", + "pfr": "application/font-tdpfr", + "pfx": "application/x-pkcs12", + "pgm": "image/x-portable-graymap", + "pgn": "application/x-chess-pgn", + "pgp": "application/pgp-encrypted", + "php": "application/x-httpd-php", + "pic": "image/x-pict", + "pkg": "application/octet-stream", + "pki": "application/pkixcmp", + "pkipath": "application/pkix-pkipath", + "pkpass": "application/vnd.apple.pkpass", + "pl": "application/x-perl", + "plb": "application/vnd.3gpp.pic-bw-large", + "plc": "application/vnd.mobius.plc", + "plf": "application/vnd.pocketlearn", + "pls": "application/pls+xml", + "pm": "application/x-perl", + "pml": "application/vnd.ctc-posml", + "png": "image/png", + "pnm": "image/x-portable-anymap", + "portpkg": "application/vnd.macports.portpkg", + "pot": "application/vnd.ms-powerpoint", + "potm": "application/vnd.ms-powerpoint.template.macroenabled.12", + "potx": "application/vnd.openxmlformats-officedocument.presentationml.template", + "ppam": "application/vnd.ms-powerpoint.addin.macroenabled.12", + "ppd": "application/vnd.cups-ppd", + "ppm": "image/x-portable-pixmap", + "pps": "application/vnd.ms-powerpoint", + "ppsm": "application/vnd.ms-powerpoint.slideshow.macroenabled.12", + "ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow", + "ppt": "application/vnd.ms-powerpoint", + "pptm": "application/vnd.ms-powerpoint.presentation.macroenabled.12", + "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "pqa": "application/vnd.palm", + "prc": "application/x-pilot", + "pre": "application/vnd.lotus-freelance", + "prf": "application/pics-rules", + "ps": "application/postscript", + "psb": "application/vnd.3gpp.pic-bw-small", + "psd": "image/vnd.adobe.photoshop", + "psf": "application/x-font-linux-psf", + "pskcxml": "application/pskc+xml", + "pti": "image/prs.pti", + "ptid": "application/vnd.pvi.ptid1", + "pub": "application/x-mspublisher", + "pvb": "application/vnd.3gpp.pic-bw-var", + "pwn": "application/vnd.3m.post-it-notes", + "pya": "audio/vnd.ms-playready.media.pya", + "pyv": "video/vnd.ms-playready.media.pyv", + "qam": "application/vnd.epson.quickanime", + "qbo": "application/vnd.intu.qbo", + "qfx": "application/vnd.intu.qfx", + "qps": "application/vnd.publishare-delta-tree", + "qt": "video/quicktime", + "qwd": "application/vnd.quark.quarkxpress", + "qwt": "application/vnd.quark.quarkxpress", + "qxb": "application/vnd.quark.quarkxpress", + "qxd": "application/vnd.quark.quarkxpress", + "qxl": "application/vnd.quark.quarkxpress", + "qxt": "application/vnd.quark.quarkxpress", + "ra": "audio/x-realaudio", + "raf": "image/x-fuji-raf", + "ram": "audio/x-pn-realaudio", + "raml": "application/raml+yaml", + "rar": "application/x-rar-compressed", + "ras": "image/x-cmu-raster", + "raw": "image/x-panasonic-raw", + "rcprofile": "application/vnd.ipunplugged.rcprofile", + "rdf": "application/rdf+xml", + "rdz": "application/vnd.data-vision.rdz", + "rep": "application/vnd.businessobjects", + "res": "application/x-dtbresource+xml", + "rgb": "image/x-rgb", + "rif": "application/reginfo+xml", + "rip": "audio/vnd.rip", + "ris": "application/x-research-info-systems", + "rl": "application/resource-lists+xml", + "rlc": "image/vnd.fujixerox.edmics-rlc", + "rld": "application/resource-lists-diff+xml", + "rm": "application/vnd.rn-realmedia", + "rmi": "audio/midi", + "rmp": "audio/x-pn-realaudio-plugin", + "rms": "application/vnd.jcp.javame.midlet-rms", + "rmvb": "application/vnd.rn-realmedia-vbr", + "rnc": "application/relax-ng-compact-syntax", + "rng": "application/xml", + "roa": "application/rpki-roa", + "roff": "text/troff", + "rp9": "application/vnd.cloanto.rp9", + "rpm": "application/x-redhat-package-manager", + "rpss": "application/vnd.nokia.radio-presets", + "rpst": "application/vnd.nokia.radio-preset", + "rq": "application/sparql-query", + "rs": "application/rls-services+xml", + "rsd": "application/rsd+xml", + "rss": "application/rss+xml", + "rtf": "text/rtf", + "rtx": "text/richtext", + "run": "application/x-makeself", + "s": "text/x-asm", + "s3m": "audio/s3m", + "saf": "application/vnd.yamaha.smaf-audio", + "sass": "text/x-sass", + "sbml": "application/sbml+xml", + "sc": "application/vnd.ibm.secure-container", + "scd": "application/x-msschedule", + "scm": "application/vnd.lotus-screencam", + "scq": "application/scvp-cv-request", + "scs": "application/scvp-cv-response", + "scss": "text/x-scss", + "scurl": "text/vnd.curl.scurl", + "sda": "application/vnd.stardivision.draw", + "sdc": "application/vnd.stardivision.calc", + "sdd": "application/vnd.stardivision.impress", + "sdkd": "application/vnd.solent.sdkm+xml", + "sdkm": "application/vnd.solent.sdkm+xml", + "sdp": "application/sdp", + "sdw": "application/vnd.stardivision.writer", + "sea": "application/x-sea", + "see": "application/vnd.seemail", + "seed": "application/vnd.fdsn.seed", + "sema": "application/vnd.sema", + "semd": "application/vnd.semd", + "semf": "application/vnd.semf", + "ser": "application/java-serialized-object", + "setpay": "application/set-payment-initiation", + "setreg": "application/set-registration-initiation", + "sfd-hdstx": "application/vnd.hydrostatix.sof-data", + "sfs": "application/vnd.spotfire.sfs", + "sfv": "text/x-sfv", + "sgi": "image/sgi", + "sgl": "application/vnd.stardivision.writer-global", + "sgm": "text/sgml", + "sgml": "text/sgml", + "sh": "application/x-sh", + "shar": "application/x-shar", + "shex": "text/shex", + "shf": "application/shf+xml", + "shtml": "text/html", + "sid": "image/x-mrsid-image", + "sig": "application/pgp-signature", + "sil": "audio/silk", + "silo": "model/mesh", + "sis": "application/vnd.symbian.install", + "sisx": "application/vnd.symbian.install", + "sit": "application/x-stuffit", + "sitx": "application/x-stuffitx", + "skd": "application/vnd.koan", + "skm": "application/vnd.koan", + "skp": "application/vnd.koan", + "skt": "application/vnd.koan", + "sldm": "application/vnd.ms-powerpoint.slide.macroenabled.12", + "sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide", + "slim": "text/slim", + "slm": "text/slim", + "slt": "application/vnd.epson.salt", + "sm": "application/vnd.stepmania.stepchart", + "smf": "application/vnd.stardivision.math", + "smi": "application/smil+xml", + "smil": "application/smil+xml", + "smv": "video/x-smv", + "smzip": "application/vnd.stepmania.package", + "snd": "audio/basic", + "snf": "application/x-font-snf", + "so": "application/octet-stream", + "spc": "application/x-pkcs7-certificates", + "spf": "application/vnd.yamaha.smaf-phrase", + "spl": "application/x-futuresplash", + "spot": "text/vnd.in3d.spot", + "spp": "application/scvp-vp-response", + "spq": "application/scvp-vp-request", + "spx": "audio/ogg", + "sql": "application/x-sql", + "sr2": "image/x-sony-sr2", + "src": "application/x-wais-source", + "srf": "image/x-sony-srf", + "srt": "application/x-subrip", + "sru": "application/sru+xml", + "srx": "application/sparql-results+xml", + "ssdl": "application/ssdl+xml", + "sse": "application/vnd.kodak-descriptor", + "ssf": "application/vnd.epson.ssf", + "ssml": "application/ssml+xml", + "st": "application/vnd.sailingtracker.track", + "stc": "application/vnd.sun.xml.calc.template", + "std": "application/vnd.sun.xml.draw.template", + "stf": "application/vnd.wt.stf", + "sti": "application/vnd.sun.xml.impress.template", + "stk": "application/hyperstudio", + "stl": "application/vnd.ms-pki.stl", + "str": "application/vnd.pg.format", + "stw": "application/vnd.sun.xml.writer.template", + "styl": "text/stylus", + "stylus": "text/stylus", + "sub": "text/vnd.dvb.subtitle", + "sus": "application/vnd.sus-calendar", + "susp": "application/vnd.sus-calendar", + "sv4cpio": "application/x-sv4cpio", + "sv4crc": "application/x-sv4crc", + "svc": "application/vnd.dvb.service", + "svd": "application/vnd.svd", + "svg": "image/svg+xml", + "svgz": "image/svg+xml", + "swa": "application/x-director", + "swf": "application/x-shockwave-flash", + "swi": "application/vnd.aristanetworks.swi", + "sxc": "application/vnd.sun.xml.calc", + "sxd": "application/vnd.sun.xml.draw", + "sxg": "application/vnd.sun.xml.writer.global", + "sxi": "application/vnd.sun.xml.impress", + "sxm": "application/vnd.sun.xml.math", + "sxw": "application/vnd.sun.xml.writer", + "t": "text/troff", + "t3": "application/x-t3vm-image", + "t38": "image/t38", + "taglet": "application/vnd.mynfc", + "tao": "application/vnd.tao.intent-module-archive", + "tap": "image/vnd.tencent.tap", + "tar": "application/x-tar", + "tcap": "application/vnd.3gpp2.tcap", + "tcl": "application/x-tcl", + "teacher": "application/vnd.smart.teacher", + "tei": "application/tei+xml", + "teicorpus": "application/tei+xml", + "tex": "application/x-tex", + "texi": "application/x-texinfo", + "texinfo": "application/x-texinfo", + "text": "text/plain", + "tfi": "application/thraud+xml", + "tfm": "application/x-tex-tfm", + "tfx": "image/tiff-fx", + "tga": "image/x-tga", + "thmx": "application/vnd.ms-officetheme", + "tif": "image/tiff", + "tiff": "image/tiff", + "tk": "application/x-tcl", + "tmo": "application/vnd.tmobile-livetv", + "torrent": "application/x-bittorrent", + "tpl": "application/vnd.groove-tool-template", + "tpt": "application/vnd.trid.tpt", + "tr": "text/troff", + "tra": "application/vnd.trueapp", + "trm": "application/x-msterminal", + "ts": "video/mp2t", + "tsd": "application/timestamped-data", + "tsv": "text/tab-separated-values", + "ttc": "font/collection", + "ttf": "font/ttf", + "ttl": "text/turtle", + "twd": "application/vnd.simtech-mindmapper", + "twds": "application/vnd.simtech-mindmapper", + "txd": "application/vnd.genomatix.tuxedo", + "txf": "application/vnd.mobius.txf", + "txt": "text/plain", + "u32": "application/x-authorware-bin", + "u8dsn": "message/global-delivery-status", + "u8hdr": "message/global-headers", + "u8mdn": "message/global-disposition-notification", + "u8msg": "message/global", + "udeb": "application/x-debian-package", + "ufd": "application/vnd.ufdl", + "ufdl": "application/vnd.ufdl", + "ulx": "application/x-glulx", + "umj": "application/vnd.umajin", + "unityweb": "application/vnd.unity", + "uoml": "application/vnd.uoml+xml", + "uri": "text/uri-list", + "uris": "text/uri-list", + "urls": "text/uri-list", + "ustar": "application/x-ustar", + "utz": "application/vnd.uiq.theme", + "uu": "text/x-uuencode", + "uva": "audio/vnd.dece.audio", + "uvd": "application/vnd.dece.data", + "uvf": "application/vnd.dece.data", + "uvg": "image/vnd.dece.graphic", + "uvh": "video/vnd.dece.hd", + "uvi": "image/vnd.dece.graphic", + "uvm": "video/vnd.dece.mobile", + "uvp": "video/vnd.dece.pd", + "uvs": "video/vnd.dece.sd", + "uvt": "application/vnd.dece.ttml+xml", + "uvu": "video/vnd.uvvu.mp4", + "uvv": "video/vnd.dece.video", + "uvva": "audio/vnd.dece.audio", + "uvvd": "application/vnd.dece.data", + "uvvf": "application/vnd.dece.data", + "uvvg": "image/vnd.dece.graphic", + "uvvh": "video/vnd.dece.hd", + "uvvi": "image/vnd.dece.graphic", + "uvvm": "video/vnd.dece.mobile", + "uvvp": "video/vnd.dece.pd", + "uvvs": "video/vnd.dece.sd", + "uvvt": "application/vnd.dece.ttml+xml", + "uvvu": "video/vnd.uvvu.mp4", + "uvvv": "video/vnd.dece.video", + "uvvx": "application/vnd.dece.unspecified", + "uvvz": "application/vnd.dece.zip", + "uvx": "application/vnd.dece.unspecified", + "uvz": "application/vnd.dece.zip", + "vbox": "application/x-virtualbox-vbox", + "vbox-extpack": "application/x-virtualbox-vbox-extpack", + "vcard": "text/vcard", + "vcd": "application/x-cdlink", + "vcf": "text/x-vcard", + "vcg": "application/vnd.groove-vcard", + "vcs": "text/x-vcalendar", + "vcx": "application/vnd.vcx", + "vdi": "application/x-virtualbox-vdi", + "vhd": "application/x-virtualbox-vhd", + "vis": "application/vnd.visionary", + "viv": "video/vnd.vivo", + "vmdk": "application/x-virtualbox-vmdk", + "vob": "video/x-ms-vob", + "vor": "application/vnd.stardivision.writer", + "vox": "application/x-authorware-bin", + "vrml": "model/vrml", + "vsd": "application/vnd.visio", + "vsf": "application/vnd.vsf", + "vss": "application/vnd.visio", + "vst": "application/vnd.visio", + "vsw": "application/vnd.visio", + "vtf": "image/vnd.valve.source.texture", + "vtt": "text/vtt", + "vtu": "model/vnd.vtu", + "vxml": "application/voicexml+xml", + "w3d": "application/x-director", + "wad": "application/x-doom", + "wadl": "application/vnd.sun.wadl+xml", + "war": "application/java-archive", + "wasm": "application/wasm", + "wav": "audio/x-wav", + "wax": "audio/x-ms-wax", + "wbmp": "image/vnd.wap.wbmp", + "wbs": "application/vnd.criticaltools.wbs+xml", + "wbxml": "application/vnd.wap.wbxml", + "wcm": "application/vnd.ms-works", + "wdb": "application/vnd.ms-works", + "wdp": "image/vnd.ms-photo", + "weba": "audio/webm", + "webapp": "application/x-web-app-manifest+json", + "webm": "video/webm", + "webmanifest": "application/manifest+json", + "webp": "image/webp", + "wg": "application/vnd.pmi.widget", + "wgt": "application/widget", + "wks": "application/vnd.ms-works", + "wm": "video/x-ms-wm", + "wma": "audio/x-ms-wma", + "wmd": "application/x-ms-wmd", + "wmf": "image/wmf", + "wml": "text/vnd.wap.wml", + "wmlc": "application/vnd.wap.wmlc", + "wmls": "text/vnd.wap.wmlscript", + "wmlsc": "application/vnd.wap.wmlscriptc", + "wmv": "video/x-ms-wmv", + "wmx": "video/x-ms-wmx", + "wmz": "application/x-msmetafile", + "woff": "font/woff", + "woff2": "font/woff2", + "wpd": "application/vnd.wordperfect", + "wpl": "application/vnd.ms-wpl", + "wps": "application/vnd.ms-works", + "wqd": "application/vnd.wqd", + "wri": "application/x-mswrite", + "wrl": "model/vrml", + "wsc": "message/vnd.wfa.wsc", + "wsdl": "application/wsdl+xml", + "wspolicy": "application/wspolicy+xml", + "wtb": "application/vnd.webturbo", + "wvx": "video/x-ms-wvx", + "x32": "application/x-authorware-bin", + "x3d": "model/x3d+xml", + "x3db": "model/x3d+binary", + "x3dbz": "model/x3d+binary", + "x3dv": "model/x3d+vrml", + "x3dvz": "model/x3d+vrml", + "x3dz": "model/x3d+xml", + "x3f": "image/x-sigma-x3f", + "xaml": "application/xaml+xml", + "xap": "application/x-silverlight-app", + "xar": "application/vnd.xara", + "xbap": "application/x-ms-xbap", + "xbd": "application/vnd.fujixerox.docuworks.binder", + "xbm": "image/x-xbitmap", + "xdf": "application/xcap-diff+xml", + "xdm": "application/vnd.syncml.dm+xml", + "xdp": "application/vnd.adobe.xdp+xml", + "xdssc": "application/dssc+xml", + "xdw": "application/vnd.fujixerox.docuworks", + "xenc": "application/xenc+xml", + "xer": "application/patch-ops-error+xml", + "xfdf": "application/vnd.adobe.xfdf", + "xfdl": "application/vnd.xfdl", + "xht": "application/xhtml+xml", + "xhtml": "application/xhtml+xml", + "xhvml": "application/xv+xml", + "xif": "image/vnd.xiff", + "xla": "application/vnd.ms-excel", + "xlam": "application/vnd.ms-excel.addin.macroenabled.12", + "xlc": "application/vnd.ms-excel", + "xlf": "application/x-xliff+xml", + "xlm": "application/vnd.ms-excel", + "xls": "application/vnd.ms-excel", + "xlsb": "application/vnd.ms-excel.sheet.binary.macroenabled.12", + "xlsm": "application/vnd.ms-excel.sheet.macroenabled.12", + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "xlt": "application/vnd.ms-excel", + "xltm": "application/vnd.ms-excel.template.macroenabled.12", + "xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template", + "xlw": "application/vnd.ms-excel", + "xm": "audio/xm", + "xml": "text/xml", + "xo": "application/vnd.olpc-sugar", + "xop": "application/xop+xml", + "xpi": "application/x-xpinstall", + "xpl": "application/xproc+xml", + "xpm": "image/x-xpixmap", + "xpr": "application/vnd.is-xpr", + "xps": "application/vnd.ms-xpsdocument", + "xpw": "application/vnd.intercon.formnet", + "xpx": "application/vnd.intercon.formnet", + "xsd": "application/xml", + "xsl": "application/xml", + "xslt": "application/xslt+xml", + "xsm": "application/vnd.syncml+xml", + "xspf": "application/xspf+xml", + "xul": "application/vnd.mozilla.xul+xml", + "xvm": "application/xv+xml", + "xvml": "application/xv+xml", + "xwd": "image/x-xwindowdump", + "xyz": "chemical/x-xyz", + "xz": "application/x-xz", + "yaml": "text/yaml", + "yang": "application/yang", + "yin": "application/yin+xml", + "yml": "text/yaml", + "ymp": "text/x-suse-ymp", + "z1": "application/x-zmachine", + "z2": "application/x-zmachine", + "z3": "application/x-zmachine", + "z4": "application/x-zmachine", + "z5": "application/x-zmachine", + "z6": "application/x-zmachine", + "z7": "application/x-zmachine", + "z8": "application/x-zmachine", + "zaz": "application/vnd.zzazz.deck+xml", + "zip": "application/zip", + "zir": "application/vnd.zul", + "zirz": "application/vnd.zul", + "zmm": "application/vnd.handheld-entertainment+xml", +} + +// Type is mime-type/content-type of the given file ext +func Type(fileName string) string { + var ext string + idx := strings.LastIndex(fileName, ".") + if idx > -1 { + idx++ + ext = fileName[idx:] + } else { + ext = fileName + } + + contentType := mimeTypes[strings.ToLower(ext)] + return contentType +} diff --git a/open/darwin.go b/open/darwin.go new file mode 100644 index 0000000..72671a5 --- /dev/null +++ b/open/darwin.go @@ -0,0 +1,19 @@ +//go:build darwin + +// Copyright 2024 Patial Tech. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package open + +import ( + "os/exec" +) + +func open(input string) *exec.Cmd { + return exec.Command("open", input) +} + +func openWith(input string, appName string) *exec.Cmd { + return exec.Command("open", "-a", appName, input) +} diff --git a/open/linux.go b/open/linux.go new file mode 100644 index 0000000..803b77a --- /dev/null +++ b/open/linux.go @@ -0,0 +1,21 @@ +//go:build linux + +// Copyright 2024 Patial Tech. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package open + +import ( + "os/exec" +) + +// http://sources.debian.net/src/xdg-utils + +func open(input string) *exec.Cmd { + return exec.Command("xdg-open", input) +} + +func openWith(input string, appName string) *exec.Cmd { + return exec.Command(appName, input) +} diff --git a/open/open.go b/open/open.go new file mode 100644 index 0000000..69c9b35 --- /dev/null +++ b/open/open.go @@ -0,0 +1,16 @@ +// Copyright 2024 Patial Tech. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package open + +// WithDefaultApp open a file, directory, or URI using the OS's default application for that object type. +func WithDefaultApp(input string) error { + cmd := open(input) + return cmd.Run() +} + +// WithApp will open a file directory, or URI using the specified application. +func App(input string, appName string) error { + return openWith(input, appName).Run() +} diff --git a/open/windows.go b/open/windows.go new file mode 100644 index 0000000..dfdfb28 --- /dev/null +++ b/open/windows.go @@ -0,0 +1,36 @@ +//go:build windows + +// Copyright 2024 Patial Tech. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package open + +import ( + "os" + "os/exec" + "path/filepath" + "strings" +) + +var ( + cmd = "url.dll,FileProtocolHandler" + runDll32 = filepath.Join(os.Getenv("SYSTEMROOT"), "System32", "rundll32.exe") +) + +func cleaninput(input string) string { + r := strings.NewReplacer("&", "^&") + return r.Replace(input) +} + +func open(input string) *exec.Cmd { + cmd := exec.Command(runDll32, cmd, input) + // cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + return cmd +} + +func openWith(input string, appName string) *exec.Cmd { + cmd := exec.Command("cmd", "/C", "start", "", appName, cleaninput(input)) + // cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + return cmd +} diff --git a/ptr/ptr.go b/ptr/ptr.go new file mode 100644 index 0000000..57d15da --- /dev/null +++ b/ptr/ptr.go @@ -0,0 +1,52 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package ptr + +import "strings" + +func Bool(v bool) *bool { + return &v +} + +func GetBool(v *bool) bool { + if v == nil { + return false + } + return *v +} + +func Str(v string) *string { + return &v +} + +func NumStr(v *string) string { + if v == nil { + return "" + } + return *v +} + +func StrTrim(v *string) *string { + if v == nil { + return nil + } + + *v = strings.TrimSpace(*v) + return v +} + +type N interface { + uint8 | int8 | uint16 | int16 | uint | int | uint32 | int32 | uint64 | int64 | float32 | float64 +} + +func Number[T N](v T) *T { + return &v +} + +func GetNumber[T N](v *T) T { + if v == nil { + return 0 + } + return *v +} diff --git a/request/pager.go b/request/pager.go new file mode 100644 index 0000000..6be6116 --- /dev/null +++ b/request/pager.go @@ -0,0 +1,90 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package request + +import ( + "net/http" + "strconv" + "strings" + + "code.patial.tech/go/appcore/ptr" +) + +type Pager struct { + Search string + OrderBy *string `json:"orderBy"` + OrderAsc *bool `json:"orderAsc"` + Page int `json:"page"` + Size int `json:"size"` + Total int `json:"total"` + TotalNeeded bool `json:"-"` +} + +func (i *Pager) HasSearch() bool { + if i == nil { + return false + } + + return strings.TrimSpace(i.Search) != "" +} + +func (i *Pager) Offset() int { + if i == nil { + return 0 + } + + return (i.Page - 1) * i.Limit() +} + +func (i *Pager) Limit() int { + if i == nil || ptr.GetNumber(&i.Size) < 1 { + return 20 + } + + return i.Size +} + +// GetPager info from request's query parameters +func GetPager(r *http.Request) Pager { + p := Pager{ + Page: 1, + Size: 20, + OrderAsc: ptr.Bool(true), + } + + if v := r.URL.Query().Get("q"); v != "" { + p.Search = strings.TrimSpace(v) + } + + if v := r.URL.Query().Get("pg"); v != "" { + if vv, err := strconv.Atoi(v); err == nil { + p.Page = int(vv) + } + } + + if v := r.URL.Query().Get("pg_s"); v != "" { + if vv, err := strconv.Atoi(v); err == nil { + p.Size = int(vv) + } + } + + if v := r.URL.Query().Get("pg_ob"); v != "" { + p.OrderBy = &v + } + + if v := r.URL.Query().Get("pg_o"); v != "" { + switch strings.ToLower(v) { + case "asc": + p.OrderAsc = ptr.Bool(true) + case "desc": + p.OrderAsc = ptr.Bool(false) + } + } + + if v := r.URL.Query().Get("pg_t"); v == "n" { + p.TotalNeeded = true + } + + return p +} diff --git a/request/payload.go b/request/payload.go new file mode 100644 index 0000000..ebc265b --- /dev/null +++ b/request/payload.go @@ -0,0 +1,46 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package request + +import ( + "encoding/json" + "fmt" + "net/http" + + "code.patial.tech/go/appcore/validate" +) + +func FormField(r *http.Request, key string) (string, error) { + f, err := Payload[map[string]any](r) + if err != nil { + return "", err + } + + return fmt.Sprintf("%v", f[key]), nil +} + +func PayloadMap(r *http.Request) (map[string]any, error) { + return Payload[map[string]any](r) +} + +func PayloadWithValidate[T any](r *http.Request) (T, error) { + p, err := Payload[T](r) + if err != nil { + return p, err + } + + if err := validate.Struct(p); err != nil { + return p, err + } + + return p, nil +} + +func Payload[T any](r *http.Request) (T, error) { + var p T + if err := json.NewDecoder(r.Body).Decode(&p); err != nil { + return p, err + } + return p, nil +} diff --git a/request/query.go b/request/query.go new file mode 100644 index 0000000..b1b554f --- /dev/null +++ b/request/query.go @@ -0,0 +1,42 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package request + +import ( + "fmt" + "net/http" + "reflect" + "strconv" +) + +type Number interface { + int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64 +} + +// NumberParam from request query string +func NumberParam[T Number](r *http.Request, key string) (T, error) { + var noop T + if !r.URL.Query().Has(key) { + return noop, fmt.Errorf("query param: %q is missing", key) + } + + p := r.URL.Query().Get(key) + t := reflect.TypeOf(noop) + k := t.Kind() + // float param + if k == reflect.Float32 || k == reflect.Float64 { + n, err := strconv.ParseFloat(p, 64) + if err != nil { + return noop, fmt.Errorf("query param: %q is not a valid float", key) + } + return T(n), nil + } + + // int param + n, err := strconv.ParseInt(p, 10, 64) + if err != nil { + return noop, fmt.Errorf("query param: %q is not a valid integer", key) + } + return T(n), nil +} diff --git a/response/reply.go b/response/reply.go new file mode 100644 index 0000000..b5775f1 --- /dev/null +++ b/response/reply.go @@ -0,0 +1,91 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package response + +import ( + "encoding/json" + "fmt" + "net/http" + + "code.patial.tech/go/appcore/request" +) + +// Detail of api response +type Detail struct { + // Data of api response + // + // it will nil in case of error + Data any `json:"data"` + + // Error if any occurred during api call + Error *string `json:"error,omitempty"` + + // Pager is used for paged data response + Pager *request.Pager `json:"pager,omitempty"` +} + +// Done data response +func Ok(w http.ResponseWriter, data any) { + reply(w, data, nil) +} + +// Paged data response +func Paged(w http.ResponseWriter, data any, p request.Pager) { + reply(w, data, &p) +} + +func reply(w http.ResponseWriter, data any, p *request.Pager) { + w.Header().Set("Content-Type", "application/json") + // Requires the client to validate the response with the server before using the cached version, + // ensuring data freshness. + w.Header().Set("Cache-Control", "no-cache") + // older HTTP header used for controlling caching behavior in HTTP/1.0, + // primarily for backwards compatibility with older browsers and caches + w.Header().Set("Pragma", "no-cache") + + // if data is nil, let's pass it on as null + if data == nil { + w.WriteHeader(http.StatusOK) + w.Write([]byte("{\"data\":null}")) + return + } + + // json data... + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(Detail{ + Data: data, + Pager: p, + }) +} + +func BadRequest(w http.ResponseWriter, err error) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + w.Write(fmt.Appendf(nil, "{\"error\": %q}", err.Error())) +} + +func InternalServerError(w http.ResponseWriter, err error) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + w.Write(fmt.Appendf(nil, "{\"error\": %q}", err.Error())) +} + +func SessionExpired(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("{\"error\": \"Session is expired, please login again\"}")) +} + +func NotAutorized(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("{\"error\": \"You are not authorized to perform this action\"}")) +} + +// Forbidden response error +func Forbidden(w http.ResponseWriter, err error) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + w.Write(fmt.Appendf(nil, "{\"error\": %q}", err.Error())) +} diff --git a/structs/structs.go b/structs/structs.go new file mode 100644 index 0000000..fcbf989 --- /dev/null +++ b/structs/structs.go @@ -0,0 +1,34 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package structs + +import ( + "reflect" +) + +func Map(obj any) map[string]any { + result := make(map[string]any) + val := reflect.ValueOf(obj) + if val.Kind() == reflect.Ptr { + val = val.Elem() + } + + typ := val.Type() + + for i := range val.NumField() { + fieldName := typ.Field(i).Name + fieldValueKind := val.Field(i).Kind() + var fieldValue any + + if fieldValueKind == reflect.Struct { + fieldValue = Map(val.Field(i).Interface()) + } else { + fieldValue = val.Field(i).Interface() + } + + result[fieldName] = fieldValue + } + + return result +} diff --git a/uid/sqid.go b/uid/sqid.go new file mode 100644 index 0000000..026c3af --- /dev/null +++ b/uid/sqid.go @@ -0,0 +1,30 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package uid + +import "github.com/sqids/sqids-go" + +type Service interface { + SquiOptions() sqids.Options +} + +// Encode a slice of IDs into one unique ID +func Encode(svc Service, ids ...uint64) (string, error) { + s, err := sqids.New(svc.SquiOptions()) + if err != nil { + return "", err + } + + return s.Encode(ids) // "86Rf07" +} + +// Decode an ID back to slice of IDs +func Decode(svc Service, id string) ([]uint64, error) { + s, err := sqids.New(svc.SquiOptions()) + if err != nil { + return nil, err + } + + return s.Decode(id), nil +} diff --git a/uid/uuid.go b/uid/uuid.go new file mode 100644 index 0000000..f657248 --- /dev/null +++ b/uid/uuid.go @@ -0,0 +1,16 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package uid + +import ( + "github.com/google/uuid" +) + +func NewUUID() (string, error) { + id, err := uuid.NewV7() + if err != nil { + return "", err + } + return id.String(), nil +} diff --git a/validate/validate.go b/validate/validate.go new file mode 100644 index 0000000..4e1f112 --- /dev/null +++ b/validate/validate.go @@ -0,0 +1,29 @@ +// Copyright 2024 Patial Tech (Ankit Patial). +// All rights reserved. + +package validate + +import ( + "reflect" + "strings" + + "github.com/go-playground/validator/v10" +) + +var validate *validator.Validate + +func init() { + validate = validator.New() + // register function to get tag name from json tags. + validate.RegisterTagNameFunc(func(fld reflect.StructField) string { + name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] + if name == "-" { + return "" + } + return name + }) +} + +func Struct(s any) error { + return validate.Struct(s) +}