The response has been limited to 50k tokens of the smallest files in the repo. You can remove this limitation by removing the max tokens filter.
├── Deployments
    ├── Dockerfile
    ├── deployment.yml
    └── docker-compose.yml
├── LICENSE
├── README.md
├── config.yaml
├── config
    └── config.go
├── core
    ├── api.go
    ├── engine.go
    ├── middlewares.go
    └── routers.go
├── go.mod
├── go.sum
├── main.go
├── resouces
    ├── JsEnv_Dev.js
    └── WeChat_Dev.js
├── test
    ├── muilte_request.py
    └── register_function.js
└── utils
    ├── code.go
    ├── file.go
    ├── hash.go
    ├── logger.go
    └── terminal.go


/Deployments/Dockerfile:
--------------------------------------------------------------------------------
 1 | FROM golang:1.16 as builder
 2 | # Setting environment variables
 3 | ENV GOPROXY="https://goproxy.cn,direct" \
 4 |     GO111MODULE="on" \
 5 |     CGO_ENABLED="0" \
 6 |     GOOS="linux" \
 7 |     GOARCH="amd64"
 8 | 
 9 | # Switch to workspace
10 | WORKDIR /go/src/github.com/gowebspider/jsrpc/
11 | # Load file
12 | COPY . .
13 | # add rely
14 | # Build and place the results in /tmp/jsrpc
15 | RUN  go mod tidy && go build -o /tmp/jsrpc .
16 | 
17 | FROM alpine:latest
18 | WORKDIR /root/
19 | COPY --from=builder /tmp/jsrpc .
20 | EXPOSE 12080 12443
21 | CMD ["./jsrpc"]


--------------------------------------------------------------------------------
/Deployments/deployment.yml:
--------------------------------------------------------------------------------
 1 | apiVersion: apps/v1
 2 | kind: Deployments
 3 | metadata:
 4 |   name: jsrpc
 5 |   labels:
 6 |     app: jsrpc
 7 | spec:
 8 |   replicas: 3
 9 |   template:
10 |     metadata:
11 |       name: jsrpc
12 |       labels:
13 |         app: jsrpc
14 |     spec:
15 |       containers:
16 |         - name: jsrpc
17 |           image:
18 |           imagePullPolicy: Always
19 |           ports:
20 |             - containerPort: 12080
21 |             - containerPort: 12443
22 |       restartPolicy: Always
23 |   selector:
24 |     matchLabels:
25 |       app: jsrpc
26 | 
27 | ---
28 | apiVersion: v1
29 | kind: Service
30 | metadata:
31 |   name: jsrpc
32 | spec:
33 |   selector:
34 |     app: jsrpc
35 |   type: NodePort
36 |   ports:
37 |     - name: basic
38 |       port: 12080
39 |       nodePort: 32080
40 |     - name: ssl
41 |       port: 12443
42 |       nodePort: 32443


--------------------------------------------------------------------------------
/Deployments/docker-compose.yml:
--------------------------------------------------------------------------------
 1 | version: "3.8"
 2 | services:
 3 |   jsrpc:
 4 |     deploy:
 5 |       replicas: 3
 6 |     image: "${}"
 7 |     ports:
 8 |       - "12080:12080"
 9 |       - "12443:12443"
10 |     restart: always


--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
  1 |                     GNU GENERAL PUBLIC LICENSE
  2 |                        Version 3, 29 June 2007
  3 | 
  4 |  Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
  5 |  Everyone is permitted to copy and distribute verbatim copies
  6 |  of this license document, but changing it is not allowed.
  7 | 
  8 |                             Preamble
  9 | 
 10 |   The GNU General Public License is a free, copyleft license for
 11 | software and other kinds of works.
 12 | 
 13 |   The licenses for most software and other practical works are designed
 14 | to take away your freedom to share and change the works.  By contrast,
 15 | the GNU General Public License is intended to guarantee your freedom to
 16 | share and change all versions of a program--to make sure it remains free
 17 | software for all its users.  We, the Free Software Foundation, use the
 18 | GNU General Public License for most of our software; it applies also to
 19 | any other work released this way by its authors.  You can apply it to
 20 | your programs, too.
 21 | 
 22 |   When we speak of free software, we are referring to freedom, not
 23 | price.  Our General Public Licenses are designed to make sure that you
 24 | have the freedom to distribute copies of free software (and charge for
 25 | them if you wish), that you receive source code or can get it if you
 26 | want it, that you can change the software or use pieces of it in new
 27 | free programs, and that you know you can do these things.
 28 | 
 29 |   To protect your rights, we need to prevent others from denying you
 30 | these rights or asking you to surrender the rights.  Therefore, you have
 31 | certain responsibilities if you distribute copies of the software, or if
 32 | you modify it: responsibilities to respect the freedom of others.
 33 | 
 34 |   For example, if you distribute copies of such a program, whether
 35 | gratis or for a fee, you must pass on to the recipients the same
 36 | freedoms that you received.  You must make sure that they, too, receive
 37 | or can get the source code.  And you must show them these terms so they
 38 | know their rights.
 39 | 
 40 |   Developers that use the GNU GPL protect your rights with two steps:
 41 | (1) assert copyright on the software, and (2) offer you this License
 42 | giving you legal permission to copy, distribute and/or modify it.
 43 | 
 44 |   For the developers' and authors' protection, the GPL clearly explains
 45 | that there is no warranty for this free software.  For both users' and
 46 | authors' sake, the GPL requires that modified versions be marked as
 47 | changed, so that their problems will not be attributed erroneously to
 48 | authors of previous versions.
 49 | 
 50 |   Some devices are designed to deny users access to install or run
 51 | modified versions of the software inside them, although the manufacturer
 52 | can do so.  This is fundamentally incompatible with the aim of
 53 | protecting users' freedom to change the software.  The systematic
 54 | pattern of such abuse occurs in the area of products for individuals to
 55 | use, which is precisely where it is most unacceptable.  Therefore, we
 56 | have designed this version of the GPL to prohibit the practice for those
 57 | products.  If such problems arise substantially in other domains, we
 58 | stand ready to extend this provision to those domains in future versions
 59 | of the GPL, as needed to protect the freedom of users.
 60 | 
 61 |   Finally, every program is threatened constantly by software patents.
 62 | States should not allow patents to restrict development and use of
 63 | software on general-purpose computers, but in those that do, we wish to
 64 | avoid the special danger that patents applied to a free program could
 65 | make it effectively proprietary.  To prevent this, the GPL assures that
 66 | patents cannot be used to render the program non-free.
 67 | 
 68 |   The precise terms and conditions for copying, distribution and
 69 | modification follow.
 70 | 
 71 |                        TERMS AND CONDITIONS
 72 | 
 73 |   0. Definitions.
 74 | 
 75 |   "This License" refers to version 3 of the GNU General Public License.
 76 | 
 77 |   "Copyright" also means copyright-like laws that apply to other kinds of
 78 | works, such as semiconductor masks.
 79 | 
 80 |   "The Program" refers to any copyrightable work licensed under this
 81 | License.  Each licensee is addressed as "you".  "Licensees" and
 82 | "recipients" may be individuals or organizations.
 83 | 
 84 |   To "modify" a work means to copy from or adapt all or part of the work
 85 | in a fashion requiring copyright permission, other than the making of an
 86 | exact copy.  The resulting work is called a "modified version" of the
 87 | earlier work or a work "based on" the earlier work.
 88 | 
 89 |   A "covered work" means either the unmodified Program or a work based
 90 | on the Program.
 91 | 
 92 |   To "propagate" a work means to do anything with it that, without
 93 | permission, would make you directly or secondarily liable for
 94 | infringement under applicable copyright law, except executing it on a
 95 | computer or modifying a private copy.  Propagation includes copying,
 96 | distribution (with or without modification), making available to the
 97 | public, and in some countries other activities as well.
 98 | 
 99 |   To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies.  Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 | 
103 |   An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License.  If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 | 
112 |   1. Source Code.
113 | 
114 |   The "source code" for a work means the preferred form of the work
115 | for making modifications to it.  "Object code" means any non-source
116 | form of a work.
117 | 
118 |   A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 | 
123 |   The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form.  A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 | 
134 |   The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities.  However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work.  For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 | 
147 |   The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 | 
151 |   The Corresponding Source for a work in source code form is that
152 | same work.
153 | 
154 |   2. Basic Permissions.
155 | 
156 |   All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met.  This License explicitly affirms your unlimited
159 | permission to run the unmodified Program.  The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work.  This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 | 
164 |   You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force.  You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright.  Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 | 
175 |   Conveying under any other circumstances is permitted solely under
176 | the conditions stated below.  Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 | 
179 |   3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 | 
181 |   No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 | 
187 |   When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 | 
195 |   4. Conveying Verbatim Copies.
196 | 
197 |   You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 | 
205 |   You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 | 
208 |   5. Conveying Modified Source Versions.
209 | 
210 |   You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 | 
214 |     a) The work must carry prominent notices stating that you modified
215 |     it, and giving a relevant date.
216 | 
217 |     b) The work must carry prominent notices stating that it is
218 |     released under this License and any conditions added under section
219 |     7.  This requirement modifies the requirement in section 4 to
220 |     "keep intact all notices".
221 | 
222 |     c) You must license the entire work, as a whole, under this
223 |     License to anyone who comes into possession of a copy.  This
224 |     License will therefore apply, along with any applicable section 7
225 |     additional terms, to the whole of the work, and all its parts,
226 |     regardless of how they are packaged.  This License gives no
227 |     permission to license the work in any other way, but it does not
228 |     invalidate such permission if you have separately received it.
229 | 
230 |     d) If the work has interactive user interfaces, each must display
231 |     Appropriate Legal Notices; however, if the Program has interactive
232 |     interfaces that do not display Appropriate Legal Notices, your
233 |     work need not make them do so.
234 | 
235 |   A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit.  Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 | 
245 |   6. Conveying Non-Source Forms.
246 | 
247 |   You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 | 
252 |     a) Convey the object code in, or embodied in, a physical product
253 |     (including a physical distribution medium), accompanied by the
254 |     Corresponding Source fixed on a durable physical medium
255 |     customarily used for software interchange.
256 | 
257 |     b) Convey the object code in, or embodied in, a physical product
258 |     (including a physical distribution medium), accompanied by a
259 |     written offer, valid for at least three years and valid for as
260 |     long as you offer spare parts or customer support for that product
261 |     model, to give anyone who possesses the object code either (1) a
262 |     copy of the Corresponding Source for all the software in the
263 |     product that is covered by this License, on a durable physical
264 |     medium customarily used for software interchange, for a price no
265 |     more than your reasonable cost of physically performing this
266 |     conveying of source, or (2) access to copy the
267 |     Corresponding Source from a network server at no charge.
268 | 
269 |     c) Convey individual copies of the object code with a copy of the
270 |     written offer to provide the Corresponding Source.  This
271 |     alternative is allowed only occasionally and noncommercially, and
272 |     only if you received the object code with such an offer, in accord
273 |     with subsection 6b.
274 | 
275 |     d) Convey the object code by offering access from a designated
276 |     place (gratis or for a charge), and offer equivalent access to the
277 |     Corresponding Source in the same way through the same place at no
278 |     further charge.  You need not require recipients to copy the
279 |     Corresponding Source along with the object code.  If the place to
280 |     copy the object code is a network server, the Corresponding Source
281 |     may be on a different server (operated by you or a third party)
282 |     that supports equivalent copying facilities, provided you maintain
283 |     clear directions next to the object code saying where to find the
284 |     Corresponding Source.  Regardless of what server hosts the
285 |     Corresponding Source, you remain obligated to ensure that it is
286 |     available for as long as needed to satisfy these requirements.
287 | 
288 |     e) Convey the object code using peer-to-peer transmission, provided
289 |     you inform other peers where the object code and Corresponding
290 |     Source of the work are being offered to the general public at no
291 |     charge under subsection 6d.
292 | 
293 |   A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 | 
297 |   A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling.  In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage.  For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product.  A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 | 
310 |   "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source.  The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 | 
318 |   If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information.  But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 | 
329 |   The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed.  Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 | 
337 |   Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 | 
343 |   7. Additional Terms.
344 | 
345 |   "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law.  If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 | 
354 |   When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it.  (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.)  You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 | 
361 |   Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 | 
365 |     a) Disclaiming warranty or limiting liability differently from the
366 |     terms of sections 15 and 16 of this License; or
367 | 
368 |     b) Requiring preservation of specified reasonable legal notices or
369 |     author attributions in that material or in the Appropriate Legal
370 |     Notices displayed by works containing it; or
371 | 
372 |     c) Prohibiting misrepresentation of the origin of that material, or
373 |     requiring that modified versions of such material be marked in
374 |     reasonable ways as different from the original version; or
375 | 
376 |     d) Limiting the use for publicity purposes of names of licensors or
377 |     authors of the material; or
378 | 
379 |     e) Declining to grant rights under trademark law for use of some
380 |     trade names, trademarks, or service marks; or
381 | 
382 |     f) Requiring indemnification of licensors and authors of that
383 |     material by anyone who conveys the material (or modified versions of
384 |     it) with contractual assumptions of liability to the recipient, for
385 |     any liability that these contractual assumptions directly impose on
386 |     those licensors and authors.
387 | 
388 |   All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10.  If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term.  If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 | 
398 |   If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 | 
403 |   Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 | 
407 |   8. Termination.
408 | 
409 |   You may not propagate or modify a covered work except as expressly
410 | provided under this License.  Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 | 
415 |   However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 | 
422 |   Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 | 
429 |   Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License.  If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 | 
435 |   9. Acceptance Not Required for Having Copies.
436 | 
437 |   You are not required to accept this License in order to receive or
438 | run a copy of the Program.  Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance.  However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work.  These actions infringe copyright if you do
443 | not accept this License.  Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 | 
446 |   10. Automatic Licensing of Downstream Recipients.
447 | 
448 |   Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License.  You are not responsible
451 | for enforcing compliance by third parties with this License.
452 | 
453 |   An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations.  If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 | 
463 |   You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License.  For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 | 
471 |   11. Patents.
472 | 
473 |   A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based.  The
475 | work thus licensed is called the contributor's "contributor version".
476 | 
477 |   A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version.  For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 | 
487 |   Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 | 
492 |   In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement).  To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 | 
499 |   If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients.  "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 | 
513 |   If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 | 
521 |   A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License.  You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 | 
536 |   Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 | 
540 |   12. No Surrender of Others' Freedom.
541 | 
542 |   If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License.  If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all.  For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 | 
552 |   13. Use with the GNU Affero General Public License.
553 | 
554 |   Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work.  The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 | 
563 |   14. Revised Versions of this License.
564 | 
565 |   The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time.  Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 | 
570 |   Each version is given a distinguishing version number.  If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation.  If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 | 
579 |   If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 | 
584 |   Later license versions may give you additional or different
585 | permissions.  However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 | 
589 |   15. Disclaimer of Warranty.
590 | 
591 |   THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 | 
600 |   16. Limitation of Liability.
601 | 
602 |   IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 | 
612 |   17. Interpretation of Sections 15 and 16.
613 | 
614 |   If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 | 
621 |                      END OF TERMS AND CONDITIONS
622 | 
623 |             How to Apply These Terms to Your New Programs
624 | 
625 |   If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 | 
629 |   To do so, attach the following notices to the program.  It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 | 
634 |     <one line to give the program's name and a brief idea of what it does.>
635 |     Copyright (C) <year>  <name of author>
636 | 
637 |     This program is free software: you can redistribute it and/or modify
638 |     it under the terms of the GNU General Public License as published by
639 |     the Free Software Foundation, either version 3 of the License, or
640 |     (at your option) any later version.
641 | 
642 |     This program is distributed in the hope that it will be useful,
643 |     but WITHOUT ANY WARRANTY; without even the implied warranty of
644 |     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
645 |     GNU General Public License for more details.
646 | 
647 |     You should have received a copy of the GNU General Public License
648 |     along with this program.  If not, see <https://www.gnu.org/licenses/>.
649 | 
650 | Also add information on how to contact you by electronic and paper mail.
651 | 
652 |   If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 | 
655 |     <program>  Copyright (C) <year>  <name of author>
656 |     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 |     This is free software, and you are welcome to redistribute it
658 |     under certain conditions; type `show c' for details.
659 | 
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License.  Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 | 
664 |   You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | <https://www.gnu.org/licenses/>.
668 | 
669 |   The GNU General Public License does not permit incorporating your program
670 | into proprietary programs.  If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library.  If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License.  But first, please read
674 | <https://www.gnu.org/licenses/why-not-lgpl.html>.
675 | 


--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
  1 | ```dart
  2 | 
  3 |        __       _______..______      .______     ______ 
  4 |       |  |     /       ||   _  \     |   _  \   /      |
  5 |       |  |    |   (----`|  |_)  |    |  |_)  | |  ,----'
  6 | .--.  |  |     \   \    |      /     |   ___/  |  |     
  7 | |  `--'  | .----)   |   |  |\  \----.|  |      |  `----.
  8 |  \______/  |_______/    | _| `._____|| _|       \______|
  9 | 
 10 | ```
 11 | 
 12 | ## 交流平台
 13 | 
 14 | 为了建立一个更好的 jsrpc 交流平台,我们与猿人学的平哥共同创建了一个微信交流群。  
 15 | 希望借此机会,帮助广大开发者更深入地了解和使用 jsrpc。
 16 | 
 17 | ### 加入方式
 18 | 请使用微信扫描以下二维码并备注“jsrpc”以申请加入我们的交流群。
 19 | 
 20 | ### 交流群的内容
 21 | 在这个交流群里,我们将:
 22 | - 及时分享 jsrpc 的使用方法和实践案例。
 23 | - 发布工具的后续功能更新和版本维护信息。
 24 | - 邀请多位长期关注 jsrpc 的技术创作者共同参与内容交流和经验分享。
 25 | 
 26 | ### 特别资源
 27 | 群内将提供更多的jsrpc 实操案例 、使用方法 及常见问题 汇总等资料,
 28 | 
 29 | 欢迎感兴趣的朋友踊跃加入,共同构建一个开放、实用的jsrpc工具交流社区。
 30 | 
 31 | <img width="250" alt="王平" src="https://github.com/user-attachments/assets/a9586ac9-a8b7-4322-b3c2-00d2841f6e48" />  
 32 | 
 33 | &nbsp; 
 34 | &nbsp; 
 35 | 
 36 | ---
 37 | -- js逆向之远程调用(rpc)免去抠代码补环境
 38 | 
 39 | > 作者-黑脸怪
 40 | - [目录结构](#目录结构)
 41 | - [基本介绍](#基本介绍)
 42 | - [实现](#实现)
 43 | - [食用方法](#食用方法)
 44 |   - [打开编译好的文件,开启服务(releases下载)](#打开编译好的文件开启服务releases下载)
 45 |   - [注入JS,构建通信环境(/resouces/JsEnv\_De.js)](#注入js构建通信环境resoucesjsenv_dejs)
 46 |   - [连接通信](#连接通信)
 47 |     - [I 远程调用0:](#i-远程调用0)
 48 |       - [接口传js代码让浏览器执行](#接口传js代码让浏览器执行)
 49 |     - [Ⅱ 远程调用1: 浏览器预先注册js方法 传递函数名调用](#ⅱ-远程调用1-浏览器预先注册js方法-传递函数名调用)
 50 |       - [远程调用1:无参获取值](#远程调用1无参获取值)
 51 |       - [远程调用2:带参获取值](#远程调用2带参获取值)
 52 |       - [远程调用3:带多个参获 并且使用post方式 取值](#远程调用3带多个参获-并且使用post方式-取值)
 53 |       - [远程调用4:获取页面基础信息](#远程调用4获取页面基础信息)
 54 | 
 55 | 
 56 | 
 57 | ## 目录结构
 58 | 
 59 | 
 60 | >  [main.go](https://github.com/jxhczhl/JsRpc/blob/main/main.go) (服务器的主代码)  
 61 | >  [resouces/JsEnv_De.js](https://github.com/jxhczhl/JsRpc/blob/main/resouces/JsEnv_Dev.js) (客户端注入js环境)  
 62 | >  [config.yaml](https://github.com/jxhczhl/JsRpc/blob/main/config.yaml) (可选配置文件)  
 63 | 
 64 | 
 65 | ## 基本介绍
 66 | 
 67 | 运行服务器程序和js脚本 即可让它们通信,实现调用接口执行js获取想要的值(加解密)
 68 | 
 69 | ## 实现
 70 | 
 71 | 原理:在网站的控制台新建一个WebScoket客户端链接到服务器通信,调用服务器的接口 服务器会发送信息给客户端 客户端接收到要执行的方法执行完js代码后把获得想要的内容发回给服务器 服务器接收到后再显示出来
 72 | 
 73 | > 说明:本方法可以https证书且支持wss
 74 | 
 75 | 
 76 | ## 食用方法
 77 | 
 78 | ### 打开编译好的文件,开启服务(releases下载)
 79 | 
 80 | 如图所示
 81 | 
 82 | <img width="570" alt="image" src="https://github.com/jxhczhl/JsRpc/assets/41224971/2530274f-33b9-4ccd-8749-6431abea27b2">
 83 | 
 84 | [如需更改部分配置,请查看 "其他说明"](#其他说明)  
 85 | 
 86 | **api 简介**
 87 | 
 88 | - `/list` :查看当前连接的ws服务  (get)
 89 | - `/ws`  :浏览器注入ws连接的接口 (ws | wss)
 90 | - `/wst`  :ws测试使用-发啥回啥 (ws | wss)
 91 | - `/go` :获取数据的接口  (get | post)
 92 | - `/execjs` :传递jscode给浏览器执行 (get | post)
 93 | - `/page/cookie` :直接获取当前页面的cookie (get)
 94 | - `/page/html` :获取当前页面的html (get)
 95 | 
 96 | 说明:接口用?group分组 如 "ws://127.0.0.1:12080/ws?group={}"
 97 | 以及可选参数 clientId
 98 | clientId说明:以group分组后,如果有注册相同group的 可以传入这个id来区分客户端,如果不传 服务程序会自动生成一个。当访问调用接口时,服务程序随机发送请求到相同group的客户端里。
 99 | 
100 | //注入例子 group可以随便起名(必填)
101 | http://127.0.0.1:12080/go?group={}&action={}&param={} //这是调用的接口
102 | group填写上面注入时候的,action是注册的方法名,param是可选的参数 param可以传string类型或者object类型(会尝试用JSON.parse)
103 | 
104 | ### 注入JS,构建通信环境([/resouces/JsEnv_De.js](https://github.com/jxhczhl/JsRpc/blob/main/resouces/JsEnv_Dev.js))
105 | 
106 | 打开JsEnv 复制粘贴到网站控制台(注意:可以在浏览器开启的时候就先注入环境,不要在调试断点时候注入)
107 | 
108 | ![image](https://github.com/jxhczhl/JsRpc/assets/41224971/799fd2ce-28f6-4719-9ff8-e60da57068d7")
109 | 
110 | 
111 | 
112 | ### 连接通信
113 | 
114 | ```js
115 | // 注入环境后连接通信
116 | var demo = new Hlclient("ws://127.0.0.1:12080/ws?group=zzz");
117 | // 可选  
118 | //var demo = new Hlclient("ws://127.0.0.1:12080/ws?group=zzz&clientId=hliang/"+new Date().getTime())
119 | ```
120 | 
121 | #### I 远程调用0:
122 | 
123 | ##### 接口传js代码让浏览器执行
124 | 
125 | 浏览器已经连接上通信后 调用execjs接口就行
126 | 
127 | ```python
128 | import requests
129 | 
130 | js_code = """
131 | (function(){
132 |     console.log("test")
133 |     return "执行成功"
134 | })()
135 | """
136 | 
137 | url = "http://localhost:12080/execjs"
138 | data = {
139 |     "group": "zzz",
140 |     "code": js_code
141 | }
142 | res = requests.post(url, data=data)
143 | print(res.text)
144 | ```
145 | 
146 | ![image](https://user-images.githubusercontent.com/41224971/165704850-0a22dd7e-68ea-44fe-bda9-608c10795558.png)
147 | 
148 | #### Ⅱ 远程调用1: 浏览器预先注册js方法 传递函数名调用
149 | 
150 | ##### 远程调用1:无参获取值
151 | 
152 | ```js
153 | 
154 | // 注册一个方法 第一个参数hello为方法名,
155 | // 第二个参数为函数,resolve里面的值是想要的值(发送到服务器的)
156 | demo.regAction("hello", function (resolve) {
157 |     //这样每次调用就会返回“好困啊+随机整数”
158 |     var Js_sjz = "好困啊"+parseInt(Math.random()*1000);
159 |     resolve(Js_sjz);
160 | })
161 | 
162 | 
163 | ```
164 | 
165 | 访问接口,获得js端的返回值  
166 | http://127.0.0.1:12080/go?group=zzz&action=hello
167 | 
168 | ![image](https://github.com/jxhczhl/JsRpc/assets/41224971/5f0da051-18f3-49ac-98f8-96f408440475)
169 | 
170 | 
171 | ##### 远程调用2:带参获取值
172 | 
173 | ```js
174 | //写一个传入字符串,返回base64值的接口(调用内置函数btoa)
175 | demo.regAction("hello2", function (resolve,param) {
176 |     //这样添加了一个param参数,http接口带上它,这里就能获得
177 |     var base666 = btoa(param)
178 |     resolve(base666);
179 | })
180 | ```
181 | 
182 | 访问接口,获得js端的返回值
183 | http://127.0.0.1:12080/go?group=zzz&action=hello2&param=123456  
184 | 
185 | ![image](https://github.com/jxhczhl/JsRpc/assets/41224971/91b993ae-7831-4b65-8553-f90e19cc7ebe)
186 | 
187 | 
188 | ##### 远程调用3:带多个参获 并且使用post方式 取值
189 | 
190 | ```js
191 | //假设有一个函数 需要传递两个参数
192 | function hlg(User,Status){
193 |     return User+"说:"+Status;
194 | }
195 | 
196 | demo.regAction("hello3", function (resolve,param) {
197 |     //这里还是param参数 param里面的key 是先这里写,但到时候传接口就必须对应的上
198 |     res=hlg(param["user"],param["status"])
199 |     resolve(res);
200 | })
201 | ```
202 | 
203 | 访问接口,获得js端的返回值
204 | 
205 | ```python
206 | url = "http://127.0.0.1:12080/go"
207 | data = {
208 |     "group": "zzz",
209 |     "action": "hello3",
210 |     "param": json.dumps({"user":"黑脸怪","status":"好困啊"})
211 | }
212 | print(data["param"]) #dumps后就是长这样的字符串{"user": "\u9ed1\u8138\u602a", "status": "\u597d\u56f0\u554a"}
213 | res=requests.post(url, data=data) #这里换get也是可以的
214 | print(res.text)
215 | ```
216 | 
217 | ![image](https://github.com/jxhczhl/JsRpc/assets/41224971/5af9bf90-cdfd-4d89-a3c0-a11a54ca7969)
218 | 
219 | 
220 | ##### 远程调用4:获取页面基础信息
221 | 
222 | ```python
223 | resp = requests.get("http://127.0.0.1:12080/page/html?group=zzz")     # 直接获取当前页面的html
224 | resp = requests.get("http://127.0.0.1:12080/page/cookie?group=zzz")   # 直接获取当前页面的cookie
225 | ```
226 | 
227 | 
228 | list接口可查看当前注入的客户端信息  
229 | <img width="321" alt="image" src="https://github.com/jxhczhl/JsRpc/assets/41224971/5b2ac7af-f6f0-4569-ac64-553ea41be387">
230 | 
231 | ---
232 | ##### 作者是个人开发者,开发和写文档工作量繁重。
233 | 
234 | ##### 如果本项目对您有所帮助,不妨打赏一下 :)
235 | 
236 | 
237 | <img width="250" alt="image" src="https://github.com/user-attachments/assets/04420785-ca81-474b-aa19-fc83ca7363a8">
238 | 


--------------------------------------------------------------------------------
/config.yaml:
--------------------------------------------------------------------------------
 1 | BasicListen: "0.0.0.0:12080" # 不想暴露公网/局域网可改成127.0.0.1:port
 2 | HttpsServices:
 3 |   IsEnable: false # 是否启用https/wss服务
 4 |   HttpsListen: "0.0.0.0:12443"
 5 |   PemPath: "hl98.cn.pem"
 6 |   KeyPath: "hl98.cn.key"
 7 | 
 8 | DefaultTimeOut: 30 # 当执行端没有返回值时,等待%d秒返回超时
 9 | CloseLog: false # 关闭一些日志
10 | CloseWebLog: false # 关闭Web服务访问的日志
11 | Mode: release  # release:发布版本   debug:调试版   test:测试版本
12 | Cors: false    # 是否开启CorsMiddleWare中间件--默认不开启
13 | RouterReplace:
14 |   IsEnable: false # 是否启用路径替换
15 |   ReplaceRoute: "/aaa" # 将访问aaa的路径替换成/根路径,访问/aaa/go 相当于直接访问/go


--------------------------------------------------------------------------------
/config/config.go:
--------------------------------------------------------------------------------
 1 | package config
 2 | 
 3 | import (
 4 | 	"JsRpc/utils"
 5 | 	"errors"
 6 | 	"flag"
 7 | 	log "github.com/sirupsen/logrus"
 8 | 	"gopkg.in/yaml.v3"
 9 | 	"os"
10 | )
11 | 
12 | var DefaultTimeout = 30
13 | 
14 | func ReadConf() ConfStruct {
15 | 	var ConfigPath string
16 | 	// 定义命令行参数-c,后面跟着的是默认值以及参数说明
17 | 	flag.StringVar(&ConfigPath, "c", "config.yaml", "指定配置文件的路径")
18 | 	// 解析命令行参数
19 | 	flag.Parse()
20 | 
21 | 	conf, err := initConf(ConfigPath)
22 | 	if err != nil {
23 | 		log.Warning(
24 | 			"使用默认配置运行 ", err.Error(), "\n",
25 | 			"配置参考 https://github.com/jxhczhl/JsRpc/blob/main/config.yaml")
26 | 	}
27 | 	return conf
28 | }
29 | 
30 | func initConf(path string) (ConfStruct, error) {
31 | 	defaultConf := ConfStruct{
32 | 		BasicListen: `:12080`,
33 | 		HttpsServices: HttpsConfig{
34 | 			IsEnable:    false,
35 | 			HttpsListen: `:12443`,
36 | 		},
37 | 		DefaultTimeOut: DefaultTimeout,
38 | 		RouterReplace: RouterReplace{
39 | 			IsEnable:     false,
40 | 			ReplaceRoute: "",
41 | 		},
42 | 	}
43 | 	if !utils.IsExists(path) {
44 | 		return defaultConf, errors.New("config path not found")
45 | 	}
46 | 
47 | 	file, _ := os.Open(path) // 因为上面已经判断了 文件是存在的 所以这里不用捕获错误
48 | 	defer func(file *os.File) {
49 | 		err := file.Close()
50 | 		if err != nil {
51 | 		}
52 | 	}(file)
53 | 	conf := ConfStruct{}
54 | 	decoder := yaml.NewDecoder(file)
55 | 	err := decoder.Decode(&conf)
56 | 	if err != nil {
57 | 		return defaultConf, err
58 | 	}
59 | 	DefaultTimeout = conf.DefaultTimeOut
60 | 	return conf, nil
61 | }
62 | 
63 | type ConfStruct struct {
64 | 	BasicListen    string        `yaml:"BasicListen"`
65 | 	HttpsServices  HttpsConfig   `yaml:"HttpsServices"`
66 | 	DefaultTimeOut int           `yaml:"DefaultTimeOut"`
67 | 	CloseLog       bool          `yaml:"CloseLog"`
68 | 	CloseWebLog    bool          `yaml:"CloseWebLog"`
69 | 	Mode           string        `yaml:"Mode"`
70 | 	Cors           bool          `yaml:"Cors"`
71 | 	RouterReplace  RouterReplace `yaml:"RouterReplace"`
72 | }
73 | 
74 | // HttpsConfig 代表HTTPS相关配置的结构体
75 | type HttpsConfig struct {
76 | 	IsEnable    bool   `yaml:"IsEnable"`
77 | 	HttpsListen string `yaml:"HttpsListen"`
78 | 	PemPath     string `yaml:"PemPath"`
79 | 	KeyPath     string `yaml:"KeyPath"`
80 | }
81 | 
82 | type RouterReplace struct {
83 | 	IsEnable     bool   `yaml:"IsEnable"`
84 | 	ReplaceRoute string `yaml:"ReplaceRoute"`
85 | }
86 | 


--------------------------------------------------------------------------------
/core/api.go:
--------------------------------------------------------------------------------
  1 | package core
  2 | 
  3 | import (
  4 | 	"JsRpc/config"
  5 | 	"JsRpc/utils"
  6 | 	"encoding/json"
  7 | 	"github.com/gin-gonic/gin"
  8 | 	"github.com/gorilla/websocket"
  9 | 	log "github.com/sirupsen/logrus"
 10 | 	"github.com/unrolled/secure"
 11 | 	"net/http"
 12 | 	"strconv"
 13 | 	"strings"
 14 | 	"sync"
 15 | )
 16 | 
 17 | var (
 18 | 	upGrader = websocket.Upgrader{
 19 | 		CheckOrigin: func(r *http.Request) bool { return true },
 20 | 	}
 21 | 	rwMu      sync.RWMutex
 22 | 	hlSyncMap sync.Map
 23 | )
 24 | 
 25 | // Message 请求和传递请求
 26 | type Message struct {
 27 | 	Action    string `json:"action"`
 28 | 	MessageId string `json:"message_id"`
 29 | 	Param     string `json:"param"`
 30 | }
 31 | type MessageResponse struct {
 32 | 	Action       string `json:"action"`
 33 | 	MessageId    string `json:"message_id"`
 34 | 	ResponseData string `json:"response_data"`
 35 | }
 36 | type ApiParam struct {
 37 | 	GroupName string `form:"group" json:"group"`
 38 | 	ClientId  string `form:"clientId" json:"clientId"`
 39 | 	Action    string `form:"action" json:"action"`
 40 | 	Param     string `form:"param" json:"param"`
 41 | 	Code      string `form:"code" json:"code"` // 直接eval的代码
 42 | }
 43 | 
 44 | // Clients 客户端信息
 45 | type Clients struct {
 46 | 	clientGroup string
 47 | 	clientId    string
 48 | 	clientIp    string                            // 客户端ip
 49 | 	actionData  map[string]map[string]chan string // {"action":{"消息id":消息管道}}
 50 | 	clientWs    *websocket.Conn
 51 | }
 52 | 
 53 | func (c *Clients) readFromMap(funcName string, MessageId string) chan string {
 54 | 	rwMu.RLock()
 55 | 	defer rwMu.RUnlock()
 56 | 	return c.actionData[funcName][MessageId]
 57 | }
 58 | func (c *Clients) writeToMap(funcName string, MessageId string, msg string) {
 59 | 	rwMu.Lock()
 60 | 	defer rwMu.Unlock()
 61 | 	c.actionData[funcName][MessageId] <- msg
 62 | }
 63 | 
 64 | // NewClient  initializes a new Clients instance
 65 | func NewClient(group string, uid string, ws *websocket.Conn, clientIp string) *Clients {
 66 | 	return &Clients{
 67 | 		clientGroup: group,
 68 | 		clientId:    uid,
 69 | 		actionData:  make(map[string]map[string]chan string), // action有消息后就保存到chan里
 70 | 		clientWs:    ws,
 71 | 		clientIp:    clientIp,
 72 | 	}
 73 | }
 74 | 
 75 | func GinJsonMsg(c *gin.Context, code int, msg string) {
 76 | 	c.JSON(code, gin.H{"status": code, "data": msg})
 77 | 	return
 78 | }
 79 | 
 80 | // ws, provides inject function for a job
 81 | func ws(c *gin.Context) {
 82 | 	group, clientId := c.Query("group"), c.Query("clientId")
 83 | 	//必须要group名字,不然不让它连接ws
 84 | 	if group == "" {
 85 | 		return
 86 | 	}
 87 | 	clientIP := c.ClientIP()
 88 | 
 89 | 	//没有给客户端id的话 就用uuid给他生成一个
 90 | 	if clientId == "" {
 91 | 		clientId = utils.GetUUID()
 92 | 	}
 93 | 	wsClient, err := upGrader.Upgrade(c.Writer, c.Request, nil)
 94 | 	if err != nil {
 95 | 		log.Error("websocket err:", err)
 96 | 		return
 97 | 	}
 98 | 	client := NewClient(group, clientId, wsClient, clientIP)
 99 | 	hlSyncMap.Store(group+"->"+clientId, client)
100 | 	utils.LogPrint("新上线group:" + group + ",clientId:->" + clientId)
101 | 	clientNameJson := `{"registerId":"` + clientId + `"}`
102 | 	err = wsClient.WriteMessage(1, []byte(clientNameJson))
103 | 	if err != nil {
104 | 		log.Warning("注册成功,但发送回执信息失败")
105 | 	}
106 | 	for {
107 | 		//等待数据
108 | 		_, message, err := wsClient.ReadMessage()
109 | 		if err != nil {
110 | 			break
111 | 		}
112 | 		// 将得到的数据转成结构体
113 | 		messageStruct := MessageResponse{}
114 | 		err = json.Unmarshal(message, &messageStruct)
115 | 		if err != nil {
116 | 			log.Error("当前IP:", clientIP, "接收到的消息不是设定的格式 不做处理", err)
117 | 		}
118 | 		action := messageStruct.Action
119 | 		messageId := messageStruct.MessageId
120 | 		msg := messageStruct.ResponseData
121 | 		// 这里直接给管道塞数据,那么之前发送的时候要初始化好
122 | 		if client.readFromMap(action, messageId) == nil {
123 | 			log.Warning("当前IP:", clientIP, "当前消息id:", messageId, " 已被超时释放,回调的数据不做处理")
124 | 		} else {
125 | 			client.writeToMap(action, messageId, msg)
126 | 		}
127 | 		if len(msg) > 100 {
128 | 			utils.LogPrint("id", messageId, "get_message:", msg[:101]+"......")
129 | 		} else {
130 | 			utils.LogPrint("IP", clientIP, "id", messageId, "get_message:", msg)
131 | 		}
132 | 
133 | 	}
134 | 	defer func(ws *websocket.Conn) {
135 | 		_ = ws.Close()
136 | 		utils.LogPrint(group+"->"+clientId, "下线了")
137 | 		hlSyncMap.Range(func(key, value interface{}) bool {
138 | 			//client, _ := value.(*Clients)
139 | 			if key == group+"->"+clientId {
140 | 				hlSyncMap.Delete(key)
141 | 			}
142 | 			return true
143 | 		})
144 | 	}(wsClient)
145 | }
146 | 
147 | func wsTest(c *gin.Context) {
148 | 	testClient, _ := upGrader.Upgrade(c.Writer, c.Request, nil)
149 | 	for {
150 | 		//等待数据
151 | 		_, message, err := testClient.ReadMessage()
152 | 		if err != nil {
153 | 			break
154 | 		}
155 | 		msg := string(message)
156 | 		utils.LogPrint("接收到测试消息", msg)
157 | 		_ = testClient.WriteMessage(websocket.BinaryMessage, []byte(msg))
158 | 	}
159 | 	defer func(ws *websocket.Conn) {
160 | 		_ = ws.Close()
161 | 	}(testClient)
162 | }
163 | 
164 | func checkRequestParam(c *gin.Context) (*Clients, string) {
165 | 	var RequestParam ApiParam
166 | 	if err := c.ShouldBind(&RequestParam); err != nil {
167 | 		return &Clients{}, err.Error()
168 | 	}
169 | 	group := RequestParam.GroupName
170 | 	if group == "" {
171 | 		return &Clients{}, "需要传入group"
172 | 	}
173 | 	clientId := RequestParam.ClientId
174 | 	client := getRandomClient(group, clientId)
175 | 	if client == nil {
176 | 		return &Clients{}, "没有找到对应的group或clientId,请通过list接口查看现有的注入"
177 | 	}
178 | 	return client, ""
179 | }
180 | 
181 | func GetCookie(c *gin.Context) {
182 | 	client, errorStr := checkRequestParam(c)
183 | 	if errorStr != "" {
184 | 		GinJsonMsg(c, http.StatusBadRequest, errorStr)
185 | 		return
186 | 	}
187 | 	c3 := make(chan string, 1)
188 | 	go client.GQueryFunc("_execjs", utils.ConcatCode("document.cookie"), c3, client.clientId)
189 | 	c.JSON(http.StatusOK, gin.H{"status": 200, "group": client.clientGroup, "clientId": client.clientId, "data": <-c3})
190 | }
191 | 
192 | func GetHtml(c *gin.Context) {
193 | 	client, errorStr := checkRequestParam(c)
194 | 	if errorStr != "" {
195 | 		GinJsonMsg(c, http.StatusBadRequest, errorStr)
196 | 		return
197 | 	}
198 | 	c3 := make(chan string, 1)
199 | 	go client.GQueryFunc("_execjs", utils.ConcatCode("document.documentElement.outerHTML"), c3, client.clientId)
200 | 	c.JSON(http.StatusOK, gin.H{"status": 200, "group": client.clientGroup, "clientId": client.clientId, "data": <-c3})
201 | }
202 | 
203 | // GetResult 接收web请求参数,并发给客户端获取结果
204 | func getResult(c *gin.Context) {
205 | 	var RequestParam ApiParam
206 | 	if err := c.ShouldBind(&RequestParam); err != nil {
207 | 		GinJsonMsg(c, http.StatusBadRequest, err.Error())
208 | 		return
209 | 	}
210 | 	action := RequestParam.Action
211 | 	if action == "" {
212 | 		GinJsonMsg(c, http.StatusOK, "请传入action来调用客户端方法")
213 | 		return
214 | 	}
215 | 	client, errorStr := checkRequestParam(c)
216 | 	if errorStr != "" {
217 | 		GinJsonMsg(c, http.StatusBadRequest, errorStr)
218 | 		return
219 | 	}
220 | 	c2 := make(chan string, 1)
221 | 	go client.GQueryFunc(action, RequestParam.Param, c2, client.clientIp)
222 | 	//把管道传过去,获得值就返回了
223 | 	c.JSON(http.StatusOK, gin.H{"status": 200, "group": client.clientGroup, "clientId": client.clientId, "data": <-c2})
224 | 
225 | }
226 | 
227 | func execjs(c *gin.Context) {
228 | 	var RequestParam ApiParam
229 | 	if err := c.ShouldBind(&RequestParam); err != nil {
230 | 		GinJsonMsg(c, http.StatusBadRequest, err.Error())
231 | 		return
232 | 	}
233 | 	Action := "_execjs"
234 | 	//获取参数
235 | 
236 | 	JsCode := RequestParam.Code
237 | 	if JsCode == "" {
238 | 		GinJsonMsg(c, http.StatusBadRequest, "请传入代码")
239 | 		return
240 | 	}
241 | 	client, errorStr := checkRequestParam(c)
242 | 	if errorStr != "" {
243 | 		GinJsonMsg(c, http.StatusBadRequest, errorStr)
244 | 		return
245 | 	}
246 | 	c2 := make(chan string)
247 | 	go client.GQueryFunc(Action, JsCode, c2, client.clientIp)
248 | 	c.JSON(200, gin.H{"status": "200", "group": client.clientGroup, "name": client.clientId, "data": <-c2})
249 | 
250 | }
251 | 
252 | func getList(c *gin.Context) {
253 | 	var data = make(map[string][]string)
254 | 	hlSyncMap.Range(func(_, value interface{}) bool {
255 | 		client, ok := value.(*Clients)
256 | 		if !ok {
257 | 			return true // 继续遍历
258 | 		}
259 | 		group := client.clientGroup
260 | 		data[group] = append(data[group], client.clientId)
261 | 		return true
262 | 	})
263 | 	c.JSON(http.StatusOK, gin.H{"status": 200, "data": data})
264 | }
265 | 
266 | func index(c *gin.Context) {
267 | 	//c.String(200, "你好,我是黑脸怪~")
268 | 	htmlContent := `
269 | 		<!DOCTYPE html>
270 | 		<html>
271 | 		<head><title>欢迎使用JsRpc</title></head>
272 | 		<body>
273 | 			你好,我是黑脸怪~
274 | 			<p>微信:hl98_cn</p>
275 | 		</body>
276 | 		</html>
277 | 		`
278 | 	// 返回 HTML 页面
279 | 	c.Data(200, "text/html; charset=utf-8", []byte(htmlContent))
280 | }
281 | 
282 | func tlsHandler(HttpsHost string) gin.HandlerFunc {
283 | 	return func(c *gin.Context) {
284 | 		secureMiddleware := secure.New(secure.Options{
285 | 			SSLRedirect: true,
286 | 			SSLHost:     HttpsHost,
287 | 		})
288 | 		err := secureMiddleware.Process(c.Writer, c.Request)
289 | 		if err != nil {
290 | 			c.Abort()
291 | 			return
292 | 		}
293 | 		c.Next()
294 | 	}
295 | }
296 | 
297 | func getGinMode(mode string) string {
298 | 	switch mode {
299 | 	case "release":
300 | 		return gin.ReleaseMode
301 | 	case "debug":
302 | 		return gin.DebugMode
303 | 	case "test":
304 | 		return gin.TestMode
305 | 	}
306 | 	return gin.ReleaseMode // 默认就是release模式
307 | }
308 | 
309 | func setupRouters(conf config.ConfStruct) *gin.Engine {
310 | 	router := gin.Default()
311 | 	if conf.Cors { // 是否开启cors中间件
312 | 		router.Use(CorsMiddleWare())
313 | 	}
314 | 	if conf.RouterReplace.IsEnable {
315 | 		router.Use(RouteReplace(router, conf.RouterReplace.ReplaceRoute))
316 | 	}
317 | 	return router
318 | }
319 | 
320 | func InitAPI(conf config.ConfStruct) {
321 | 	if conf.CloseWebLog {
322 | 		// 将默认的日志输出器设置为空
323 | 		gin.DefaultWriter = utils.LogWriter{}
324 | 	}
325 | 	gin.SetMode(getGinMode(conf.Mode))
326 | 	router := setupRouters(conf)
327 | 
328 | 	setJsRpcRouters(router) // 核心路由
329 | 
330 | 	var sb strings.Builder
331 | 	sb.WriteString("当前监听地址:")
332 | 	sb.WriteString(conf.BasicListen)
333 | 
334 | 	sb.WriteString(" ssl启用状态:")
335 | 	sb.WriteString(strconv.FormatBool(conf.HttpsServices.IsEnable))
336 | 
337 | 	if conf.HttpsServices.IsEnable {
338 | 		sb.WriteString(" https监听地址:")
339 | 		sb.WriteString(conf.HttpsServices.HttpsListen)
340 | 		router.Use(tlsHandler(conf.HttpsServices.HttpsListen))
341 | 		go func() {
342 | 			err := router.RunTLS(
343 | 				conf.HttpsServices.HttpsListen,
344 | 				conf.HttpsServices.PemPath,
345 | 				conf.HttpsServices.KeyPath,
346 | 			)
347 | 			if err != nil {
348 | 				log.Error(err)
349 | 			}
350 | 		}()
351 | 	}
352 | 	log.Infoln(sb.String())
353 | 
354 | 	err := router.Run(conf.BasicListen)
355 | 	if err != nil {
356 | 		log.Errorln("服务启动失败..")
357 | 	}
358 | }
359 | 


--------------------------------------------------------------------------------
/core/engine.go:
--------------------------------------------------------------------------------
  1 | package core
  2 | 
  3 | import (
  4 | 	"JsRpc/config"
  5 | 	"JsRpc/utils"
  6 | 	"context"
  7 | 	"encoding/json"
  8 | 	log "github.com/sirupsen/logrus"
  9 | 	"math/rand"
 10 | 	"time"
 11 | )
 12 | 
 13 | // GQueryFunc 发送请求到客户端
 14 | func (c *Clients) GQueryFunc(funcName string, param string, resChan chan<- string, clientIp string) {
 15 | 	if c.actionData[funcName] == nil {
 16 | 		rwMu.Lock()
 17 | 		c.actionData[funcName] = make(map[string]chan string)
 18 | 		rwMu.Unlock()
 19 | 	}
 20 | 	var MessageId string
 21 | 	for {
 22 | 		MessageId = utils.GetUUID()
 23 | 		if c.readFromMap(funcName, MessageId) == nil {
 24 | 			rwMu.Lock()
 25 | 			c.actionData[funcName][MessageId] = make(chan string, 1)
 26 | 			rwMu.Unlock()
 27 | 			break
 28 | 		}
 29 | 		utils.LogPrint("存在的消息id,跳过")
 30 | 	}
 31 | 	// 确保资源释放
 32 | 	defer func() {
 33 | 		rwMu.Lock()
 34 | 		delete(c.actionData[funcName], MessageId)
 35 | 		rwMu.Unlock()
 36 | 		close(resChan)
 37 | 	}()
 38 | 
 39 | 	// 构造消息并发送
 40 | 	WriteData := Message{Param: param, MessageId: MessageId, Action: funcName}
 41 | 	data, err := json.Marshal(WriteData)
 42 | 	if err != nil {
 43 | 		log.Error("当前IP:", clientIp, err, "JSON序列化失败")
 44 | 		resChan <- "JSON序列化失败"
 45 | 		return
 46 | 	}
 47 | 
 48 | 	rwMu.Lock()
 49 | 	err = c.clientWs.WriteMessage(1, data)
 50 | 	rwMu.Unlock()
 51 | 	if err != nil {
 52 | 		log.Error("当前IP:", clientIp, err, "写入数据失败")
 53 | 		resChan <- "rpc发送数据失败"
 54 | 		return
 55 | 	}
 56 | 	// 使用 context 控制超时
 57 | 	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(config.DefaultTimeout)*time.Second)
 58 | 	defer cancel()
 59 | 	resultChan := c.readFromMap(funcName, MessageId)
 60 | 	if resultChan == nil {
 61 | 		resChan <- "消息ID对应的管道不存在"
 62 | 		return
 63 | 	}
 64 | 	select {
 65 | 	case res := <-resultChan:
 66 | 		resChan <- res
 67 | 	case <-ctx.Done():
 68 | 		utils.LogPrint("当前IP:", clientIp, "超时了。", MessageId)
 69 | 		resChan <- "获取结果超时 timeout"
 70 | 	}
 71 | 
 72 | }
 73 | 
 74 | func getRandomClient(group string, clientId string) *Clients {
 75 | 	var client *Clients
 76 | 	// 不传递clientId时候,从group分组随便拿一个
 77 | 	if clientId != "" {
 78 | 		clientName, ok := hlSyncMap.Load(group + "->" + clientId)
 79 | 		if ok == false {
 80 | 			return nil
 81 | 		}
 82 | 		client, _ = clientName.(*Clients)
 83 | 		return client
 84 | 	}
 85 | 	groupClients := make([]*Clients, 0)
 86 | 	//循环读取syncMap 获取group名字的
 87 | 	hlSyncMap.Range(func(_, value interface{}) bool {
 88 | 		tmpClients, ok := value.(*Clients)
 89 | 		if !ok {
 90 | 			return true
 91 | 		}
 92 | 		if tmpClients.clientGroup == group {
 93 | 			groupClients = append(groupClients, tmpClients)
 94 | 		}
 95 | 		return true
 96 | 	})
 97 | 	if len(groupClients) == 0 {
 98 | 		return nil
 99 | 	}
100 | 	// 使用随机数发生器
101 | 	r := rand.New(rand.NewSource(time.Now().UnixNano()))
102 | 	randomIndex := r.Intn(len(groupClients))
103 | 	client = groupClients[randomIndex]
104 | 	return client
105 | 
106 | }
107 | 


--------------------------------------------------------------------------------
/core/middlewares.go:
--------------------------------------------------------------------------------
 1 | package core
 2 | 
 3 | import (
 4 | 	"github.com/gin-gonic/gin"
 5 | 	"strings"
 6 | )
 7 | 
 8 | func CorsMiddleWare() gin.HandlerFunc {
 9 | 	return func(context *gin.Context) {
10 | 		method := context.Request.Method
11 | 		origin := context.Request.Header.Get("Origin") //请求头部
12 | 		if origin != "" {
13 | 			//接收客户端发送的origin (重要!)
14 | 			context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
15 | 
16 | 			//服务器支持的所有跨域请求的方法
17 | 			context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
18 | 			//允许跨域设置可以返回其他子段,可以自定义字段
19 | 			context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
20 | 			// 允许浏览器(客户端)可以解析的头部 (重要)
21 | 			context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
22 | 			//设置缓存时间
23 | 			//c.Header("Access-Control-Max-Age", "172800")
24 | 			//允许客户端传递校验信息比如 cookie (重要)
25 | 			context.Header("Access-Control-Allow-Credentials", "true")
26 | 		}
27 | 
28 | 		//允许类型校验
29 | 		if method == "OPTIONS" {
30 | 			context.AbortWithStatus(200)
31 | 		} else {
32 | 			context.Next()
33 | 		}
34 | 	}
35 | 
36 | }
37 | func RouteReplace(router *gin.Engine, routeStr string) gin.HandlerFunc {
38 | 	return func(context *gin.Context) {
39 | 		// 去掉 前缀
40 | 		newPath := strings.TrimPrefix(context.Request.URL.Path, routeStr)
41 | 		if newPath == context.Request.URL.Path {
42 | 			// 如果没有匹配到前缀,直接放行
43 | 			context.Next()
44 | 			return
45 | 		}
46 | 		if newPath == "" {
47 | 			newPath = "/"
48 | 		}
49 | 		// 修改请求路径并重新处理
50 | 		context.Request.URL.Path = newPath
51 | 		router.HandleContext(context)
52 | 		context.Abort()
53 | 	}
54 | }
55 | 


--------------------------------------------------------------------------------
/core/routers.go:
--------------------------------------------------------------------------------
 1 | package core
 2 | 
 3 | import (
 4 | 	"github.com/gin-gonic/gin"
 5 | )
 6 | 
 7 | func setJsRpcRouters(router *gin.Engine) {
 8 | 	// 核心部分的的路由组
 9 | 	router.GET("/", index)
10 | 
11 | 	page := router.Group("/page")
12 | 	{
13 | 		page.GET("/cookie", GetCookie)
14 | 		page.GET("/html", GetHtml)
15 | 	}
16 | 
17 | 	rpc := router.Group("/")
18 | 	{
19 | 		rpc.GET("go", getResult)
20 | 		rpc.POST("go", getResult)
21 | 		rpc.GET("ws", ws)
22 | 		rpc.GET("wst", wsTest)
23 | 		rpc.GET("execjs", execjs)
24 | 		rpc.POST("execjs", execjs)
25 | 		rpc.GET("list", getList)
26 | 	}
27 | 
28 | }
29 | 


--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
 1 | module JsRpc
 2 | 
 3 | go 1.22.1
 4 | 
 5 | require (
 6 | 	github.com/gin-gonic/gin v1.9.1
 7 | 	github.com/google/uuid v1.6.0
 8 | 	github.com/gorilla/websocket v1.5.1
 9 | 	github.com/sirupsen/logrus v1.9.3
10 | 	github.com/unrolled/secure v1.14.0
11 | 	gopkg.in/yaml.v3 v3.0.1
12 | )
13 | 
14 | require (
15 | 	github.com/bytedance/sonic v1.9.1 // indirect
16 | 	github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
17 | 	github.com/gabriel-vasile/mimetype v1.4.2 // indirect
18 | 	github.com/gin-contrib/sse v0.1.0 // indirect
19 | 	github.com/go-playground/locales v0.14.1 // indirect
20 | 	github.com/go-playground/universal-translator v0.18.1 // indirect
21 | 	github.com/go-playground/validator/v10 v10.14.0 // indirect
22 | 	github.com/goccy/go-json v0.10.2 // indirect
23 | 	github.com/json-iterator/go v1.1.12 // indirect
24 | 	github.com/klauspost/cpuid/v2 v2.2.4 // indirect
25 | 	github.com/leodido/go-urn v1.2.4 // indirect
26 | 	github.com/mattn/go-isatty v0.0.20 // indirect
27 | 	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
28 | 	github.com/modern-go/reflect2 v1.0.2 // indirect
29 | 	github.com/pelletier/go-toml/v2 v2.0.8 // indirect
30 | 	github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
31 | 	github.com/ugorji/go/codec v1.2.11 // indirect
32 | 	golang.org/x/arch v0.3.0 // indirect
33 | 	golang.org/x/crypto v0.14.0 // indirect
34 | 	golang.org/x/net v0.17.0 // indirect
35 | 	golang.org/x/sys v0.14.0 // indirect
36 | 	golang.org/x/text v0.13.0 // indirect
37 | 	google.golang.org/protobuf v1.30.0 // indirect
38 | )
39 | 


--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
 1 | github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
 2 | github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
 3 | github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
 4 | github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
 5 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
 6 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
 7 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 8 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 9 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
10 | github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
11 | github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
12 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
13 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
14 | github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
15 | github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
16 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
17 | github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
18 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
19 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
20 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
21 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
22 | github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
23 | github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
24 | github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
25 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
26 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
27 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
28 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
29 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
30 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
31 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
32 | github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
33 | github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
34 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
35 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
36 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
37 | github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
38 | github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
39 | github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
40 | github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
41 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
42 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
43 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
44 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
45 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
46 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
47 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
48 | github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
49 | github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
50 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
51 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
52 | github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
53 | github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
54 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
55 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
56 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
57 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
58 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
59 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
60 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
61 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
62 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
63 | github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
64 | github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
65 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
66 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
67 | github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
68 | github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
69 | github.com/unrolled/secure v1.14.0 h1:u9vJTU/pR4Bny0ntLUMxdfLtmIRGvQf2sEFuA0TG9AE=
70 | github.com/unrolled/secure v1.14.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40=
71 | golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
72 | golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
73 | golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
74 | golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
75 | golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
76 | golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
77 | golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
78 | golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
79 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
80 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
81 | golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
82 | golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
83 | golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
84 | golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
85 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
86 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
87 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
88 | google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
89 | google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
90 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
91 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
92 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
93 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
94 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
95 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
96 | 


--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
 1 | package main
 2 | 
 3 | import (
 4 | 	"JsRpc/config"
 5 | 	"JsRpc/core"
 6 | 	"JsRpc/utils"
 7 | )
 8 | 
 9 | func main() {
10 | 	utils.PrintJsRpc()                // 开屏打印
11 | 	utils.InitLogger()                // 初始化日志
12 | 	baseConf := config.ReadConf()     // 读取日志信息
13 | 	utils.PrintSet(baseConf.CloseLog) // 关闭部分日志
14 | 	core.InitAPI(baseConf)            // 初始化api部分
15 | 
16 | 	utils.CloseTerminal() // 安全退出
17 | }
18 | 


--------------------------------------------------------------------------------
/resouces/JsEnv_Dev.js:
--------------------------------------------------------------------------------
  1 | var rpc_client_id, Hlclient = function (wsURL) {
  2 |     this.wsURL = wsURL;
  3 |     this.handlers = {
  4 |         _execjs: function (resolve, param) {
  5 |             var res = eval(param)
  6 |             if (!res) {
  7 |                 resolve("没有返回值")
  8 |             } else {
  9 |                 resolve(res)
 10 |             }
 11 |         }
 12 |     };
 13 |     this.socket = undefined;
 14 |     if (!wsURL) {
 15 |         throw new Error('wsURL can not be empty!!')
 16 |     }
 17 |     this.connect()
 18 | }
 19 | Hlclient.prototype.connect = function () {
 20 |     if (this.wsURL.indexOf("clientId=") === -1 && rpc_client_id) {
 21 |         this.wsURL += "&clientId=" + rpc_client_id
 22 |     }
 23 |     console.log('begin of connect to wsURL: ' + this.wsURL);
 24 |     var _this = this;
 25 |     try {
 26 |         this.socket = new WebSocket(this.wsURL);
 27 |         this.socket.onmessage = function (e) {
 28 |             _this.handlerRequest(e.data)
 29 |         }
 30 |     } catch (e) {
 31 |         console.log("connection failed,reconnect after 10s");
 32 |         setTimeout(function () {
 33 |             _this.connect()
 34 |         }, 10000)
 35 |     }
 36 |     this.socket.onclose = function () {
 37 |         console.log('rpc已关闭');
 38 |         setTimeout(function () {
 39 |             _this.connect()
 40 |         }, 10000)
 41 |     }
 42 |     this.socket.addEventListener('open', (event) => {
 43 |         console.log("rpc连接成功");
 44 |     });
 45 |     this.socket.addEventListener('error', (event) => {
 46 |         console.error('rpc连接出错,请检查是否打开服务端:', event.error);
 47 |     })
 48 | };
 49 | Hlclient.prototype.send = function (msg) {
 50 |     this.socket.send(msg)
 51 | }
 52 | Hlclient.prototype.regAction = function (func_name, func) {
 53 |     if (typeof func_name !== 'string') {
 54 |         throw new Error("an func_name must be string");
 55 |     }
 56 |     if (typeof func !== 'function') {
 57 |         throw new Error("must be function");
 58 |     }
 59 |     console.log("register func_name: " + func_name);
 60 |     this.handlers[func_name] = func;
 61 |     return true
 62 | }
 63 | Hlclient.prototype.handlerRequest = function (requestJson) {
 64 |     var _this = this;
 65 |     try {
 66 |         var result = JSON.parse(requestJson)
 67 |     } catch (error) {
 68 |         console.log("请求信息解析错误", requestJson);
 69 |         return
 70 |     }
 71 |     if (result["registerId"]) {
 72 |         rpc_client_id = result['registerId']
 73 |         return
 74 |     }
 75 |     if (!result['action'] || !result["message_id"]) {
 76 |         console.warn('没有方法或者消息id,不处理');
 77 |         return
 78 |     }
 79 |     var action = result["action"], message_id = result["message_id"]
 80 |     var theHandler = this.handlers[action];
 81 |     if (!theHandler) {
 82 |         this.sendResult(action, message_id, 'action没找到');
 83 |         return
 84 |     }
 85 |     try {
 86 |         if (!result["param"]) {
 87 |             theHandler(function (response) {
 88 |                 _this.sendResult(action, message_id, response);
 89 |             })
 90 |             return
 91 |         }
 92 |         var param = result["param"]
 93 |         try {
 94 |             param = JSON.parse(param)
 95 |         } catch (e) {
 96 |         }
 97 |         theHandler(function (response) {
 98 |             _this.sendResult(action, message_id, response);
 99 |         }, param)
100 |     } catch (e) {
101 |         console.log("error: " + e);
102 |         _this.sendResult(action, message_id, e);
103 |     }
104 | }
105 | Hlclient.prototype.sendResult = function (action, message_id, e) {
106 |     if (typeof e === 'object' && e !== null) {
107 |         try {
108 |             e = JSON.stringify(e)
109 |         } catch (v) {
110 |             console.log(v)//不是json无需操作
111 |         }
112 |     }
113 |     this.send(JSON.stringify({"action": action, "message_id": message_id, "response_data": e}));
114 | }


--------------------------------------------------------------------------------
/resouces/WeChat_Dev.js:
--------------------------------------------------------------------------------
  1 | var rpc_client_id, Hlclient = function (wsURL) {
  2 |     this.wsURL = wsURL;
  3 |     this.handlers = {
  4 |         _execjs: function (resolve, param) {
  5 |             var res = eval(param)
  6 |             resolve(res || "没有返回值")
  7 |         }
  8 |     };
  9 |     this.socket = undefined;
 10 |     this.isWechat = typeof wx !== 'undefined'; // 新增环境判断
 11 | 
 12 |     if (!wsURL) throw new Error('wsURL can not be empty!!');
 13 | 
 14 |     // 微信环境读取持久化的clientId
 15 |     if (this.isWechat && wx.getStorageSync('rpc_client_id')) {
 16 |         rpc_client_id = wx.getStorageSync('rpc_client_id');
 17 |     }
 18 | 
 19 |     this.connect();
 20 | }
 21 | 
 22 | Hlclient.prototype.connect = function () {
 23 |     var _this = this;
 24 | 
 25 |     // 处理clientId参数
 26 |     if (this.wsURL.indexOf("clientId=") === -1 && rpc_client_id) {
 27 |         this.wsURL += "&clientId=" + rpc_client_id;
 28 |     }
 29 | 
 30 |     console.log('begin connect to:', this.wsURL);
 31 | 
 32 |     try {
 33 |         if (this.isWechat) {
 34 |             // 微信环境使用wx API
 35 |             this.socket = wx.connectSocket({
 36 |                 url: this.wsURL,
 37 |                 success() {
 38 |                     console.log('微信WS连接建立成功');
 39 |                 },
 40 |                 fail(err) {
 41 |                     console.error('微信WS连接失败:', err);
 42 |                     _this.reconnect();
 43 |                 }
 44 |             });
 45 | 
 46 |             // 微信事件监听
 47 |             wx.onSocketMessage(function (res) {
 48 |                 _this.handlerRequest(res.data);
 49 |             });
 50 | 
 51 |             wx.onSocketOpen(function () {
 52 |                 console.log("rpc连接成功");
 53 |             });
 54 | 
 55 |             wx.onSocketError(function (err) {
 56 |                 console.error('rpc连接出错:', err);
 57 |             });
 58 | 
 59 |             wx.onSocketClose(function () {
 60 |                 console.log('rpc连接关闭');
 61 |                 _this.reconnect();
 62 |             });
 63 | 
 64 |         } else {
 65 |             // 浏览器环境
 66 |             this.socket = new WebSocket(this.wsURL);
 67 | 
 68 |             this.socket.onmessage = function (e) {
 69 |                 _this.handlerRequest(e.data);
 70 |             }
 71 | 
 72 |             this.socket.onclose = function () {
 73 |                 console.log('rpc已关闭');
 74 |                 _this.reconnect();
 75 |             }
 76 | 
 77 |             this.socket.addEventListener('open', () => {
 78 |                 console.log("rpc连接成功");
 79 |             });
 80 | 
 81 |             this.socket.addEventListener('error', (err) => {
 82 |                 console.error('rpc连接出错:', err);
 83 |             });
 84 |         }
 85 |     } catch (e) {
 86 |         console.log("connection failed:", e);
 87 |         this.reconnect();
 88 |     }
 89 | };
 90 | 
 91 | Hlclient.prototype.reconnect = function () {
 92 |     console.log("10秒后尝试重连...");
 93 |     var _this = this;
 94 |     setTimeout(function () {
 95 |         _this.connect();
 96 |     }, 10000);
 97 | };
 98 | 
 99 | Hlclient.prototype.send = function (msg) {
100 |     if (this.isWechat) {
101 |         // 微信环境发送消息
102 |         if (this.socket && this.socket.readyState === 1) {
103 |             wx.sendSocketMessage({
104 |                 data: msg,
105 |                 fail(err) {
106 |                     console.error('消息发送失败:', err);
107 |                 }
108 |             });
109 |         }
110 |     } else {
111 |         // 浏览器环境
112 |         if (this.socket.readyState === WebSocket.OPEN) {
113 |             this.socket.send(msg);
114 |         }
115 |     }
116 | };
117 | 
118 | Hlclient.prototype.regAction = function (func_name, func) {
119 |     if (typeof func_name !== 'string') throw new Error("func_name must be string");
120 |     if (typeof func !== 'function') throw new Error("must be function");
121 |     console.log("register func:", func_name);
122 |     this.handlers[func_name] = func;
123 |     return true;
124 | };
125 | 
126 | Hlclient.prototype.handlerRequest = function (requestJson) {
127 |     var _this = this;
128 |     try {
129 |         var result = JSON.parse(requestJson);
130 |         // 微信环境持久化clientId
131 |         if (result["registerId"]) {
132 |             rpc_client_id = result['registerId'];
133 |             if (this.isWechat) {
134 |                 wx.setStorageSync('rpc_client_id', rpc_client_id);
135 |             }
136 |             return;
137 |         }
138 | 
139 |         if (!result['action'] || !result["message_id"]) {
140 |             console.warn('Invalid request:', result);
141 |             return;
142 |         }
143 | 
144 |         var action = result["action"],
145 |             message_id = result["message_id"],
146 |             param = result["param"];
147 | 
148 |         try { param = JSON.parse(param); } catch (e) { }
149 | 
150 |         var handler = this.handlers[action];
151 |         if (!handler) {
152 |             return this.sendResult(action, message_id, 'Action not found');
153 |         }
154 | 
155 |         handler(function (response) {
156 |             _this.sendResult(action, message_id, response);
157 |         }, param);
158 | 
159 |     } catch (error) {
160 |         console.log("处理请求出错:", error);
161 |         this.sendResult(action, message_id, error.message);
162 |     }
163 | };
164 | 
165 | Hlclient.prototype.sendResult = function (action, message_id, data) {
166 |     if (typeof data === 'object') {
167 |         try { data = JSON.stringify(data); } catch (e) { }
168 |     }
169 |     var response = JSON.stringify({
170 |         action: action,
171 |         message_id: message_id,
172 |         response_data: data
173 |     });
174 |     this.send(response);
175 | };
176 | 


--------------------------------------------------------------------------------
/test/muilte_request.py:
--------------------------------------------------------------------------------
 1 | import requests,time
 2 | from concurrent.futures.thread import ThreadPoolExecutor
 3 | tp = ThreadPoolExecutor(max_workers=50)
 4 | def fetch_response(url):
 5 |     response = requests.get(url)
 6 |     return url,response.text
 7 | 
 8 | def callback_successed(f):
 9 |     print(f.result())
10 | 
11 | start_timestamp = time.time()
12 | for i in range(100):
13 |     tp.submit(fetch_response,"http://localhost:12080/go?group=zzz&name=hlg&action=hello&param={}".format(i)).add_done_callback(callback_successed)
14 | tp.shutdown()
15 | end_timestamp = time.time()
16 | 
17 | print("每个请求时间开销:{}ms".format(round(end_timestamp-start_timestamp,3) *1000 / 100))


--------------------------------------------------------------------------------
/test/register_function.js:
--------------------------------------------------------------------------------
1 | hlc = new Hlclient("ws://127.0.0.1:12080/ws?group=zzz&name=hlg");
2 | 
3 | 
4 | hlc.regAction("hello", function (resolve,param) {
5 |     var base666 = btoa(param)
6 |     resolve(base666 + "**" + atob(base666));
7 | 
8 | })


--------------------------------------------------------------------------------
/utils/code.go:
--------------------------------------------------------------------------------
1 | package utils
2 | 
3 | import "fmt"
4 | 
5 | func ConcatCode(code string) string {
6 | 	// 拼接页面元素的js
7 | 	return fmt.Sprintf("(function(){return %s;})()", code)
8 | }
9 | 


--------------------------------------------------------------------------------
/utils/file.go:
--------------------------------------------------------------------------------
 1 | package utils
 2 | 
 3 | import (
 4 | 	"fmt"
 5 | 	"os"
 6 | )
 7 | 
 8 | func IsExists(root string) bool {
 9 | 	// 判断文件或者文件夹是否存在
10 | 	_, err := os.Stat(root)
11 | 	if err == nil {
12 | 		return true
13 | 	}
14 | 	if os.IsNotExist(err) {
15 | 		return false
16 | 	}
17 | 	return false
18 | }
19 | 
20 | func PrintJsRpc() {
21 | 	JsRpc := "       __       _______..______      .______     ______ \n      |  |     /       ||   _  \\     |   _  \\   /      |\n      |  |    |   (----`|  |_)  |    |  |_)  | |  ,----'\n.--.  |  |     \\   \\    |      /     |   ___/  |  |     \n|  `--'  | .----)   |   |  |\\  \\----.|  |      |  `----.\n \\______/  |_______/    | _| `._____|| _|       \\______|\n                                                        \n"
22 | 	fmt.Print(JsRpc)
23 | }
24 | 


--------------------------------------------------------------------------------
/utils/hash.go:
--------------------------------------------------------------------------------
 1 | package utils
 2 | 
 3 | import "github.com/google/uuid"
 4 | 
 5 | func GetUUID() string {
 6 | 	u := uuid.New()
 7 | 	key := u.String()
 8 | 	return key
 9 | }
10 | 


--------------------------------------------------------------------------------
/utils/logger.go:
--------------------------------------------------------------------------------
 1 | package utils
 2 | 
 3 | import (
 4 | 	log "github.com/sirupsen/logrus"
 5 | )
 6 | 
 7 | var isPrint = true
 8 | 
 9 | func InitLogger() {
10 | 	log.SetFormatter(&log.TextFormatter{
11 | 		ForceColors:     true, // 强制终端输出带颜色日志
12 | 		FullTimestamp:   true, // 显示完整时间戳
13 | 		TimestampFormat: "2006-01-02 15:04:05",
14 | 		DisableQuote:    true,
15 | 	})
16 | }
17 | 
18 | func PrintSet(closeLog bool) {
19 | 	if closeLog {
20 | 		isPrint = false
21 | 	}
22 | }
23 | 
24 | type LogWriter struct{}
25 | 
26 | func (w LogWriter) Write(p []byte) (n int, err error) {
27 | 	return len(p), nil
28 | }
29 | 
30 | func LogPrint(p ...interface{}) {
31 | 	if isPrint {
32 | 		log.Infoln(p)
33 | 	}
34 | }
35 | 


--------------------------------------------------------------------------------
/utils/terminal.go:
--------------------------------------------------------------------------------
 1 | package utils
 2 | 
 3 | import (
 4 | 	"context"
 5 | 	log "github.com/sirupsen/logrus"
 6 | 	"os"
 7 | 	"os/signal"
 8 | 	"syscall"
 9 | 	"time"
10 | )
11 | 
12 | func CloseTerminal() {
13 | 	// 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
14 | 	quit := make(chan os.Signal)
15 | 	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
16 | 	<-quit
17 | 	_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
18 | 	defer cancel()
19 | 	log.Println("- EXIT - [Ctrl+C] The project will automatically close after 3 seconds")
20 | 	time.Sleep(time.Second * 3)
21 | }
22 | 


--------------------------------------------------------------------------------