gin读取静态文件内容

测试准备两个txt文件,内容随意,在文件static/json文件夹下, homeTab.txt,searchKey.txt

启动入口

main.go

复制代码
package main

import (
	"fmt"
	"gin-test/router"
)

func main() {
	// 初始化路由并启动
	router.InitRouter()
}

路由配置

router/router.go

复制代码
package router

import (
	"gin-test/controller"

	"github.com/gin-gonic/gin"
)

func InitRouter() {
	// 创建路由
	r := gin.Default()

	// 读取静态资源
	r.Static("/static", "./static")

	// 创建一个emp路由组
	empRouter := r.Group("/emp")

	// 测试路由组
	empRouter.GET("/test", controller.EmpController{}.Index)

	// 获取搜索关键词数据
	empRouter.GET("/searchKeyWord", controller.EmpController{}.SearchKeyContent)

	// 获取首页tab信息
	empRouter.GET("/getTabInfo", controller.EmpController{}.HomeTabInfos)

	// 启动服务
	r.Run(":9999")

}

控制器

controller/empController.go

复制代码
package controller

import (
	"io/ioutil"
	"net/http"

	"github.com/gin-gonic/gin"
)

type EmpController struct{}

// 测试内容
func (EmpController) Index(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "hello world",
	})
}

// 获取搜索内容数据
func (EmpController) SearchKeyContent(c *gin.Context) {
	// 读取文件searchKey.txt内容
	searchKeyContent, err := ioutil.ReadFile("static/json/searchKey.txt")

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":     1,
			"msg":      "error",
			"errorMsg": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": string(searchKeyContent),
		"msg":  "success",
	})
}

// 获取首页tan名称以及跳转信息
func (EmpController) HomeTabInfos(c *gin.Context) {
	// 读取文件searchKey.txt内容
	searchKeyContent, err := ioutil.ReadFile("static/json/homeTab.txt")

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":     1,
			"msg":      "error",
			"errorMsg": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": string(searchKeyContent),
		"msg":  "success",
	})
}
相关推荐
我的golang之路果然有问题6 天前
云服务器部署Gin+gorm 项目 demo
运维·服务器·后端·学习·golang·gin
fashia8 天前
Java转Go日记(六十):gin其他常用知识
开发语言·后端·golang·go·gin
我的golang之路果然有问题9 天前
ElasticSearch+Gin+Gorm简单示例
大数据·开发语言·后端·elasticsearch·搜索引擎·golang·gin
fashia9 天前
Java转Go日记(五十七):gin 中间件
开发语言·后端·golang·go·gin
夏沫mds9 天前
不动产登记区块链系统(Vue3 + Go + Gin + Hyperledger Fabric)
linux·golang·区块链·gin·fabric
比特森林探险记9 天前
Go Gin框架深度解析:高性能Web开发实践
前端·golang·gin
在成都搬砖的鸭鸭10 天前
【Golang】使用gin框架导出excel和csv文件
golang·excel·gin
三金C_C10 天前
gin 框架
go·gin·后端框架
Chandler2411 天前
Go 即时通讯系统:日志模块重构,并从main函数开始
后端·重构·golang·gin
三金C_C11 天前
gin 常见中间件配置
中间件·gin