Golang实践之博客(三)Web框架Gin的使用|Go主

前言

今天完成项目基本骨架搭建及使用Gin作为web框架

目标

  • 完成基础骨架的搭建
  • 引入Gin作为Web开发框架
  • Gin路由的简单使用

项目结构

image.png

使用go get 下载Gin

终端执行指令go get -u github.com/gin-gonic/gin

image.png

下载完成后在go.mod中可查看到依赖
image.png

Gin的Hello World

在main.go输入代码:

package main

import "github.com/gin-gonic/gin"

func main() {
	r := gin.Default()
	r.GET("/hi", func(c *gin.Context) {
		c.JSON(200, "hello world")
	})
	r.Run(":8888") // 监听并在 127.0.0.1:8888 上启动服务
}
复制代码

右键启动项目

image.png

访问127.0.0.1:8888

image.png

控制器

Controller-->新建目录HomeControoler-->新建文件HomeController.go

输入代码:

package HomeControoler

import "github.com/gin-gonic/gin"

func Index(c *gin.Context) {
	c.JSON(200,"hello world")
}

func Hi(c *gin.Context) {
	c.JSON(200,"hi")
}

复制代码

路由器

Routers-->新建文件HomeController.go
输入代码:

package Routers

import (
	"github.com/gin-gonic/gin"
	"golang-blog/Controller/HomeControoler"
)

func Init(router *gin.Engine) {
	home := router.Group("Home")

	// 1.首位多余元素会被删除(../ or //);
	//2.然后路由会对新的路径进行不区分大小写的查找;
	//3.如果能正常找到对应的handler,路由就会重定向到正确的handler上并返回301或者307.(比如: 用户访问/FOO 和 /..//Foo可能会被重定向到/foo这个路由上)
	router.RedirectFixedPath = true

	{
		home.GET("/", HomeControoler.Index)
                home.GET("/hi",HomeControoler.Hi)
	}

	router.Run(":8888") // 监听并在 127.0.0.1:8888 上启动服务
}
复制代码

Url忽略大小写

router.RedirectFixedPath = true

main代码调整

package main

import (
	"github.com/gin-gonic/gin"
	"golang-blog/Routers"
)

func main() {
	router := gin.Default()
	Routers.Init(router)
}
复制代码

调整后的目录结构

image.png

启动项目

请求http://127.0.0.1:8888/Home/

image.png

请求http://127.0.0.1:8888/Home/Hi

image.png

项目地址

github.com/panle666/Go…