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",
	})
}
相关推荐
码界奇点2 天前
基于Gin与GORM的若依后台管理系统设计与实现
论文阅读·go·毕业设计·gin·源代码管理
迷迭香与樱花2 天前
Gin 框架
go·gin
席万里3 天前
基于Go和Vue快速开发的博客系统-快速上手Gin框架
vue.js·golang·gin
娱乐我有3 天前
Gin Lee八年淬炼金嗓重返红馆,2026开年第一场「声波开运仪式」
gin
kite01219 天前
GIn + Casbin: RBAC 权限控制系统集成
gin·jwt·casbin
王家视频教程图书馆14 天前
go语言 gin grom jwt 登陆token验证 增删改查 分页 完整 图书管理系统
gin
liuyunshengsir16 天前
golang Gin 框架下的大数据量 CSV 流式下载
开发语言·golang·gin
我不是8神21 天前
gin与gorm框架知识点总结
ios·iphone·gin
西京刀客21 天前
golang路由与框架选型(对比原生net/http、httprouter、Gin)
http·golang·gin
天天向上10241 个月前
在 Go 的 Gin Web 框架中,获取 HTTP 请求参数有多种方式
前端·golang·gin