diff --git a/web-framework/go/gin/src/.gitignore b/web-framework/go/gin/src/.gitignore new file mode 100644 index 000000000..b5ff4240c --- /dev/null +++ b/web-framework/go/gin/src/.gitignore @@ -0,0 +1,144 @@ +# Created by https://www.toptal.com/developers/gitignore/api/goland,go +# Edit at https://www.toptal.com/developers/gitignore?templates=goland,go + +### Go ### +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ +# Go workspace file +go.work + +### GoLand ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### GoLand Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +# End of https://www.toptal.com/developers/gitignore/api/goland,go +myapp/vendor/ +myapp/bin/ +myapp/main +/myapp/main +/myapp/vendor/ diff --git a/web-framework/go/gin/src/LICENSE b/web-framework/go/gin/src/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/web-framework/go/gin/src/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 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. + + + Copyright (C) + + 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: + + Copyright (C) + 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 +. diff --git a/web-framework/go/gin/src/cd.yaml b/web-framework/go/gin/src/cd.yaml new file mode 100644 index 000000000..a68c55392 --- /dev/null +++ b/web-framework/go/gin/src/cd.yaml @@ -0,0 +1,68 @@ +kind: Pipeline +# 流水线名称,需要全局唯一 +name: p-<%.appName%>-<%.releaseVersion%> +spec: + context: + data: + dingdingNotification: + enable: false + skipOnSuccess: false + message: + at: + isAtAll: false + atMobiles: [] + atUserIds: [] + text: {} + msgtype: text + templateSpec: + tasks: + - context: + data: + enable: true + steps: + # 配置s工具 + - plugin: '@serverless-cd/s-setup' + # 从git或模板仓库拉取代码 + - plugin: '@serverless-cd/checkout' + # 预览配置变更 + - run: s plan -t s.yaml --debug + name: pre-check + runAfters: [] + taskTemplate: serverless-runner-task + - context: + data: + # 如果是测试环境不需要部署确认,可以改为false + enable: false + name: pre-check-approval + runAfters: + - name: pre-check + taskTemplate: need-approval + - context: + data: + enable: true + steps: + - plugin: '@serverless-cd/s-setup' + - plugin: '@serverless-cd/checkout' + # 设置构建工具版本,查看文档:https://help.aliyun.com/zh/functioncompute/user-guide/use-the-runtime-setup-plug-in-to-initialize-a-runtime + - plugin: "@serverless-cd/runtime-setup" + inputs: + runtime: + - go1.18 + - run: go version + # 设置依赖缓存 + - plugin: "@serverless-cd/cache" + inputs: + # 缓存的key,相同key的缓存会被共享并更新。 + # 在Bucket中缓存路径为cache-home/cache-<% .appName %> + key: "cache-<% .appName %>" + # 按照当前构建的工具要求,配置缓存的路径 + # gomod场景这里是$GOPATH/pkg/mod,详情查看:https://help.aliyun.com/zh/functioncompute/user-guide/use-the-oss-cache-plug-in-to-accelerate-dependency-building + path: $GOPATH/pkg/mod + # 执行构建命令 + - run: cd ./myapp && bash build.sh + # 执行构建部署 + - plugin: '@serverless-cd/s-deploy' + name: build-and-deploy + runAfters: + - name: pre-check-approval + taskTemplate: serverless-runner-task \ No newline at end of file diff --git a/web-framework/go/gin/src/code/go.mod b/web-framework/go/gin/src/code/go.mod deleted file mode 100644 index 24d0beb4d..000000000 --- a/web-framework/go/gin/src/code/go.mod +++ /dev/null @@ -1,26 +0,0 @@ -module example.com/m - -go 1.18 - -require github.com/gin-gonic/gin v1.8.2 - -require ( - github.com/gin-contrib/sse v0.1.0 // indirect - github.com/go-playground/locales v0.14.0 // indirect - github.com/go-playground/universal-translator v0.18.0 // indirect - github.com/go-playground/validator/v10 v10.11.1 // indirect - github.com/goccy/go-json v0.9.11 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/leodido/go-urn v1.2.1 // indirect - github.com/mattn/go-isatty v0.0.16 // indirect - github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect - github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/pelletier/go-toml/v2 v2.0.6 // indirect - github.com/ugorji/go/codec v1.2.7 // indirect - golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect - golang.org/x/net v0.4.0 // indirect - golang.org/x/sys v0.3.0 // indirect - golang.org/x/text v0.5.0 // indirect - google.golang.org/protobuf v1.28.1 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect -) diff --git a/web-framework/go/gin/src/code/go.sum b/web-framework/go/gin/src/code/go.sum deleted file mode 100644 index 7aee98dfc..000000000 --- a/web-framework/go/gin/src/code/go.sum +++ /dev/null @@ -1,95 +0,0 @@ -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -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/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= -github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/gin-gonic/gin v1.8.2 h1:UzKToD9/PoFj/V4rvlKqTRKnQYyz8Sc1MJlv4JHPtvY= -github.com/gin-gonic/gin v1.8.2/go.mod h1:qw5AYuDrzRTnhvusDsrov+fDIxp9Dleuu12h8nfB398= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU= -github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs= -github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho= -github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA= -github.com/go-playground/validator/v10 v10.11.1 h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ= -github.com/go-playground/validator/v10 v10.11.1/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU= -github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk= -github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= -github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= -github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= -github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= -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/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= -github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M= -github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0= -github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY= -golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 h1:0es+/5331RGQPcXlMfP+WrnIIS6dNnNRe0WB02W0F4M= -golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.4.0 h1:Q5QPcMlvfxFTAPV0+07Xz/MpK9NTXu2VDUuy0FeMfaU= -golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ= -golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM= -golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= -google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -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/web-framework/go/gin/src/code/main.go b/web-framework/go/gin/src/code/main.go deleted file mode 100644 index f9c316121..000000000 --- a/web-framework/go/gin/src/code/main.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - r.GET("/ping", func(c *gin.Context) { - c.JSON(200, gin.H{ - "message": "pong", - }) - }) - r.GET("/", func(c *gin.Context) { - c.JSON(200, gin.H{ - "message": "hello world", - }) - }) - // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") - r.Run() -} diff --git a/web-framework/go/gin/src/myapp/.fcignore b/web-framework/go/gin/src/myapp/.fcignore new file mode 100644 index 000000000..87d0d625e --- /dev/null +++ b/web-framework/go/gin/src/myapp/.fcignore @@ -0,0 +1,9 @@ +build.sh +go.mod +go.sum +main.go +vendor/ +src/ +pkg/ +bin/ +.fcignore \ No newline at end of file diff --git a/web-framework/go/gin/src/myapp/assets/css/style.css b/web-framework/go/gin/src/myapp/assets/css/style.css new file mode 100644 index 000000000..b085936ca --- /dev/null +++ b/web-framework/go/gin/src/myapp/assets/css/style.css @@ -0,0 +1,7 @@ +body { + font-family: Arial, sans-serif; +} + +h1 { + color: #333; +} \ No newline at end of file diff --git a/web-framework/go/gin/src/myapp/build.sh b/web-framework/go/gin/src/myapp/build.sh new file mode 100644 index 000000000..dbd002dfe --- /dev/null +++ b/web-framework/go/gin/src/myapp/build.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -e +go mod tidy +rm -f main +GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main main.go \ No newline at end of file diff --git a/web-framework/go/gin/src/myapp/go.mod b/web-framework/go/gin/src/myapp/go.mod new file mode 100644 index 000000000..5b133321d --- /dev/null +++ b/web-framework/go/gin/src/myapp/go.mod @@ -0,0 +1,41 @@ +module myapp + +go 1.18 + +require ( + github.com/aliyun/aliyun-oss-go-sdk v2.2.6+incompatible + github.com/gin-gonic/gin v1.10.0 + github.com/google/uuid v1.6.0 + github.com/pkg/errors v0.9.1 + github.com/sirupsen/logrus v1.9.3 +) + +require ( + github.com/bytedance/sonic v1.11.8 // indirect + github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.4 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.21.0 // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.8.0 // indirect + golang.org/x/crypto v0.23.0 // indirect + golang.org/x/net v0.25.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + golang.org/x/time v0.5.0 // indirect + google.golang.org/protobuf v1.34.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/web-framework/go/gin/src/myapp/go.sum b/web-framework/go/gin/src/myapp/go.sum new file mode 100644 index 000000000..a209bdb3c --- /dev/null +++ b/web-framework/go/gin/src/myapp/go.sum @@ -0,0 +1,97 @@ +github.com/aliyun/aliyun-oss-go-sdk v2.2.6+incompatible h1:KXeJoM1wo9I/6xPTyt6qCxoSZnmASiAjlrr0dyTUKt8= +github.com/aliyun/aliyun-oss-go-sdk v2.2.6+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= +github.com/bytedance/sonic v1.11.8 h1:Zw/j1KfiS+OYTi9lyB3bb0CFxPJVkM17k1wyDG32LRA= +github.com/bytedance/sonic v1.11.8/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +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.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I= +github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +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.21.0 h1:4fZA11ovvtkdgaeev9RGWPgc1uj3H8W+rNYyH/ySBb0= +github.com/go-playground/validator/v10 v10.21.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +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/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +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/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +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/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= +golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/web-framework/go/gin/src/myapp/main.go b/web-framework/go/gin/src/myapp/main.go new file mode 100644 index 000000000..53e7ce768 --- /dev/null +++ b/web-framework/go/gin/src/myapp/main.go @@ -0,0 +1,25 @@ +package main + +import ( + "github.com/gin-gonic/gin" + + "myapp/pkg/logging" + "myapp/src/routes" +) + +func main() { + router := gin.Default() + router.Use(logging.RequestIDMiddleware()) + + // 设置静态文件路径 + router.Static("/assets", "./assets") + + // 加载视图文件 + router.LoadHTMLGlob("views/*") + + // 初始化路由 + routes.InitRoutes(router) + + // 运行服务器 + router.Run(":8080") // 监听并在 0.0.0.0:8080 上启动服务 +} diff --git a/web-framework/go/gin/src/myapp/pkg/constant/system.go b/web-framework/go/gin/src/myapp/pkg/constant/system.go new file mode 100644 index 000000000..73d520d76 --- /dev/null +++ b/web-framework/go/gin/src/myapp/pkg/constant/system.go @@ -0,0 +1,9 @@ +package constant + +const ( + RequestID = "RequestID" + FC_REGION = "FC_REGION" + ALIBABA_CLOUD_ACCESS_KEY_ID = "ALIBABA_CLOUD_ACCESS_KEY_ID" + ALIBABA_CLOUD_ACCESS_KEY_SECRET = "ALIBABA_CLOUD_ACCESS_KEY_SECRET" + ALIBABA_CLOUD_SECURITY_TOKEN = "ALIBABA_CLOUD_SECURITY_TOKEN" +) diff --git a/web-framework/go/gin/src/myapp/pkg/logging/config.go b/web-framework/go/gin/src/myapp/pkg/logging/config.go new file mode 100644 index 000000000..5187df53a --- /dev/null +++ b/web-framework/go/gin/src/myapp/pkg/logging/config.go @@ -0,0 +1,43 @@ +package logging + +import ( + "fmt" + "os" + "time" + + "github.com/sirupsen/logrus" + + "myapp/pkg/constant" +) + +type customFormatter struct{} + +func (f *customFormatter) Format(entry *logrus.Entry) ([]byte, error) { + timestamp := entry.Time.Format(time.RFC3339) + message := entry.Message + level := entry.Level.String() + requestID, ok := entry.Data[constant.RequestID] + if !ok { + requestID, ok = entry.Context.Value(constant.RequestID).(string) + if !ok { + requestID = "" + } + } + + // 注意:获取调用者的代码路径需开启logrus的ReportCaller,这会有性能开销 + caller := "unknown" + if entry.HasCaller() { + caller = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) + } + + log := fmt.Sprintf("%s - %s - %s - %s: %s\n", timestamp, requestID, level, caller, message) + return []byte(log), nil +} + +func init() { + formatter := &customFormatter{} + logrus.SetFormatter(formatter) + logrus.SetReportCaller(true) + logrus.SetLevel(logrus.InfoLevel) + logrus.SetOutput(os.Stdout) +} diff --git a/web-framework/go/gin/src/myapp/pkg/logging/logging_middleware.go b/web-framework/go/gin/src/myapp/pkg/logging/logging_middleware.go new file mode 100644 index 000000000..a3b8c5ae7 --- /dev/null +++ b/web-framework/go/gin/src/myapp/pkg/logging/logging_middleware.go @@ -0,0 +1,24 @@ +package logging + +import ( + "strings" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "myapp/pkg/constant" +) + +func RequestIDMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + requestID := c.GetHeader("X-Fc-Request-Id") + if requestID == "" { + // 随机生成request-id,这里使用简单的示例,建议使用更复杂的生成方式 + requestID = strings.ToLower(uuid.New().String()) + } + // 将request-id设置到Gin的Context中,方便后续的handler获取 + c.Set(constant.RequestID, requestID) + c.Header("X-Fc-Request-Id", requestID) + c.Next() + } +} diff --git a/web-framework/go/gin/src/myapp/pkg/services/oss.go b/web-framework/go/gin/src/myapp/pkg/services/oss.go new file mode 100644 index 000000000..971bea0f6 --- /dev/null +++ b/web-framework/go/gin/src/myapp/pkg/services/oss.go @@ -0,0 +1,39 @@ +package services + +import ( + "os" + + "github.com/aliyun/aliyun-oss-go-sdk/oss" + + "myapp/pkg/constant" +) + +type OssService struct { + ossClient *oss.Client +} + +func NewOSSServiceFromEnv() *OssService { + regionID := os.Getenv(constant.FC_REGION) + accessKeyID := os.Getenv(constant.ALIBABA_CLOUD_ACCESS_KEY_ID) + accessKeySecret := os.Getenv(constant.ALIBABA_CLOUD_ACCESS_KEY_SECRET) + securityToken := os.Getenv(constant.ALIBABA_CLOUD_SECURITY_TOKEN) + endpoint := "oss-" + regionID + "-internal.aliyuncs.com" + + ossClient, err := oss.New(endpoint, accessKeyID, accessKeySecret, func(client *oss.Client) { + client.Config.SecurityToken = securityToken + }) + if err != nil { + panic(err) + } + return &OssService{ + ossClient: ossClient, + } +} + +func (s *OssService) ListBuckets() ([]oss.BucketProperties, error) { + res, err := s.ossClient.ListBuckets() + if err != nil { + return nil, err + } + return res.Buckets, nil +} diff --git a/web-framework/go/gin/src/myapp/src/controllers/debug.go b/web-framework/go/gin/src/myapp/src/controllers/debug.go new file mode 100644 index 000000000..661c23080 --- /dev/null +++ b/web-framework/go/gin/src/myapp/src/controllers/debug.go @@ -0,0 +1,53 @@ +package controllers + +import ( + "os" + "strings" + + "github.com/gin-gonic/gin" + logger "github.com/sirupsen/logrus" + + "myapp/pkg/constant" +) + +func SetupDebugRouters(e *gin.Engine) { + g := e.Group("/debug") + g.Any("/displayHttpContext", DebugAPI) +} + +func DebugAPI(c *gin.Context) { + env := getEnvAsMap() + if env[constant.ALIBABA_CLOUD_ACCESS_KEY_ID] != "" { + env[constant.ALIBABA_CLOUD_ACCESS_KEY_ID] = "encrypted" + } + if env[constant.ALIBABA_CLOUD_ACCESS_KEY_SECRET] != "" { + env[constant.ALIBABA_CLOUD_ACCESS_KEY_SECRET] = "encrypted" + } + if env[constant.ALIBABA_CLOUD_SECURITY_TOKEN] != "" { + env[constant.ALIBABA_CLOUD_SECURITY_TOKEN] = "encrypted" + } + result := gin.H{ + "path": c.Request.URL.Path, + "body": "", // Gin中读取请求体要用c.Request.Body,且只能读取一次 + "method": c.Request.Method, + "queries": c.Request.URL.Query(), + "headers": c.Request.Header, + "env": env, // Go的环境变量是通过os包获取的 + } + + logger.WithContext(c).Infof("receive request: %#v", result) // 使用Go的内置日志库,但可以选择更强大的库如logrus + c.JSON(200, result) +} + +func getEnvAsMap() map[string]string { + envs := os.Environ() + envMap := make(map[string]string, len(envs)) + + for _, env := range envs { + pair := strings.SplitN(env, "=", 2) // 仅分割第一个"=",以确保值中的"="不会被分割 + if len(pair) == 2 { + envMap[pair[0]] = pair[1] + } + } + return envMap +} diff --git a/web-framework/go/gin/src/myapp/src/controllers/oss.go b/web-framework/go/gin/src/myapp/src/controllers/oss.go new file mode 100644 index 000000000..7e4bda499 --- /dev/null +++ b/web-framework/go/gin/src/myapp/src/controllers/oss.go @@ -0,0 +1,33 @@ +package controllers + +import ( + logger "github.com/sirupsen/logrus" + + "myapp/pkg/services" + + "github.com/gin-gonic/gin" + "github.com/pkg/errors" +) + +func SetupOSSRouters(e *gin.Engine) { + g := e.Group("/oss") + f := &OSSFunc{ + ossService: services.NewOSSServiceFromEnv(), + } + g.GET("/listBuckets", f.ListBuckets) +} + +type OSSFunc struct { + ossService *services.OssService +} + +func (s *OSSFunc) ListBuckets(c *gin.Context) { + result, err := s.ossService.ListBuckets() + if err != nil { + logger.WithContext(c).Errorf("failed to list buckets: %v", err) + c.JSON(500, gin.H{ + "error": errors.Wrapf(err, "failed to list buckets").Error(), + }) + } + c.JSON(200, result) +} diff --git a/web-framework/go/gin/src/myapp/src/controllers/welcome.go b/web-framework/go/gin/src/myapp/src/controllers/welcome.go new file mode 100644 index 000000000..a16c9907e --- /dev/null +++ b/web-framework/go/gin/src/myapp/src/controllers/welcome.go @@ -0,0 +1,16 @@ +package controllers + +import ( + "github.com/gin-gonic/gin" +) + +func SetupWelcomeRouters(e *gin.Engine) { + e.GET("/", RenderWelcomePage) +} + +// RenderWelcomePage 渲染首页 +func RenderWelcomePage(c *gin.Context) { + c.HTML(200, "index.html", gin.H{ + "title": "主页 - Gin Web App", + }) +} diff --git a/web-framework/go/gin/src/myapp/src/routes/routes.go b/web-framework/go/gin/src/myapp/src/routes/routes.go new file mode 100644 index 000000000..5d9777dbe --- /dev/null +++ b/web-framework/go/gin/src/myapp/src/routes/routes.go @@ -0,0 +1,22 @@ +package routes + +import ( + "myapp/src/controllers" + + "github.com/gin-gonic/gin" +) + +type RouterOptions func(router *gin.Engine) + +var opts = []RouterOptions{ + controllers.SetupDebugRouters, + controllers.SetupWelcomeRouters, + controllers.SetupOSSRouters, +} + +// InitRoutes 初始化路由规则 +func InitRoutes(router *gin.Engine) { + for _, opt := range opts { + opt(router) + } +} diff --git a/web-framework/go/gin/src/myapp/views/index.html b/web-framework/go/gin/src/myapp/views/index.html new file mode 100644 index 000000000..c32ebd871 --- /dev/null +++ b/web-framework/go/gin/src/myapp/views/index.html @@ -0,0 +1,11 @@ + + + + {{ .title }} + + + +

Welcome to Gin Web App!!!

+ + + \ No newline at end of file diff --git a/web-framework/go/gin/src/s.yaml b/web-framework/go/gin/src/s.yaml index 292234394..6beccf797 100644 --- a/web-framework/go/gin/src/s.yaml +++ b/web-framework/go/gin/src/s.yaml @@ -1,32 +1,37 @@ +# ------------------------------------ +# 官方手册: https://manual.serverless-devs.com/user-guide/aliyun/#fc3 +# 有问题快来钉钉群问一下吧:33947367 +# ------------------------------------ + edition: 3.0.0 -name: web-framework-app +name: my-gin-app access: '{{ access }}' vars: - region: '{{ region }}' + region: "{{ region }}" + functionName: '{{ functionName }}' + memorySize: 2048 # 实例内存默认为2GB + cpu: 1 # 实例CPU默认为1核 + timeout: 30 # 后端超时时间默认为30s + instanceConcurrency: 100 # 单个实例最多同时承载100个请求 + runtime: 'custom.debian10' + resources: framework: component: fc3 - actions: - pre-deploy: - - run: go mod tidy - path: ./code - - run: >- - GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o target/main - main.go - path: ./code props: region: ${vars.region} description: Serverless Devs Web Framework Gin Function - runtime: custom.debian10 - memorySize: 1024 - timeout: 30 - instanceConcurrency: 100 + runtime: ${vars.runtime} + memorySize: ${vars.memorySize} + timeout: ${vars.timeout} + instanceConcurrency: ${vars.instanceConcurrency} customRuntimeConfig: command: - /code/main port: 8080 - functionName: '{{ functionName }}' - code: ./code/target + functionName: ${vars.functionName} + code: ./myapp + role: acs:ram::${config('AccountID')}:role/aliyunfcdefaultrole triggers: - triggerName: httpTrigger triggerType: http diff --git a/web-framework/java/springboot/src/.gitignore b/web-framework/java/springboot/src/.gitignore new file mode 100644 index 000000000..e69de29bb diff --git a/web-framework/java/springboot/src/LICENSE b/web-framework/java/springboot/src/LICENSE new file mode 100644 index 000000000..d159169d1 --- /dev/null +++ b/web-framework/java/springboot/src/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/web-framework/java/springboot/src/cd.yaml b/web-framework/java/springboot/src/cd.yaml new file mode 100644 index 000000000..a67ae56d5 --- /dev/null +++ b/web-framework/java/springboot/src/cd.yaml @@ -0,0 +1,73 @@ +# 使用YAML文件定义发布的流水线,详见文档:https://help.aliyun.com/zh/functioncompute/user-guide/use-a-yaml-file-to-define-a-pipeline +kind: Pipeline +# 流水线名称,需要全局唯一 +name: p-<%.appName%>-<%.releaseVersion%> +spec: + context: + data: + dingdingNotification: + enable: false + skipOnSuccess: false + message: + at: + isAtAll: false + atMobiles: [] + atUserIds: [] + text: {} + msgtype: text + templateSpec: + tasks: + - context: + data: + enable: true + steps: + # 配置s工具 + - plugin: '@serverless-cd/s-setup' + # 从git或模板仓库拉取代码 + - plugin: '@serverless-cd/checkout' + # 预览配置变更 + - run: s plan -t s.yaml --debug + name: pre-check + runAfters: [] + taskTemplate: serverless-runner-task + - context: + data: + # 如果是测试环境不需要部署确认,可以改为false + enable: false + name: pre-check-approval + runAfters: + - name: pre-check + taskTemplate: need-approval + - context: + data: + enable: true + steps: + - plugin: '@serverless-cd/s-setup' + - plugin: '@serverless-cd/checkout' + # 设置构建工具版本 + - plugin: "@serverless-cd/runtime-setup" + inputs: + runtime: + # - java11 + # - java8 + - java17 + # 设置maven + - run: cp ./configs/settings-hz.xml ~/.m2/settings.xml + - run: java -version + # 设置依赖缓存 + - plugin: "@serverless-cd/cache" + inputs: + # 缓存的key,相同key的缓存会被共享并更新。 + # 在Bucket中缓存路径为cache-home/cache-<% .appName %> + key: "cache-<% .appName %>" + # 按照当前构建的工具要求,配置缓存的路径 + # maven场景这里是~/.m2 + path: ~/.m2 + # 执行构建命令 + - run: cd ./code && bash build.sh + # 执行构建部署 + - plugin: '@serverless-cd/s-deploy' + name: build-and-deploy + runAfters: + - name: pre-check-approval + taskTemplate: serverless-runner-task diff --git a/web-framework/java/springboot/src/code/.fcignore b/web-framework/java/springboot/src/code/.fcignore index e0089d352..e07fbdf2c 100644 --- a/web-framework/java/springboot/src/code/.fcignore +++ b/web-framework/java/springboot/src/code/.fcignore @@ -1,7 +1,5 @@ .s Dockerfile -mvnw pom.xml src -mvnw.cmd .fcignore diff --git a/web-framework/java/springboot/src/code/.gitignore b/web-framework/java/springboot/src/code/.gitignore new file mode 100644 index 000000000..52dfadd82 --- /dev/null +++ b/web-framework/java/springboot/src/code/.gitignore @@ -0,0 +1,121 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij+all,java +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij+all,java + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +# End of https://www.toptal.com/developers/gitignore/api/intellij+all,java + + +target/** \ No newline at end of file diff --git a/web-framework/java/springboot/src/code/mvnw b/web-framework/java/springboot/src/code/mvnw deleted file mode 100755 index 8b9da3b8b..000000000 --- a/web-framework/java/springboot/src/code/mvnw +++ /dev/null @@ -1,286 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - wget "$jarUrl" -O "$wrapperJarPath" - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - curl -o "$wrapperJarPath" "$jarUrl" - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/web-framework/java/springboot/src/code/mvnw.cmd b/web-framework/java/springboot/src/code/mvnw.cmd deleted file mode 100644 index fef5a8f7f..000000000 --- a/web-framework/java/springboot/src/code/mvnw.cmd +++ /dev/null @@ -1,161 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM https://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" -FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - echo Found %WRAPPER_JAR% -) else ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" - echo Finished downloading %WRAPPER_JAR% -) -@REM End of extension - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/web-framework/java/springboot/src/code/pom.xml b/web-framework/java/springboot/src/code/pom.xml index 16c8c01e7..0494f330c 100644 --- a/web-framework/java/springboot/src/code/pom.xml +++ b/web-framework/java/springboot/src/code/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.1.8.RELEASE + 2.7.18 com.example @@ -15,15 +15,10 @@ Demo project for Spring Boot - 1.8 + 17 + + - - - - ali-maven - http://maven.aliyun.com/nexus/content/groups/public - - @@ -31,11 +26,18 @@ spring-boot-starter-web + + com.aliyun.oss + aliyun-sdk-oss + 3.17.4 + + org.springframework.boot spring-boot-starter-test test + diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/Application.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/Application.java new file mode 100644 index 000000000..70ec59b43 --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/Application.java @@ -0,0 +1,39 @@ +package com.example.webframework; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + // 正确实践http函数怎么进行bootstrap + // 事件函数怎么进行initiate? + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + + // TODO 事件类型的函数如何正确地写处理? + // 事件函数与http函数场景,如何获取约定的上下文信息? + // 常见问题怎么解决,包括 + + // TODO 应用SpringBoot + SpringMVC的正确实践,开发RESTful接口 + // TODO SpringBoot + SpringMVC的正确实践,开发前后端一体化的接口 + // 详细程度需要到Action层或Controller层,DAO与Service层属于Spring应用问题 + // 常见问题可以提炼FAQ或者沉淀到工程中 + + // TODO 如何正确地推送metrics? @夏莞 + // 可观测的最佳实践也要放进去 + + // 产品出了什么新功能,涉及到研发层面的,要在runtime的模板案例里面show出来才对。 + // 旧功能设计的客户体验问题可以自己消化,新功能设计的问题可以自己赋能自己,了解客户的痛苦,进行优化 + + // 展示约定的environment变量 + + // 展示通过host指定hostname并生效 + + // 展示打印日志功能 + + // + +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/http/DebugController.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/http/DebugController.java new file mode 100644 index 000000000..e21f55bfd --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/http/DebugController.java @@ -0,0 +1,47 @@ +package com.example.webframework.application.http; + +import com.example.webframework.domain.EchoResponse; +import com.example.webframework.infrastructure.exceptions.InternalErrorException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.Map; + + +@RestController +@RequestMapping("/debug") +public class DebugController { + + + @Autowired + private ObjectMapper objectMapper; + + private static final Logger logger = LoggerFactory.getLogger(DebugController.class); + + + @RequestMapping(value = {"/displayHttpContext", "/displayHttpContext/"}) + public EchoResponse echo( + HttpServletRequest request, + @RequestHeader Map headers, + @RequestParam(required = false) Map params, + @RequestBody(required = false) String body) { + + EchoResponse result = new EchoResponse(); + if (request == null) { + logger.error("http request is null"); + throw new InternalErrorException("http request is null"); + } + result.path = request.getRequestURI(); + result.body = body; + result.method = request.getMethod(); + result.queries = request.getQueryString(); + result.headers = headers; + result.env = System.getenv(); + logger.info("receive request: {}", result); + return result; + } +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/WebFrameworkApplication.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/http/IndexController.java similarity index 55% rename from web-framework/java/springboot/src/code/src/main/java/com/example/webframework/WebFrameworkApplication.java rename to web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/http/IndexController.java index 5fae5e71c..8a6ad3978 100644 --- a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/WebFrameworkApplication.java +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/http/IndexController.java @@ -1,59 +1,40 @@ -package com.example.webframework; +package com.example.webframework.application.http; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.HashMap; -import java.util.Map; - -@SpringBootApplication +/** + * @author luoyu + * @date 2024/5/15 + **/ @RestController -public class WebFrameworkApplication { - - public static void main(String[] args) { - SpringApplication.run(WebFrameworkApplication.class, args); - } +@RequestMapping({"/", ""}) +public class IndexController { - @GetMapping("/") + @GetMapping({"/", ""}) public ResponseEntity welcome() { + // TODO P2 开发功能说明页面,引导用户体验全部功能 String welcome = "" + "" + "Serverless Devs - Powered By Serverless Devs" + - "" - + + "" + "" + "" + "
" + "
" + "

Devsapp

" + "

这是一个 Spring Boot 项目

" + - "自豪地通过Serverless Devs进行部署" + + "自豪的通过Serverless Devs进行部署" + "

您也可以快速体验:
" + "• 下载Serverless Devs工具:npm install @serverless-devs/s
" + - "• 初始化项目:s init start-springboot-v3
" + + "• 初始化项目:s init start-springboot
" + "• 项目部署:s deploy

" + "Serverless Devs 钉钉交流群:33947367

" + "
"; return new ResponseEntity<>(welcome, HttpStatus.OK); } - - @GetMapping("/fcheaders") - public ResponseEntity> listHeaders( - @RequestHeader Map headers) { - Map fcHeaders = new HashMap<>(); - headers.forEach((key, value) -> { - if (key.startsWith("x-fc")) { - fcHeaders.put(key, value); - } - - }); - - return new ResponseEntity<>(fcHeaders, HttpStatus.OK); - } } diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/http/OssController.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/http/OssController.java new file mode 100644 index 000000000..88c67335f --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/http/OssController.java @@ -0,0 +1,27 @@ +package com.example.webframework.application.http; + +import com.aliyun.oss.model.Bucket; +import com.example.webframework.application.service.OssService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * @author luoyu + * @date 2024/5/8 + **/ +@RestController +@RequestMapping("/oss") +public class OssController { + + @Autowired + private OssService ossService; + @GetMapping("/listBuckets") + public List listBuckets() { + return ossService.listBuckets(); + } + +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/service/OssService.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/service/OssService.java new file mode 100644 index 000000000..ba23b46dd --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/application/service/OssService.java @@ -0,0 +1,29 @@ +package com.example.webframework.application.service; + + +import com.aliyun.oss.OSS; +import com.aliyun.oss.model.Bucket; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.InputStream; +import java.util.List; + + + + +/** + * @author luoyu + * @date 2024/5/14 + **/ +@Component +public class OssService { + + @Autowired + private OSS ossClient; + + public List listBuckets() { + return ossClient.listBuckets(); + } + +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/domain/EchoResponse.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/domain/EchoResponse.java new file mode 100644 index 000000000..72ed16513 --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/domain/EchoResponse.java @@ -0,0 +1,28 @@ +package com.example.webframework.domain; + +import java.util.Map; + +/** + * @author luoyu + * @date 2024/5/7 + **/ +public class EchoResponse { + public String path; + public String body; + public String method; + public String queries; + public Map headers; + public Map env; + + @Override + public String toString() { + return "EchoResponse{" + + "path='" + path + '\'' + + ", body='" + body + '\'' + + ", method='" + method + '\'' + + ", queries='" + queries + '\'' + + ", headers=" + headers + + ", env=" + env + + '}'; + } +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/domain/STSCredentials.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/domain/STSCredentials.java new file mode 100644 index 000000000..12d07a96c --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/domain/STSCredentials.java @@ -0,0 +1,20 @@ +package com.example.webframework.domain; + +/** + * @author luoyu + * @date 2024/5/14 + **/ +public class STSCredentials { + public String accessKeyId; + public String accessKeySecret; + public String securityToken; + + @Override + public String toString() { + return "STSCredentials{" + + "accessKeyId='" + accessKeyId + '\'' + + ", accessKeySecret='" + accessKeySecret + '\'' + + ", securityToken='" + securityToken + '\'' + + '}'; + } +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/exceptions/InternalErrorException.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/exceptions/InternalErrorException.java new file mode 100644 index 000000000..28ae3a4a8 --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/exceptions/InternalErrorException.java @@ -0,0 +1,11 @@ +package com.example.webframework.infrastructure.exceptions; + +/** + * @author luoyu + * @date 2024/5/7 + **/ +public class InternalErrorException extends RuntimeException { + public InternalErrorException(String message) { + super(message); + } +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/filters/RequestIDInterceptor.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/filters/RequestIDInterceptor.java new file mode 100644 index 000000000..26962d51e --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/filters/RequestIDInterceptor.java @@ -0,0 +1,40 @@ +package com.example.webframework.infrastructure.filters; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.UUID; + +/** + * @author luoyu + * @date 2024/5/10 + **/ +@Component +public class RequestIDInterceptor extends OncePerRequestFilter { + + private static final String KEY_REQUEST_ID = "x-fc-request-id"; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + try { + String requestId = request.getHeader(KEY_REQUEST_ID); + if (requestId == null) { + requestId = UUID.randomUUID().toString(); + } + MDC.put("RequestId", requestId); + response.addHeader(KEY_REQUEST_ID, requestId); + filterChain.doFilter(request, response); + } finally { + MDC.remove("RequestId"); + } + } +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/oss/OssBeans.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/oss/OssBeans.java new file mode 100644 index 000000000..a6398ec3c --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/oss/OssBeans.java @@ -0,0 +1,36 @@ +package com.example.webframework.infrastructure.oss; + +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import com.aliyun.oss.common.auth.DefaultCredentialProvider; +import com.example.webframework.domain.STSCredentials; +import com.example.webframework.infrastructure.utils.EnvironmentUtils; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Component; + +/** + * @author luoyu + * @date 2024/5/14 + **/ + +@Component +public class OssBeans { + + @Bean + public OSS ossClient() { + STSCredentials credentials = EnvironmentUtils.getSTSCredentials(); + DefaultCredentialProvider provider = new DefaultCredentialProvider( + credentials.accessKeyId, + credentials.accessKeySecret, + credentials.securityToken + ); + String regionID = EnvironmentUtils.getCurrentRegion(); + return OSSClientBuilder.create() + .region(regionID) + // https://help.aliyun.com/zh/oss/user-guide/regions-and-endpoints + .endpoint("oss-" + regionID + "-internal.aliyuncs.com") + .credentialsProvider(provider) + .build(); + } + +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/utils/EnvironmentUtils.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/utils/EnvironmentUtils.java new file mode 100644 index 000000000..c685b4bf8 --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/utils/EnvironmentUtils.java @@ -0,0 +1,21 @@ +package com.example.webframework.infrastructure.utils; + +import com.example.webframework.domain.STSCredentials; + +/** + * @author luoyu + * @date 2024/5/10 + **/ +public class EnvironmentUtils { + public static STSCredentials getSTSCredentials() { + STSCredentials result = new STSCredentials(); + result.accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); + result.accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); + result.securityToken = System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN"); + return result; + } + + public static String getCurrentRegion() { + return System.getenv("FC_REGION"); + } +} diff --git a/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/utils/HeadersUtils.java b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/utils/HeadersUtils.java new file mode 100644 index 000000000..411e118f9 --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/java/com/example/webframework/infrastructure/utils/HeadersUtils.java @@ -0,0 +1,16 @@ +package com.example.webframework.infrastructure.utils; + +/** + * @author luoyu + * @date 2024/5/10 + **/ +public class HeadersUtils { + + // 从headers中获取credentials + + public static String getCredentials(String headers) { + return null; + } + + +} diff --git a/web-framework/java/springboot/src/code/src/main/resources/application.properties b/web-framework/java/springboot/src/code/src/main/resources/application.properties index 6f6a64403..99802c632 100644 --- a/web-framework/java/springboot/src/code/src/main/resources/application.properties +++ b/web-framework/java/springboot/src/code/src/main/resources/application.properties @@ -1,2 +1 @@ -server.port=9000 -# server.servlet.context-path=/2016-08-15/proxy/springboot/welcome/ \ No newline at end of file +server.port=9000 \ No newline at end of file diff --git a/web-framework/java/springboot/src/code/src/main/resources/logback.xml b/web-framework/java/springboot/src/code/src/main/resources/logback.xml new file mode 100644 index 000000000..3c40f0c01 --- /dev/null +++ b/web-framework/java/springboot/src/code/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} %X{RequestId:- } - [%thread] %-5level %logger{36} - %msg%n + UTF-8 + + + + + + + \ No newline at end of file diff --git a/web-framework/java/springboot/src/code/src/test/java/com/example/webframework/WebFrameworkApplicationTests.java b/web-framework/java/springboot/src/code/src/test/java/com/example/webframework/WebFrameworkApplicationTests.java deleted file mode 100644 index 75cee61d6..000000000 --- a/web-framework/java/springboot/src/code/src/test/java/com/example/webframework/WebFrameworkApplicationTests.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.example.webframework; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.HttpStatus; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class WebFrameworkApplicationTests { - - @Test - public void testWelcome() { - assertEquals(HttpStatus.OK, new WebFrameworkApplication().welcome().getStatusCode()); - } - -} diff --git a/web-framework/java/springboot/src/configs/settings-hz.xml b/web-framework/java/springboot/src/configs/settings-hz.xml new file mode 100644 index 000000000..0247e86c9 --- /dev/null +++ b/web-framework/java/springboot/src/configs/settings-hz.xml @@ -0,0 +1,33 @@ + + + + + + + + alimaven + central + aliyun maven + https://maven.aliyun.com/repository/public + + + + + repo2 + central + maven apache org maven + https://repo.maven.apache.org/maven2/ + + + + + repo1 + central + maven org maven + https://repo1.maven.org/maven2/ + + + + + diff --git a/web-framework/java/springboot/src/readme.md b/web-framework/java/springboot/src/readme.md index 23b5ea435..992c0f6a3 100644 --- a/web-framework/java/springboot/src/readme.md +++ b/web-framework/java/springboot/src/readme.md @@ -1,135 +1,119 @@ +# start-springboot 帮助文档 -> 注:当前项目为 Serverless Devs 应用,由于应用中会存在需要初始化才可运行的变量(例如应用部署地区、函数名等等),所以**不推荐**直接 Clone 本仓库到本地进行部署或直接复制 s.yaml 使用,**强烈推荐**通过 `s init ${模版名称}` 的方法或应用中心进行初始化,详情可参考[部署 & 体验](#部署--体验) 。 - -# start-springboot-v3 帮助文档 -

- - - - - - - - - -

- - - -本案例是基于Pivotal团队提供的全新的Spring Boot框架,简化Spring应用的初始化搭建过程,并且快速部署到阿里云函数计算FC。 - - - - - -- [:smiley_cat: 代码](https://github.com/devsapp/start-web-framework/tree/V3/web-framework/java/springboot/src) - - - +这是函数计算平台的一个springboot+custom runtime开发的脚手架,内置了完整的函数描述文件以及流水线配置,可以在本地以及Devs平台上一键部署,并完成函数的后续开发、构建、部署以及调试功能。 +## 前期准备 +1. 安装并学会使用Git工具。 +2. 拥有阿里云的账号,并开通函数计算产品,并保证有足够的余额使用函数计算产品。 - ++ 云上开发(推荐) + 推荐在云上开发,可以省去本地环境的搭建过程,只需要赋予Devs平台足够的权限即可完成自动构建发布。 -## 前期准备 ++ 本地开发 -使用该项目,您需要有开通以下服务并拥有对应权限: + 如果需要在本地完成开发、构建,需要以下工作。 + + 完成Docker安装。 + + 完成s工具安装与配置。 + + 完成Java环境的初始化,默认为Java11。 - +云上开发需要为Devs平台赋予以下权限,本地开发需要为s工具配置的账号或角色赋予以下权限。 +| 服务/业务 | 函数计算 | +|-------|---------------------| +| 权限/策略 | AliyunFCFullAccess | +| 权限/策略 | AliyunOSSFullAccess | +## 部署&体验 -| 服务/业务 | 权限 | 相关文档 | -| --- | --- | --- | -| 函数计算 | AliyunFCFullAccess | [帮助文档](https://help.aliyun.com/product/2508973.html) [计费文档](https://help.aliyun.com/document_detail/2512928.html) | +1. 云上部署(推荐) - +将代码push到远程仓库,通过Devs平台找到相关流水线点击确认后,自动完成部署。 - +2. 本地构建+部署 +在本地根路径执行下列命令或使用Maven工具直接进行构建. +```shell + cd ./code && bash build.sh && cd ../ +``` - +在本地根路径执行下列命令进行一键部署。 - +```shell +s deploy --use-local --skip-push --assume-yes +``` +# 应用详情 +1. web类型,返回静态或动态网页。 - +查看示例[文件](code/src/main/java/com/example/webframework/application/http/IndexController.java),学习如何返回静态或动态网页类型。 -## 部署 & 体验 +访问域名根路径,如:http://{分配域名}.fc.devsapp.net/,即可看到返回的网页。 - - -- :fire: 通过 [Serverless 应用中心](https://fcnext.console.aliyun.com/applications/create?template=start-springboot-v3) , - [![Deploy with Severless Devs](https://img.alicdn.com/imgextra/i1/O1CN01w5RFbX1v45s8TIXPz_!!6000000006118-55-tps-95-28.svg)](https://fcnext.console.aliyun.com/applications/create?template=start-springboot-v3) 该应用。 - - - - -- 通过 [Serverless Devs Cli](https://www.serverless-devs.com/serverless-devs/install) 进行部署: - - [安装 Serverless Devs Cli 开发者工具](https://www.serverless-devs.com/serverless-devs/install) ,并进行[授权信息配置](https://docs.serverless-devs.com/fc/config) ; - - 初始化项目:`s init start-springboot-v3 -d start-springboot-v3` - - 进入项目,并进行项目部署:`cd start-springboot-v3 && s deploy -y` - - +2. 查看http请求详情。 -## 案例介绍 +查看示例[文件](code/src/main/java/com/example/webframework/application/http/DebugController.java) +,学习如何查看http请求上下文详情,学习从请求以及环境变量中获取上下文信息。 - +访问域名相对路径`/debug/displayHttpContext`,如http://{分配域名}.fc.devsapp.net/debug/displayHttpContext,即可看到返回的http请求上下文详情。 -本案例是基于 Pivotal 团队提供的全新的 Spring Boot 框架,简化 Spring 应用的初始化搭建过程,并且快速部署到阿里云函数计算FC。 +3. 学习访问其他云产品。 -Spring Boot 是一个快速开发 Spring 框架应用的脚手架,它使用“习惯优于配置”(约定优于配置)的理念让你的项目快速运行起来。Spring Boot 并不是对 Spring 功能上的增强,而是提供了一种快速使用 Spring 的方式。 +查看示例[文件](code/src/main/java/com/example/webframework/application/http/OssController.java),学习如何访问其他云产品。 -Spring Boot的流行程度非常高,主要得益于其快速开发、微服务架构支持、易于管理和部署、兼容性强以及社区支持等特点。Spring Boot天然支持微服务架构的特点使其成为了构建微服务的理想选择。通过Spring Boot,开发者可以轻松地将应用程序拆分成多个可独立部署和升级的小型服务,充分利用计算资源,提高系统的可扩展性和可维护性。 +访问域名相对路径`/oss/listBuckets`,如http://{分配域名}.fc.devsapp.net/loss/listBuckets,即可看到返回的oss桶列表。 -Spring Boot因其快速开发、微服务架构支持、易于管理和部署、兼容性强以及社区支持等特点而备受欢迎,成为了当前最流行的Java Web开发框架之一。 +## 如何开发 -Spring Boot适用的场景也非常广泛,如:Web应用程序开发、微服务架构、批处理和数据处理等。无论是简单的Web应用还是复杂的分布式系统,Spring Boot都能提供高效、稳定的开发支持,是Java开发者在构建企业级应用时的首选框架之一。 +//TODO 回答客户在这个案例基础上开发的问题。 -通过 Serverless 开发平台,您只需要几步,就可以体验 Spring Boot 框架,并享受 Serverless 架构带来的降本提效的技术红利。 +### 切换java版本 - +开发web类型函数时,推荐使用custom runtime进行开发。custom runtime的说明可以参加文档。TODO +结合公共层技术(链接TODO),可以在函数计算场景切换java版本,方式如下。 -## 使用流程 +#### 修改maven配置文件 - +在[pom](code/pom.xml)中第11行修改maven构建配置配置。 -### 查看部署的案例 +TODO: 低版本的springboot对高版本的jdk17有兼容性问题,使用jdk17时需要切换springboot到更高版本。 -部署完成之后,您可以看到系统返回给您的案例地址,例如: +#### 修改云上运行环境配置 -![图片alt](https://img.alicdn.com/imgextra/i2/O1CN01DMr08p1Os7yU07ky9_!!6000000001760-0-tps-1126-324.jpg) +修改[文件](s.yaml) +中的path、javaHome、javaLayers配置,详见[文档](https://help.aliyun.com/zh/functioncompute/user-guide/configure-common-layers-for-a-function?#p-dmq-hai-qq7)。 -此时,打开案例地址,就可以进入 Springboot 项目首页: +| 语言 | runtime | path | javaHome | javaLayers | +|--------|-----------------|------------------------------------------------------------------------------------------------------|-------------|---------------------------------------------------------| +| java8 | custom.debian10 | /opt/java8/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin | /opt/java8 | acs:fc:${vars.region}:official:layers/Java8/versions/1 | +| java11 | custom | /opt/java11/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin | /opt/java11 | acs:fc:${vars.region}:official:layers/Java11/versions/2 | +| java17 | custom | /opt/java17/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin | /opt/java17 | acs:fc:${vars.region}:official:layers/Java17/versions/2 | -![图片alt](https://img.alicdn.com/imgextra/i4/O1CN01xaoDCw1PNjIy0sBA2_!!6000000001829-0-tps-1746-1318.jpg) +### 修改云上构建环境 -### 二次开发 +修改[文件](cd.yaml)中的第50行关于runtime-setup插件的配置。 +| 语言 | @serverless-cd/runtime-setup插件 | +|--------|----------------------| +| java8 | java8 | +| java11 | java11 | +| java17 | java17 | -您可以通过云端控制台的开发功能进行二次开发,如果您之前是在本地创建的项目案例,也可以在本地项目目录`start-springboot-v3`文件夹下,对项目进行二次开发。开发完成后,可以通过`s deploy`进行快速部署。 - +### 依赖添加 -## 注意事项 +在pom文件中直接添加依赖描述即可。 - - +## 本地开发、调试 +## 线上流水线运行说明 - +## 常见问题的FAQ ## 开发者社区 -您如果有关于错误的反馈或者未来的期待,您可以在 [Serverless Devs repo Issues](https://github.com/serverless-devs/serverless-devs/issues) 中进行反馈和交流。如果您想要加入我们的讨论组或者了解 FC 组件的最新动态,您可以通过以下渠道进行: - -

- -| | | | -| --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | -|

微信公众号:`serverless`
|
微信小助手:`xiaojiangwh`
|
钉钉交流群:`33947367`
| -

-
+您如果有关于错误的反馈或者未来的期待,您可以在 [Serverless Devs repo Issues](https://github.com/serverless-devs/serverless-devs/issues) +中进行反馈和交流。 \ No newline at end of file diff --git a/web-framework/java/springboot/src/s.yaml b/web-framework/java/springboot/src/s.yaml index b32a38691..eb85bb2c0 100644 --- a/web-framework/java/springboot/src/s.yaml +++ b/web-framework/java/springboot/src/s.yaml @@ -4,49 +4,58 @@ # ------------------------------------ edition: 3.0.0 -name: springboot-app -access: "{{ access }}" +name: my-springboot-app +access: '{{ access }}' vars: - region: "{{ region }}" - + region: 'cn-qingdao' + functionName: 'my-springboot-app' + memorySize: 2048 + cpu: 1 + timeout: 30 + instanceConcurrency: 100 + runtime: 'custom' + path: '/opt/java17/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin' + javaHome: '/opt/java17' + javaLayers: 'acs:fc:${vars.region}:official:layers/Java17/versions/2' resources: - framework: + function_1: component: fc3 - actions: - pre-deploy: - - run: mvn package -DskipTests - path: ./code props: - region: ${vars.region} # - description: Serverless Devs Web Framework Function - runtime: custom - cpu: 1 - memorySize: 2048 + region: ${vars.region} + functionName: ${vars.functionName} + runtime: ${vars.runtime} + description: 'Serverless Devs Web Framework Demo Function update' + timeout: ${vars.timeout} + memorySize: ${vars.memorySize} + instanceConcurrency: ${vars.instanceConcurrency} + logConfig: auto + role: acs:ram::${config('AccountID')}:role/aliyunfcdefaultrole + cpu: ${vars.cpu} diskSize: 512 - instanceConcurrency: 100 + code: ./code customRuntimeConfig: command: - ./bootstrap - functionName: "{{ functionName }}" - code: ./code - triggers: - - triggerName: httpTrigger - triggerType: http - triggerConfig: + environmentVariables: + PATH: ${vars.path} + JAVA_HOME: ${vars.javaHome} + layers: + - ${vars.javaLayers} + domain_1: + component: fc3-domain + props: # 组件的属性值 + region: ${vars.region} + domainName: auto # 使用 auto 自动获取一个临时测试域名, 生产请务必使用自己的域名 + protocol: HTTP # HTTP | HTTPS | HTTP,HTTPS + routeConfig: + routes: + - functionName: ${vars.functionName} methods: - GET - POST - PUT - DELETE - authType: anonymous + - PATCH + path: /* + qualifier: LATEST - fc3_domain_0: - component: fc3-domain - props: - region: ${vars.region} - domainName: auto - protocol: HTTP - routeConfig: - routes: - - path: /* - functionName: ${resources.framework.props.functionName} diff --git a/web-framework/nodejs/express/src/.gitignore b/web-framework/nodejs/express/src/.gitignore index b512c09d4..dea2e4ddc 100644 --- a/web-framework/nodejs/express/src/.gitignore +++ b/web-framework/nodejs/express/src/.gitignore @@ -1 +1,4 @@ -node_modules \ No newline at end of file +myapp/node_modules +.idea +.s/ +.s.cache/ \ No newline at end of file diff --git a/web-framework/nodejs/express/src/LICENSE b/web-framework/nodejs/express/src/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/web-framework/nodejs/express/src/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 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. + + + Copyright (C) + + 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: + + Copyright (C) + 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 +. diff --git a/web-framework/nodejs/express/src/cd.yaml b/web-framework/nodejs/express/src/cd.yaml new file mode 100644 index 000000000..30bc3c0c2 --- /dev/null +++ b/web-framework/nodejs/express/src/cd.yaml @@ -0,0 +1,69 @@ +# 使用YAML文件定义发布的流水线,详见文档:https://help.aliyun.com/zh/functioncompute/user-guide/use-a-yaml-file-to-define-a-pipeline +kind: Pipeline +# 流水线名称,需要全局唯一 +name: p-<%.appName%>-<%.releaseVersion%> +spec: + context: + data: + dingdingNotification: + enable: false + skipOnSuccess: false + message: + at: + isAtAll: false + atMobiles: [] + atUserIds: [] + text: {} + msgtype: text + templateSpec: + tasks: + - context: + data: + enable: true + steps: + # 配置s工具 + - plugin: '@serverless-cd/s-setup' + # 从git或模板仓库拉取代码 + - plugin: '@serverless-cd/checkout' + # 预览配置变更 + - run: s plan -t s.yaml --debug + name: pre-check + runAfters: [] + taskTemplate: serverless-runner-task + - context: + data: + # 如果是测试环境不需要部署确认,可以改为false + enable: false + name: pre-check-approval + runAfters: + - name: pre-check + taskTemplate: need-approval + - context: + data: + enable: true + steps: + - plugin: '@serverless-cd/s-setup' + - plugin: '@serverless-cd/checkout' + # 设置构建工具版本,查看文档:https://help.aliyun.com/zh/functioncompute/user-guide/use-the-runtime-setup-plug-in-to-initialize-a-runtime + - plugin: "@serverless-cd/runtime-setup" + inputs: + runtime: + - nodejs20 + - run: node -v + # 设置依赖缓存 + - plugin: "@serverless-cd/cache" + inputs: + # 缓存的key,相同key的缓存会被共享并更新。 + # 在Bucket中缓存路径为cache-home/cache-<% .appName %> + key: "cache-<% .appName %>" + # 按照当前构建的工具要求,配置缓存的路径 + # npm场景这里是~/.npm,详情查看:https://help.aliyun.com/zh/functioncompute/user-guide/use-the-oss-cache-plug-in-to-accelerate-dependency-building + path: ~/.npm + # 执行构建命令 + - run: cd myapp && npm install --production + # 执行构建部署 + - plugin: '@serverless-cd/s-deploy' + name: build-and-deploy + runAfters: + - name: pre-check-approval + taskTemplate: serverless-runner-task diff --git a/web-framework/nodejs/express/src/code/index.js b/web-framework/nodejs/express/src/code/index.js deleted file mode 100644 index 94787a183..000000000 --- a/web-framework/nodejs/express/src/code/index.js +++ /dev/null @@ -1,32 +0,0 @@ -const express = require("express"); -const bodyParser = require("body-parser"); - -const app = express(); - -app.use(bodyParser.urlencoded({ extended: true })); -app.use(bodyParser.json()); -app.use(bodyParser.text()); -app.use(bodyParser.raw()); - -app.all("/*", (req, res) => { - const requestId = req.headers["x-fc-request-id"]; - console.log("FC Invoke Start RequestId: " + requestId); - - res.send( - JSON.stringify({ - msg: "Hello, World! ", - reqeust: { - query: req.query, - path: req.originalUrl, - data: req.body, - clientIp: req.headers["x-forwarded-for"], - }, - }) - ); - - console.log("FC Invoke End RequestId: " + requestId); -}); - -app.listen(9000, () => { - console.log("Express started on port 9000"); -}); diff --git a/web-framework/nodejs/express/src/code/package.json b/web-framework/nodejs/express/src/code/package.json deleted file mode 100644 index fa241c260..000000000 --- a/web-framework/nodejs/express/src/code/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "nodejs-express", - "version": "0.0.0", - "private": true, - "dependencies": { - "express": "^4.19.2" - } -} diff --git a/web-framework/nodejs/express/src/myapp/.gitignore b/web-framework/nodejs/express/src/myapp/.gitignore new file mode 100644 index 000000000..346073233 --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/.gitignore @@ -0,0 +1,232 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij+all,node +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij+all,node + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Node ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* + +### Node Patch ### +# Serverless Webpack directories +.webpack/ + +# Optional stylelint cache + +# SvelteKit build / generate output +.svelte-kit + +# End of https://www.toptal.com/developers/gitignore/api/intellij+all,node \ No newline at end of file diff --git a/web-framework/nodejs/express/src/myapp/alicloud/oss.js b/web-framework/nodejs/express/src/myapp/alicloud/oss.js new file mode 100644 index 000000000..9c80a841f --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/alicloud/oss.js @@ -0,0 +1,23 @@ +const OSS = require('ali-oss'); +const {logger} = require('../logger/config') + +const getOssClient = () => { + const region = 'oss-'+process.env.FC_REGION || 'oss-cn-hangzhou'; + const accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID || 'dummy-access-key-id'; + const accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET || 'dummy-access-key-secret'; + const securityToken = process.env.ALIBABA_CLOUD_SECURITY_TOKEN || 'dummy-security-token'; + return new OSS({ + region, + accessKeyId, + accessKeySecret, + stsToken: securityToken, + internal: true, + }); +}; + +const client = getOssClient(); + +module.exports = { + getOssClient, + client +} \ No newline at end of file diff --git a/web-framework/nodejs/express/src/myapp/app.js b/web-framework/nodejs/express/src/myapp/app.js new file mode 100644 index 000000000..0c36180c6 --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/app.js @@ -0,0 +1,53 @@ +const createError = require('http-errors'); +const express = require('express'); +const path = require('path'); +const cookieParser = require('cookie-parser'); +const {v4: uuidv4} = require('uuid'); +const {logger, requestContext} = require('./logger/config') + +const welcomeRouter = require('./routes/welcome') +const ossRouter = require('./routes/oss') +const debugRouter = require('./routes/debug') + +const app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'pug'); + + +function requestIdMiddleware(req, res, next) { + let requestId = req.headers['x-fc-request-id'] || 'unknown-request-id'; + requestContext.run(() => { + requestContext.set('requestId', requestId); + next(); + }); +} + +app.use(requestIdMiddleware); +app.use(express.json()); +app.use(express.urlencoded({extended: false})); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/', welcomeRouter); +app.use('/oss', ossRouter); +app.use('/debug', debugRouter) + +// catch 404 and forward to error handler +app.use(function (req, res, next) { + next(createError(404)); +}); + +// error handler +app.use(function (err, req, res, next) { + // set locals, only providing error in development + res.locals.message = err.message; + res.locals.error = req.app.get('env') === 'development' ? err : {}; + + // render the error page + res.status(err.status || 500); + res.render('error'); +}); + +module.exports = app; diff --git a/web-framework/nodejs/express/src/myapp/bin/www b/web-framework/nodejs/express/src/myapp/bin/www new file mode 100755 index 000000000..710593824 --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/bin/www @@ -0,0 +1,90 @@ +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +const app = require('../app'); +const debug = require('debug')('myapp:server'); +const http = require('http'); + +/** + * Get port from environment and store in Express. + */ + +const port = normalizePort(process.env.PORT || '9000'); +app.set('port', port); + +/** + * Create HTTP server. + */ + +var server = http.createServer(app); + +/** + * Listen on provided port, on all network interfaces. + */ + +server.listen(port); +server.on('error', onError); +server.on('listening', onListening); + +/** + * Normalize a port into a number, string, or false. + */ + +function normalizePort(val) { + var port = parseInt(val, 10); + + if (isNaN(port)) { + // named pipe + return val; + } + + if (port >= 0) { + // port number + return port; + } + + return false; +} + +/** + * Event listener for HTTP server "error" event. + */ + +function onError(error) { + if (error.syscall !== 'listen') { + throw error; + } + + var bind = typeof port === 'string' + ? 'Pipe ' + port + : 'Port ' + port; + + // handle specific listen errors with friendly messages + switch (error.code) { + case 'EACCES': + console.error(bind + ' requires elevated privileges'); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(bind + ' is already in use'); + process.exit(1); + break; + default: + throw error; + } +} + +/** + * Event listener for HTTP server "listening" event. + */ + +function onListening() { + var addr = server.address(); + var bind = typeof addr === 'string' + ? 'pipe ' + addr + : 'port ' + addr.port; + debug('Listening on ' + bind); +} diff --git a/web-framework/nodejs/express/src/myapp/build.sh b/web-framework/nodejs/express/src/myapp/build.sh new file mode 100644 index 000000000..08a2afa74 --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/build.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -e + +npm install --production \ No newline at end of file diff --git a/web-framework/nodejs/express/src/myapp/logger/config.js b/web-framework/nodejs/express/src/myapp/logger/config.js new file mode 100644 index 000000000..30ab04253 --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/logger/config.js @@ -0,0 +1,27 @@ +const winston = require('winston'); +const { createNamespace } = require('cls-hooked'); +const requestContext = createNamespace('requestContext'); + +// 设置 winston logger 实例 +const logger = winston.createLogger({ + level: 'info', + transports: [ + new winston.transports.Console({ + format: winston.format.combine( + winston.format.colorize(), + winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), + winston.format.printf((info) => { + const requestId = requestContext.get('requestId') || 'N/A'; + return `${info.timestamp} [${requestId}] ${info.level}: ${info.message}`; + //const requestId = info.meta && info.meta.req && info.meta.req.headers && info.meta.req.headers['x-fc-request-id'] ? info.meta.req.headers.headers['x-fc-request-id'] : 'N/A'; + return `${info.timestamp} - ${info.level} - ${requestId}: ${info.message}`; + }) + ), + }) + ] +}); + +module.exports = { + logger, + requestContext, +}; \ No newline at end of file diff --git a/web-framework/nodejs/express/src/myapp/package.json b/web-framework/nodejs/express/src/myapp/package.json new file mode 100644 index 000000000..db5870fdc --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/package.json @@ -0,0 +1,20 @@ +{ + "name": "myapp", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www" + }, + "dependencies": { + "ali-oss": "^6.20.0", + "cls-hooked": "^4.2.2", + "cookie-parser": "~1.4.4", + "debug": "~2.6.9", + "express": "~4.16.1", + "express-winston": "^4.2.0", + "http-errors": "~1.6.3", + "pug": "2.0.0-beta11", + "uuid": "^9.0.1", + "winston": "^3.13.0" + } +} diff --git a/web-framework/nodejs/express/src/myapp/public/stylesheets/style.css b/web-framework/nodejs/express/src/myapp/public/stylesheets/style.css new file mode 100644 index 000000000..9453385b9 --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/public/stylesheets/style.css @@ -0,0 +1,8 @@ +body { + padding: 50px; + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; +} + +a { + color: #00B7FF; +} diff --git a/web-framework/nodejs/express/src/myapp/routes/debug.js b/web-framework/nodejs/express/src/myapp/routes/debug.js new file mode 100644 index 000000000..deb69606b --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/routes/debug.js @@ -0,0 +1,28 @@ +const express = require('express'); +const router = express.Router(); +const {logger} = require('../logger/config') +/* GET home page. */ +router.get('/displayHttpContext', (req, res) => { + const env = Object.assign({}, process.env) + env.ALIBABA_CLOUD_ACCESS_KEY_ID = "encrypted" + env.ALIBABA_CLOUD_ACCESS_KEY_SECRET = "encrypted" + env.ALIBABA_CLOUD_SECURITY_TOKEN = "encrypted" + const headers = Object.assign({}, req.headers) + headers['x-fc-access-key-id'] = "encrypted" + headers['x-fc-access-key-secret'] = "encrypted" + headers['x-fc-security-token'] = "encrypted" + const result = { + path: req.path, + body: req.body, + method: req.method, + queries: req.query, + headers: headers, + env: env, + }; + + // 使用标准日志记录方式替换了console.log + logger.info(`Receive request: ${JSON.stringify(result)}`); + res.json(result); +}); + +module.exports = router; \ No newline at end of file diff --git a/web-framework/nodejs/express/src/myapp/routes/oss.js b/web-framework/nodejs/express/src/myapp/routes/oss.js new file mode 100644 index 000000000..e90d39910 --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/routes/oss.js @@ -0,0 +1,19 @@ +const express = require('express'); +const router = express.Router(); +const {client} = require('../alicloud/oss') +const {logger} = require('../logger/config') +/* GET home page. */ +router.get('/listBuckets', async (req, res) => { + try { + const result = await client.listBuckets() + return res.json(result) + } catch (e) { + logger.error(`failed to list buckets: ${JSON.stringify(e)}`) + return res.json({ + code: 500, + msg: e.message + }) + } +}); + +module.exports = router; \ No newline at end of file diff --git a/web-framework/nodejs/express/src/myapp/routes/welcome.js b/web-framework/nodejs/express/src/myapp/routes/welcome.js new file mode 100644 index 000000000..8c0c53dc0 --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/routes/welcome.js @@ -0,0 +1,11 @@ +const express = require('express'); +const router = express.Router(); +const {logger} = require('../logger/config') + +/* GET home page. */ +router.get('/', function(req, res) { + logger.info('welcome page'); + res.render('index', { title: 'Serverless Devs' }); +}); + +module.exports = router; diff --git a/web-framework/nodejs/express/src/myapp/views/error.pug b/web-framework/nodejs/express/src/myapp/views/error.pug new file mode 100644 index 000000000..51ec12c6a --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/views/error.pug @@ -0,0 +1,6 @@ +extends layout + +block content + h1= message + h2= error.status + pre #{error.stack} diff --git a/web-framework/nodejs/express/src/myapp/views/index.pug b/web-framework/nodejs/express/src/myapp/views/index.pug new file mode 100644 index 000000000..ad1434e67 --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/views/index.pug @@ -0,0 +1,22 @@ +extends layout + +block content + h1 #{title} - Powered By Serverless Devs + h2 这是一个 Express.js 项目 + span 自豪的通过Serverless Devs进行部署 + br + p + | 您也可以快速体验: + br + | • 下载Serverless Devs工具:npm install @serverless-devs/s + br + | 初始化项目:s init start-flask-v3 + br + | • 项目部署:s deploy + br + | + br + | Serverless Devs 钉钉交流群:33947367 + + + diff --git a/web-framework/nodejs/express/src/myapp/views/layout.pug b/web-framework/nodejs/express/src/myapp/views/layout.pug new file mode 100644 index 000000000..15af079bf --- /dev/null +++ b/web-framework/nodejs/express/src/myapp/views/layout.pug @@ -0,0 +1,7 @@ +doctype html +html + head + title= title + link(rel='stylesheet', href='/stylesheets/style.css') + body + block content diff --git a/web-framework/nodejs/express/src/s.yaml b/web-framework/nodejs/express/src/s.yaml index f1151cb5b..d46267172 100644 --- a/web-framework/nodejs/express/src/s.yaml +++ b/web-framework/nodejs/express/src/s.yaml @@ -6,36 +6,43 @@ edition: 3.0.0 name: express-app access: "{{ access }}" + vars: region: "{{ region }}" + functionName: '{{ functionName }}' + memorySize: 2048 # 实例内存默认为2GB + cpu: 1 # 实例CPU默认为1核 + timeout: 30 # 后端超时时间默认为30s + diskSize: 512 # 实例磁盘默认为512MB + instanceConcurrency: 100 # 单个实例最多同时承载100个请求 + runtime: 'custom.debian10' + path: '/opt/nodejs20/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/ruby/bin' + nodejsLayers: 'acs:fc:${vars.region}:official:layers/Nodejs20/versions/1' + resources: framework: component: fc3 - actions: - pre-deploy: - - run: export PATH=/usr/local/versions/node/v20.8.1/bin:$PATH && npm install --production - path: ./code props: region: ${vars.region} description: Serverless Devs Web Framework Function - runtime: custom.debian10 - timeout: 60 - cpu: 1 - memorySize: 2048 - diskSize: 512 - instanceConcurrency: 100 + runtime: ${vars.runtime} + timeout: ${vars.timeout} + cpu: ${vars.cpu} + memorySize: ${vars.memorySize} + diskSize: ${vars.diskSize} + instanceConcurrency: ${vars.instanceConcurrency} layers: - - acs:fc:${vars.region}:official:layers/Nodejs20/versions/1 + - ${vars.nodejsLayers} environmentVariables: - PATH: >- - /opt/nodejs20/bin:/usr/local/bin/apache-maven/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/ruby/bin + PATH: ${vars.path} customRuntimeConfig: command: - node - - ./index.js + - ./bin/www port: 9000 - functionName: "{{ functionName }}" - code: ./code + functionName: ${vars.functionName} + role: acs:ram::${config('AccountID')}:role/aliyunfcdefaultrole + code: ./myapp triggers: - triggerName: httpTrigger triggerType: http @@ -45,6 +52,8 @@ resources: - POST - PUT - DELETE + - PATCH + - OPTIONS authType: anonymous fc3_domain_0: component: fc3-domain diff --git a/web-framework/python/flask/src/.fcignore b/web-framework/python/flask/src/.fcignore new file mode 100644 index 000000000..b2ff5e1e4 --- /dev/null +++ b/web-framework/python/flask/src/.fcignore @@ -0,0 +1,10 @@ +.idea/ +.venv/ +.vscode/ +.DS_Store +.env +s.yaml +readme.md +build.sh +.fcignore +.gitignore \ No newline at end of file diff --git a/web-framework/python/flask/src/.gitignore b/web-framework/python/flask/src/.gitignore new file mode 100644 index 000000000..49fd9ff25 --- /dev/null +++ b/web-framework/python/flask/src/.gitignore @@ -0,0 +1,267 @@ +# Created by https://www.toptal.com/developers/gitignore/api/python,intellij+all +# Edit at https://www.toptal.com/developers/gitignore?templates=python,intellij+all + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +# End of https://www.toptal.com/developers/gitignore/api/python,intellij+all + +python +.idea \ No newline at end of file diff --git a/web-framework/python/flask/src/LICENSE b/web-framework/python/flask/src/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/web-framework/python/flask/src/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 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. + + + Copyright (C) + + 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: + + Copyright (C) + 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 +. diff --git a/web-framework/python/flask/src/alicloud/oss.py b/web-framework/python/flask/src/alicloud/oss.py new file mode 100644 index 000000000..9bf4d7c69 --- /dev/null +++ b/web-framework/python/flask/src/alicloud/oss.py @@ -0,0 +1,8 @@ +import oss2 + +from config import config + +stsAuth = oss2.StsAuth(config.ACCESS_KEY_ID, config.ACCESS_KEY_SECRET, config.SECURITY_TOKEN) +# https://help.aliyun.com/zh/oss/user-guide/regions-and-endpoints +endpoint = "oss-%s-internal.aliyuncs.com" % config.CURRENT_REGION +oss_client = oss2.Service(stsAuth, endpoint) diff --git a/web-framework/python/flask/src/build.sh b/web-framework/python/flask/src/build.sh new file mode 100644 index 000000000..05936e90c --- /dev/null +++ b/web-framework/python/flask/src/build.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e + +# make sure .env exist +if [ ! -d .env ]; then + python3 -m venv .env +fi + +source .venv/bin/activate +# build for local +.venv/bin/pip3 install -r requirements.txt +mkdir -p python +rm -rf python +# build for remote, docker is required for this action +s build \ No newline at end of file diff --git a/web-framework/python/flask/src/cd.yaml b/web-framework/python/flask/src/cd.yaml new file mode 100644 index 000000000..54df28a63 --- /dev/null +++ b/web-framework/python/flask/src/cd.yaml @@ -0,0 +1,69 @@ +# 使用YAML文件定义发布的流水线,详见文档:https://help.aliyun.com/zh/functioncompute/user-guide/use-a-yaml-file-to-define-a-pipeline +kind: Pipeline +# 流水线名称,需要全局唯一 +name: p-<%.appName%>-<%.releaseVersion%> +spec: + context: + data: + dingdingNotification: + enable: false + skipOnSuccess: false + message: + at: + isAtAll: false + atMobiles: [] + atUserIds: [] + text: {} + msgtype: text + templateSpec: + tasks: + - context: + data: + enable: true + steps: + # 配置s工具 + - plugin: '@serverless-cd/s-setup' + # 从git或模板仓库拉取代码 + - plugin: '@serverless-cd/checkout' + # 预览配置变更 + - run: s plan -t s.yaml --debug + name: pre-check + runAfters: [] + taskTemplate: serverless-runner-task + - context: + data: + # 如果是测试环境不需要部署确认,可以改为false + enable: false + name: pre-check-approval + runAfters: + - name: pre-check + taskTemplate: need-approval + - context: + data: + enable: true + steps: + - plugin: '@serverless-cd/s-setup' + - plugin: '@serverless-cd/checkout' + # 设置构建工具版本,查看文档:https://help.aliyun.com/zh/functioncompute/user-guide/use-the-runtime-setup-plug-in-to-initialize-a-runtime + - plugin: "@serverless-cd/runtime-setup" + inputs: + runtime: + - python3.10 + - run: python -V + # 设置依赖缓存 + - plugin: "@serverless-cd/cache" + inputs: + # 缓存的key,相同key的缓存会被共享并更新。 + # 在Bucket中缓存路径为cache-home/cache-<% .appName %> + key: "cache-<% .appName %>" + # 按照当前构建的工具要求,配置缓存的路径 + # pip场景这里是~/.cache,详情查看:https://help.aliyun.com/zh/functioncompute/user-guide/use-the-oss-cache-plug-in-to-accelerate-dependency-building + path: ~/.cache + # 执行构建命令 + - run: pip install -r requirements.txt -t ./python + # 执行构建部署 + - plugin: '@serverless-cd/s-deploy' + name: build-and-deploy + runAfters: + - name: pre-check-approval + taskTemplate: serverless-runner-task diff --git a/web-framework/python/flask/src/code/index.py b/web-framework/python/flask/src/code/index.py deleted file mode 100644 index 9329a3a2e..000000000 --- a/web-framework/python/flask/src/code/index.py +++ /dev/null @@ -1,30 +0,0 @@ -from flask import Flask, request, jsonify -import arrow - -app = Flask(__name__) - - -@app.route("/", defaults={"path": ""}, methods=["GET", "POST", "PUT", "DELETE"]) -@app.route("/", methods=["GET", "POST", "PUT", "DELETE"]) -def hello_world(path): - requestId = request.headers.get("x-fc-request-id") - print("FC Invoke Start RequestId: " + requestId) - - response = jsonify( - { - "msg": "Hello, World!" + " at " + arrow.now().format("YYYY-MM-DD HH:mm:ss"), - "reqeust": { - "query": str(request.query_string, "utf-8"), - "path": path, - "data": str(request.stream.read(), "utf-8"), - "clientIp": request.headers.get("x-forwarded-for"), - }, - } - ) - - print("FC Invoke End RequestId: " + requestId) - return response - - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=9000) diff --git a/web-framework/python/flask/src/code/requirements.txt b/web-framework/python/flask/src/code/requirements.txt deleted file mode 100644 index 023f6a616..000000000 --- a/web-framework/python/flask/src/code/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -# 建议您使用 pip install -r requirements.txt -t ./python 将依赖安装到 python 目录下。 -arrow==1.3.0 \ No newline at end of file diff --git a/web-framework/python/flask/src/config.py b/web-framework/python/flask/src/config.py new file mode 100644 index 000000000..d3add7214 --- /dev/null +++ b/web-framework/python/flask/src/config.py @@ -0,0 +1,13 @@ +import os + + +class Config: + SECRET_KEY = os.environ.get('SECRET_KEY') or 'my-passwd' + ACCESS_KEY_ID = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID") or 'default-access-key-id' + ACCESS_KEY_SECRET = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET") or 'default-access-key-secret' + SECURITY_TOKEN = os.environ.get("ALIBABA_CLOUD_SECURITY_TOKEN") or 'default-security-token' + CURRENT_REGION = os.environ.get("FC_REGION") or 'cn-hangzhou' + DEBUG = True + + +config = Config diff --git a/web-framework/python/flask/src/index.py b/web-framework/python/flask/src/index.py new file mode 100644 index 000000000..4948114f1 --- /dev/null +++ b/web-framework/python/flask/src/index.py @@ -0,0 +1,5 @@ +from init import create_app +app = create_app() + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=9000) diff --git a/web-framework/python/flask/src/init.py b/web-framework/python/flask/src/init.py new file mode 100644 index 000000000..8c0ec5b68 --- /dev/null +++ b/web-framework/python/flask/src/init.py @@ -0,0 +1,35 @@ +import logging +import uuid + +from flask import Flask, g, request + +from route.debug import debug_bp +from route.oss import oss_bp +from route.welcome import welcome_bp + + +def create_app(): + app = Flask(__name__) + + # 载入配置 + app.config.from_pyfile('./config.py') + + logging.basicConfig(level=logging.INFO) + with app.app_context(): + # 注册路由 + app.register_blueprint(welcome_bp) + app.register_blueprint(oss_bp) + app.register_blueprint(debug_bp) + + @app.before_request + def before_request(): + # 从请求头中获取 request-id + g.request_id = request.headers.get('x-fc-request-id', uuid.uuid4()) + + @app.after_request + def after_request(response): + # 移除request-id + g.request_id = '' + return response + + return app diff --git a/web-framework/python/flask/src/logger/config.py b/web-framework/python/flask/src/logger/config.py new file mode 100644 index 000000000..915617d53 --- /dev/null +++ b/web-framework/python/flask/src/logger/config.py @@ -0,0 +1,22 @@ +import logging + +from flask import g + + +class RequestIdFilter(logging.Filter): + def filter(self, record): + record.request_id = getattr(g, 'request_id', '') + return True + + +# 配置日志记录器 +handler = logging.StreamHandler() +handler.setLevel(logging.INFO) +fmt = '%(asctime)s - %(name)s - %(levelname)s - %(request_id)s - %(message)s' +formatter = logging.Formatter(fmt=fmt, datefmt='%Y-%m-%d %H:%M:%S') +handler.setFormatter(formatter) + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) +logger.addHandler(handler) +logger.addFilter(RequestIdFilter()) diff --git a/web-framework/python/flask/src/requirements.txt b/web-framework/python/flask/src/requirements.txt new file mode 100644 index 000000000..22f2f7437 --- /dev/null +++ b/web-framework/python/flask/src/requirements.txt @@ -0,0 +1,7 @@ +# 建议您使用bash build.sh将依赖安装到 python 目录下。 +arrow==1.3.0 +Flask==3.0.3 +cryptography==38.0.4 +charset-normalizer==2.1.1 +urllib3==1.26.18 +oss2==2.18.6 \ No newline at end of file diff --git a/web-framework/python/flask/src/route/debug.py b/web-framework/python/flask/src/route/debug.py new file mode 100644 index 000000000..77e84f3bf --- /dev/null +++ b/web-framework/python/flask/src/route/debug.py @@ -0,0 +1,33 @@ +from logger.config import logger +import os + +from flask import Blueprint, jsonify, request + +debug_bp = Blueprint('debug', __name__, url_prefix='/debug') + + +@debug_bp.route('/displayHttpContext', methods=['GET', 'POST', 'PUT', 'DELETE']) +def echo(): + # 构建响应数据 + env = dict(os.environ) + if 'ALIBABA_CLOUD_ACCESS_KEY_ID' in env: + env['ALIBABA_CLOUD_ACCESS_KEY_ID'] = 'encrypted' + if 'ALIBABA_CLOUD_ACCESS_KEY_SECRET' in env: + env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] = 'encrypted' + if 'ALIBABA_CLOUD_SECURITY_TOKEN' in env: + env['ALIBABA_CLOUD_SECURITY_TOKEN'] = 'encrypted' + + result = { + 'path': request.path, + 'body': request.get_data(as_text=True), + 'method': request.method, + 'queries': request.args, + 'headers': dict(request.headers), + 'env': env, + } + + # 记录日志信息 + logger.info('receive request: %s', result) + + # 返回 JSON 响应 + return jsonify(result) diff --git a/web-framework/python/flask/src/route/oss.py b/web-framework/python/flask/src/route/oss.py new file mode 100644 index 000000000..d32dc8324 --- /dev/null +++ b/web-framework/python/flask/src/route/oss.py @@ -0,0 +1,26 @@ +from flask import Blueprint, jsonify + +from logger.config import logger + +from alicloud.oss import oss_client + +oss_bp = Blueprint('oss', __name__, url_prefix='/oss') + + +@oss_bp.route('/listBuckets', methods=['GET']) +def index(): + try: + resp = oss_client.list_buckets() + return jsonify(list(map(lambda x : { + 'name': x.name, + 'location': x.location, + 'creation_date': x.creation_date, + 'extranet_endpoint': x.extranet_endpoint, + 'intranet_endpoint': x.intranet_endpoint, + 'storage_class': x.storage_class, + 'region': x.region, + 'resource_group_id': x.resource_group_id + }, resp.buckets))) + except Exception as e: + logger.info('failed to list buckets: %s', e) + return jsonify(e) diff --git a/web-framework/python/flask/src/route/welcome.py b/web-framework/python/flask/src/route/welcome.py new file mode 100644 index 000000000..f784a8fae --- /dev/null +++ b/web-framework/python/flask/src/route/welcome.py @@ -0,0 +1,9 @@ +from flask import Blueprint, render_template + +welcome_bp = Blueprint('welcome', __name__, url_prefix='/') + + +@welcome_bp.route('/') +def index(): + return render_template('index.html') + diff --git a/web-framework/python/flask/src/s.yaml b/web-framework/python/flask/src/s.yaml index ea718aa85..2faaa08ef 100644 --- a/web-framework/python/flask/src/s.yaml +++ b/web-framework/python/flask/src/s.yaml @@ -8,37 +8,38 @@ name: flask-app access: "{{ access }}" vars: region: "{{ region }}" + functionName: '{{ functionName }}' + memorySize: 2048 # 实例内存默认为2GB + cpu: 1 # 实例CPU默认为1核 + timeout: 30 # 后端超时时间默认为30s + instanceConcurrency: 100 # 单个实例最多同时承载100个请求 + runtime: 'custom.debian10' + path: "/code/python/bin:/var/fc/lang/python3.10/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin" + resources: framework: component: fc3 - actions: - pre-deploy: - - run: mkdir python - path: ./code - - run: pip install -r requirements.txt -t ./python - path: ./code props: - timeout: 60 - cpu: 1 - memorySize: 2048 + timeout: ${vars.timeout} + cpu: ${vars.cpu} + memorySize: ${vars.memorySize} + role: acs:ram::${config('AccountID')}:role/aliyunfcdefaultrole diskSize: 512 - instanceConcurrency: 100 + instanceConcurrency: ${vars.instanceConcurrency} region: ${vars.region} description: Serverless Devs Web Framework Function - runtime: custom.debian10 + runtime: ${vars.runtime} customRuntimeConfig: command: - python3 - index.py port: 9000 environmentVariables: - PATH: /var/fc/lang/python3.10/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/ruby/bin:/opt/bin:/code:/code/bin - PYTHONPATH: /opt/python:/code/python:/code + PATH: ${vars.path} + PYTHONPATH: /code/python TZ: Asia/Shanghai - functionName: "{{ functionName }}" - code: ./code - layers: - - acs:fc:${this.props.region}:official:layers/Python3-Flask2x/versions/2 + functionName: ${vars.functionName} + code: ./ triggers: - triggerName: httpTrigger triggerType: http @@ -48,6 +49,8 @@ resources: - POST - PUT - DELETE + - PATCH + - OPTIONS authType: anonymous fc3_domain_0: diff --git a/web-framework/python/flask/src/static/style.css b/web-framework/python/flask/src/static/style.css new file mode 100644 index 000000000..6e94bdfaf --- /dev/null +++ b/web-framework/python/flask/src/static/style.css @@ -0,0 +1,10 @@ +body { + font-family: Arial, sans-serif; + margin: 0; + padding: 0; + text-align: center; + background-color: #f0f0f0; +} +h1 { + color: #333; +} \ No newline at end of file diff --git a/web-framework/python/flask/src/templates/index.html b/web-framework/python/flask/src/templates/index.html new file mode 100644 index 000000000..b49fe0d67 --- /dev/null +++ b/web-framework/python/flask/src/templates/index.html @@ -0,0 +1,20 @@ + + + + + Serverless Devs - Powered By Serverless Devs + + + +
+
+

Devsapp

+

这是一个 Flask 项目

+ 自豪的通过Serverless Devs进行部署 +

您也可以快速体验:
+ • 下载Serverless Devs工具:npm install @serverless-devs/s
+ • 初始化项目:s init start-flask-v3
+ • 项目部署:s deploy

+ Serverless Devs 钉钉交流群:33947367

+
+ \ No newline at end of file