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",
	})
}
相关推荐
meowrain7 天前
Go语言 Web框架Gin
前端·golang·gin
Golinie7 天前
【Gin】Web框架开发快速入门
golang·web·gin·后端开发
莫忘初心丶8 天前
Golang Gin框架获取JSON输入
golang·json·gin
m0_7482482315 天前
Go-Gin Web 框架完整教程
前端·golang·gin
程序员林北北16 天前
玩转Gin框架:Golang使用Gin完成登录流程
开发语言·golang·gin
龙雨LongYu1223 天前
go gin配置air
开发语言·golang·gin
梦想画家24 天前
Golang Gin系列-9:Gin 集成Swagger生成文档
golang·gin·swagger
梦想画家25 天前
Golang Gin系列-7:认证和授权
golang·gin·授权认证
Amd7941 个月前
深入探讨数据库索引类型:B-tree、Hash、GIN与GiST的对比与应用
数据结构·gin·b-tree·查询优化·数据库索引·gist·hash索引
寻找优秀的自己1 个月前
Gin 应用并注册 pprof
gin·性能调优·pprof