neovim下进行接口测试,并且登录token自动保存

327 阅读2分钟

最近一段时间最大的乐趣就是用自己配置的neovim写go代码, 现在用go代码写的接口,一开始用curl测试接口,感觉不是很方便。 就尝试能否在neovim发起接口测试。 功夫不负有心人,找到了一个插件rest.nvim。记录下安装和自己定制的lua脚本

lazy.nvim安装插件

  {
    "rest-nvim/rest.nvim",
    config = function()
      require "yuyu.config.rest" --个人的配置文件
    end,
    dependencies = { "nvim-lua/plenary.nvim" },
  }

配置快捷键

vim.keymap.set("n","<leader>ar","<Cmd>lua require('rest-nvim').run()<cr>",{desc = "接口测试"})

自动保存login的token

网上找到的脚本使用不了,还加入了sed等系统命令,决定自己尝试用neovim的一等公民lua脚本实现下

local function Split(szFullString, szSeparator)
  local nFindStartIndex = 1
  local nSplitIndex = 1
  local nSplitArray = {}
  while true do
    local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)
    if not nFindLastIndex then
      nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))
      break
    end
    nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)
    nFindStartIndex = nFindLastIndex + string.len(szSeparator)
    nSplitIndex = nSplitIndex + 1
  end
  return nSplitArray
end

local function findTokenLine(value, tab)
  for _, v in ipairs(tab) do
    if string.find(v, value) then
      return v 
    end
  end
  return nil
end

-- api login的token自动保存
vim.api.nvim_create_autocmd({ "BufEnter" }, {
  pattern = "*",
  callback = function()
    if vim.bo.filetype == 'httpResult' then
      local bufnr = vim.api.nvim_get_current_buf()
      local bufc = vim.api.nvim_buf_get_lines(bufnr, 0, -1, true) --获取buf内容
      local loginLine = findTokenLine("/login", bufc) 
      if loginLine  then
        local tokenLine = findTokenLine("\"token\":\"",bufc)
        local config = require("rest-nvim.config")
        local env_file = vim.fn.getcwd() .. "/" .. (config.get("env_file") or ".env")
        local rs = Split(tokenLine, "\"token\":\"")[2]
        rs = string.sub(rs,1,-3)
        rs = "token=" .. rs
        local file = io.open(env_file, "w")
        io.output(file) 
        io.write(rs)
        io.close()
      end
    end
  end,
})

以上脚本会自动判断buf打开,fileType是httpResult的把指定/login接口获取到的token数据保存到.env文件 .env内容大概是这样: token=xxxxxxxxxxxxxxxx

需要token的接口写法

### login
POST http://10.25.2.182:8080/napi/login
Accept: application/json, application/problem+json, text/plain, */*
Content-Type: application/json;charset=utf-8

{"username": "admin", "password": "xxxxx"}

### resource
GET http://10.25.2.182:8080/napi/app/resource/list
Content-Type: application/json
Authorization:  {{token}}

关键写法{{token}} rest.nvim会从.env文件找到token=对应的值替换. 通过配置的快捷键ar 运行就会请求接口的时候在头信息里自动带上 Authorization: {{token}}

后续优化的地方

.env文件还可以维护更多的变量,但是我偷懒了直接保存token=,整个文件覆盖,自己的lua脚本简单点。