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",
	})
}
相关推荐
张烫麻辣亮。20 小时前
golang-gin包
开发语言·golang·gin
小红帽2.03 天前
GOFLY开源客服系统-处理gin框架下的session中间件
中间件·gin
小红帽2.03 天前
从零搭建客服系统:我是如何用Gin实现页面路由与模板渲染的
gin
戎码江湖4 天前
使用CI/CD部署后端项目(gin)
ci/cd·golang·gin·后端自动部署项目·自动化部署项目
夏沫mds11 天前
【基于hyperledger fabric的教育证书管理系统】
运维·go·vue·区块链·gin·fabric
水墨熊猫12 天前
【FIX】go运行报错“missing go.sum entry for module providing package”解决方案
golang·gin
用户895356032822015 天前
告别重复,用Go泛型精简Gin代码
后端·gin
水痕0123 天前
gin结合minio来做文件存储
java·eureka·gin
一个热爱生活的普通人1 个月前
解构 gin.Context:不止是 Context
后端·go·gin