基于Golang的可视化Web管理后台生成工具Go-sword 🗡️

基于Golang的可视化Web管理后台生成工具Go-sword 🗡️

Go-sword

【点我访问中文文档_cn_zh】

Go-sword 是一个基于 Go 语言的可视化 Web 管理后台生成工具。

目标是快速创建一个具备 CRUD 功能的可视化后台。

根据 MySQL 的表结构,创建完整的管理后台界面,开发者不再需要手动创建具备 CRUD 功能的页面。 只需点击按钮即可生成完整的管理后台。

136e8b44d5d4acf00d5a63125928bd731587996269.jpg

特性

  1. 一键生成,无需编写一行代码
  2. 支持增、删、改、查、批量删除、分页、搜索
  3. 页面基于 Vue.js + iView
  4. 每个数据表会生成独立的逻辑文件,开发者可以寻求使用 Vue 或 iView 来实现功能更丰富的页面

1626ee1d3300ac6db6669d63721d96381587996351.jpg

开始

安装

go get -u github.com/sunshinev/go-sword

安装完成后,确保 go-sword 命令位于 GOPATH/bin 目录下,并且可执行。

启动服务

go-sword -db {db_database} -password {db_password} -user {db_uesr} -module {module_name}

例如:go-sword -db blog -password 123456 -user root -module go-sword-app

以上命令是连接数据库 blog,用户名 root,密码 12345,并在运行 go-sword 命令的当前目录下创建项目 go-sword-app

启动成功的提示:

Go-Sword will create new project named go-sword-app in current directory

[Server info]
Server port: 8080
Project module: go-sword-app

[db info]
MySQL host: localhost
MySQL port: 3306
MySQL user: root
MySQL password: 123456

Start successful, server is running ...
Please request: http://localhost: 8080

参数说明

+ ------------------------------------------------- -+
| |
| Welcome to use Go-Sword |
| |
| Visualized tool |
| Fastest to create CRUD background |
| https://github.com/sunshinev/go-sword |
| |
+ ------------------------------------------------- -+
Usage of go-sword:
 //Database information to be connected
  -db string
      MySQL database
  -host string
      MySQL Host (default "localhost")
 //Important: module parameters are explained separately
  -module string
      New project module, the same as 'module' in go.mod file. (Default "go-sword-app /")
 //The default port where the go-sword service starts
  -p string
      Go-sword Server port (default "8080")
  -password string
      MySQL password
  -port int
      MySQL port (default 3306)
  -user string
      MySQL user

参数:-module

-module 参数是要创建的项目名称,同时也是新项目 go.mod 文件中 module 字段的值。请确保两者一致。

注意

新项目将直接在运行 go-sword 命令的当前目录下创建 module 目录作为新项目。

开始使用服务

Start successful, server is running ...
Please request: http://localhost: 8080

根据服务启动的提示,直接点击 http://localhost: 8080 进入 Web 可视化工具页面。

59384a43cbc382dec53dd76d169a5d001587995174.jpg

重要:页面功能介绍

  1. 首先,通过下拉菜单选择 MySQL 表,然后点击 Preview 按钮来渲染将要创建的文件。
  2. 第一次创建新项目文件时,需要点击 select all 全选,因为第一次创建包含了项目启动所必需的核心文件。
  3. 点击 Generate 按钮,可以看到文件成功创建的提示。
  4. 至此,我们的后台已成功创建。

注意:

  1. 第一次需要全选所有文件。
  2. 如果创建第二个管理页面,只需选择 select diff & new 按钮,然后点击 Generate 按钮即可。
  3. 每次生成新的管理界面后,请重启新创建的项目。

开始使用新项目

进入我们新创建的项目目录。

➜ test tree -L 2
.
└── go-sword-app
    ├── controller
    ├── core
    ├── go.mod
    ├── go.sum
    ├── main.go
    ├── model
    ├── resource
    ├── route
    └── view

例如,如果我们刚刚在 test 目录下运行了 go-sword 命令,那么创建的项目就是 test/go-sword-app

我们进入 test/go-sword-app 目录,按照以下命令启动项目。

初始化新项目 go mod init

使用 go mod 初始化项目,这里的 module 与我们之前提到的项目名称相同!

go mod init {module}

启动项目

go run main.go

然后你会看到以下提示,点击 http://localhost: 8082 即可进入后台管理界面。

Enjoy your system ^ ^
Generated by Go-sword
https://github.com/sunshinev/go-sword

[Server info]
Server port: 8082

[db info]
MySQL host: localhost
MySQL port: 3306
MySQL user: root
MySQL password: 123456

Start successful, server is running ...
Please request: http://localhost: 8082

管理后台效果

  1. 后端错误通知
  2. 增、删、改、查、批量删除、分页、搜索

1626ee1d3300ac6db6669d63721d96381587996351.jpg

一些问题

  1. 由于 Golang 的 map 结构是无序遍历的,因此无法保证某些页面的字段顺序与数据库字段顺序一致。
  2. 关于 module 参数的处理,可能有更好的解决方案。
  3. 没有提供注册和登录功能,这与初衷不符。最初是想做更基础的事情,快速创建页面。
  4. 生成的项目代码有很大的优化空间。

页面功能展示

列表

ea1f86ebc1b5c88aaf6484fa078584951587997286.jpg

删除

70279af696d9a230001f821cdf3a1ac21587997368.jpg

预览

2d1871a645acc3d3544ad7f77a0d6fca1587997398.jpg

编辑

a9255db26b2af0365655840f6afd27851587997440.jpg

Go-sword fork

如果你想进行定制,那么需要注意,Go-sword 项目可以打包成单个命令来执行,因为所有静态文件也被打包进去了。

静态文件压缩命令如下:

go-bindata -o assets/resource/dist.go -pkg resource resource/dist/...
go-bindata -o assets/stub/stub.go -pkg stub stub/...
go-bindata -o assets/view/view.go -pkg view view/...

更多关于基于Golang的可视化Web管理后台生成工具Go-sword 🗡️的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于基于Golang的可视化Web管理后台生成工具Go-sword 🗡️的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Go-sword确实是一个高效的Go语言后台管理快速开发工具。它通过数据库表结构自动生成CRUD界面的设计思路很实用,特别是对于需要快速搭建管理后台的场景。

从技术实现来看,Go-sword采用了典型的MVC架构,自动生成controller、model、view等目录结构。以下是一个生成的项目结构示例:

// 生成的项目main.go示例
package main

import (
    "github.com/sunshinev/go-sword-app/core"
    "github.com/sunshinev/go-sword-app/route"
)

func main() {
    // 初始化配置
    core.InitConfig()
    
    // 初始化数据库
    core.InitDB()
    
    // 注册路由
    r := route.InitRouter()
    
    // 启动服务
    r.Run(":8082")
}

生成的controller层代码通常会包含标准的CRUD操作:

// 自动生成的controller示例
package controller

import (
    "github.com/gin-gonic/gin"
    "github.com/sunshinev/go-sword-app/model"
    "net/http"
)

type UserController struct{}

func (c *UserController) List(ctx *gin.Context) {
    var users []model.User
    page := ctx.Query("page")
    size := ctx.Query("size")
    
    // 分页查询逻辑
    db := model.DB.Limit(size).Offset((page-1)*size)
    db.Find(&users)
    
    ctx.JSON(http.StatusOK, gin.H{
        "data": users,
        "total": len(users),
    })
}

func (c *UserController) Create(ctx *gin.Context) {
    var user model.User
    if err := ctx.ShouldBindJSON(&user); err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    
    model.DB.Create(&user)
    ctx.JSON(http.StatusOK, gin.H{"data": user})
}

func (c *UserController) Update(ctx *gin.Context) {
    id := ctx.Param("id")
    var user model.User
    
    model.DB.First(&user, id)
    ctx.ShouldBindJSON(&user)
    model.DB.Save(&user)
    
    ctx.JSON(http.StatusOK, gin.H{"data": user})
}

func (c *UserController) Delete(ctx *gin.Context) {
    id := ctx.Param("id")
    model.DB.Delete(&model.User{}, id)
    
    ctx.JSON(http.StatusOK, gin.H{"message": "删除成功"})
}

model层会根据数据库表自动生成对应的结构体:

// 自动生成的model示例
package model

import (
    "time"
    "github.com/jinzhu/gorm"
)

type User struct {
    gorm.Model
    Username string `gorm:"type:varchar(100);not null"`
    Email    string `gorm:"type:varchar(100);unique_index"`
    Password string `gorm:"type:varchar(255)"`
    Age      int    `gorm:"type:int"`
    Status   int    `gorm:"type:int;default:1"`
    CreatedAt time.Time
    UpdatedAt time.Time
}

func (User) TableName() string {
    return "users"
}

前端Vue组件也会自动生成,包含表格、表单等界面元素:

<!-- 自动生成的Vue列表组件示例 -->
<template>
  <div>
    <Card>
      <div slot="title">
        <Row :gutter="16">
          <Col span="8">
            <Input search placeholder="搜索..." v-model="searchKey" @on-search="handleSearch" />
          </Col>
          <Col span="16" class="text-right">
            <Button type="primary" @click="handleCreate">新增</Button>
            <Button type="error" @click="handleBatchDelete" :disabled="selection.length === 0">批量删除</Button>
          </Col>
        </Row>
      </div>
      
      <Table 
        :columns="columns" 
        :data="tableData"
        @on-selection-change="handleSelectionChange"
        border>
      </Table>
      
      <Page 
        :total="total" 
        :current="currentPage"
        :page-size="pageSize"
        @on-change="handlePageChange"
        show-total
        class="margin-top-20"/>
    </Card>
    
    <!-- 编辑模态框 -->
    <Modal v-model="showModal" :title="modalTitle">
      <Form :model="formData" :label-width="80">
        <FormItem label="用户名">
          <Input v-model="formData.username" />
        </FormItem>
        <FormItem label="邮箱">
          <Input v-model="formData.email" />
        </FormItem>
        <FormItem label="年龄">
          <InputNumber v-model="formData.age" :min="0" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      columns: [
        { type: 'selection', width: 60, align: 'center' },
        { title: 'ID', key: 'id', width: 80 },
        { title: '用户名', key: 'username' },
        { title: '邮箱', key: 'email' },
        { title: '年龄', key: 'age' },
        { title: '操作', key: 'action', width: 150, render: (h, params) => {
          return h('div', [
            h('Button', {
              props: { type: 'primary', size: 'small' },
              on: { click: () => this.handleEdit(params.row) }
            }, '编辑'),
            h('Button', {
              props: { type: 'error', size: 'small' },
              style: { marginLeft: '5px' },
              on: { click: () => this.handleDelete(params.row.id) }
            }, '删除')
          ])
        }}
      ],
      tableData: [],
      searchKey: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selection: [],
      showModal: false,
      formData: {},
      modalTitle: '新增'
    }
  },
  methods: {
    loadData() {
      this.$http.get('/api/users', {
        params: {
          page: this.currentPage,
          size: this.pageSize,
          search: this.searchKey
        }
      }).then(response => {
        this.tableData = response.data.data
        this.total = response.data.total
      })
    },
    handleCreate() {
      this.formData = {}
      this.modalTitle = '新增'
      this.showModal = true
    },
    handleEdit(row) {
      this.formData = { ...row }
      this.modalTitle = '编辑'
      this.showModal = true
    },
    handleDelete(id) {
      this.$Modal.confirm({
        title: '确认删除',
        content: '确定要删除这条记录吗?',
        onOk: () => {
          this.$http.delete(`/api/users/${id}`).then(() => {
            this.$Message.success('删除成功')
            this.loadData()
          })
        }
      })
    },
    handleBatchDelete() {
      // 批量删除逻辑
    },
    handlePageChange(page) {
      this.currentPage = page
      this.loadData()
    },
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    handleSelectionChange(selection) {
      this.selection = selection
    }
  },
  mounted() {
    this.loadData()
  }
}
</script>

工具在打包时使用go-bindata将静态资源嵌入二进制文件的方案很巧妙,这使得分发和部署更加方便。对于需要快速原型开发或内部管理系统的项目,Go-sword能显著减少重复的CRUD代码编写工作。

回到顶部