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",
	})
}
相关推荐
hid558845362 小时前
深度学习之噬菌体特异性蛋白质预测:代码实现与解析
gin
ChineHe5 小时前
Gin框架入门篇002_第一个Gin服务
macos·xcode·gin
kite01216 小时前
Gin 与消息队列集成:使用 RabbitMQ 处理异步任务
golang·rabbitmq·gin
未来魔导21 小时前
Gin版本的路由总结
开发语言·llm·gin·路由
未来魔导1 天前
基于 Gin 框架的 大型 Web 项目推荐架构目录结
前端·架构·gin
kgduu2 天前
Gin源码解析
算法·gin
ZNineSun2 天前
Go的Http框架:gin
http·golang·gin
古城小栈8 天前
Gin 实现 大文件 分片上传 与 断点续传
go·gin
古城小栈9 天前
为Gin应用添加 一双眼睛:Prometheus
prometheus·gin
风生u9 天前
Go: Gin的用法
golang·xcode·gin