使用 Golang Gin 新建一个网页

发布时间: 2019-10-15 15:27:39 作者: 大象笔记

总不能将所有逻辑代码都写在一个 main.go 中吧。还是独立出一个 controller 比较好。

gin 项目代码目录结构

mkdir controllers
mkdir views

controller - go 逻辑代码

package controllers

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func ChineseMoneyIndex(c *gin.Context) {
	c.HTML(http.StatusOK, "chinese_money_index.html", gin.H{})
}

HTML 模板

对应的在 views 目录下,新建一个 chinese_money_index.html 文件。

main.go 中的路由处理

package main

import (
	"github.com/gin-gonic/gin"
	"sunzhongwei.com/go_tool/controllers"
)

func main() {
	router := gin.Default()
	router.LoadHTMLGlob("views/*")
	router.GET("/go/chinese-money", controllers.ChineseMoneyIndex)
	router.Run() 
}

注意,引入 controllers package 时,前面要加上 module 名。

Tips: 创建 go module 的方法

项目结构参考

https://github.com/wangsongyan/wblog

我是一名山东烟台的开发者,联系作者