preface

Today I finished building the basic skeleton of the project and using Gin as the Web framework

The target

  • Complete the construction of the basic skeleton
  • Gin was introduced as a Web development framework
  • Simple use of Gin routing

The project structure

Use Go Get to download Gin

Run the go get -u github.com/gin-gonic/gin command

After downloading, you can view the dependencies in go.mod

Hello World of Gin

Enter the code in main.go:

package main

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

func main(a) {
	r := gin.Default()
	r.GET("/hi".func(c *gin.Context) {
		c.JSON(200."hello world")
	})
	r.Run(": 8888") // Listen and start the service on 127.0.0.1:8888
}
Copy the code

Right click to launch the project

Access to 127.0.0.1:8888

The controller

Controller–> create directory HomeControoler–> create file homecontroller.go

Input code:

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")}Copy the code

The router

Routers–> Create a new file homecontroller. go

package Routers

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

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

	// 1. The first superfluous element will be removed (.. / or //);
	//2. The route searches the new path in a case-insensitive manner.
	//3. If the handler is found correctly, the route is redirected to the correct handler and returns either 301 or 307. //Foo may be redirected to /Foo)
	router.RedirectFixedPath = true

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

	router.Run(": 8888") // Listen and start the service on 127.0.0.1:8888
}
Copy the code

Url case insensitive

router.RedirectFixedPath = true

Main code adjustment

package main

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

func main(a) {
	router := gin.Default()
	Routers.Init(router)
}
Copy the code

Modified directory structure

Start the project

requesthttp://127.0.0.1:8888/Home/

requesthttp://127.0.0.1:8888/Home/Hi

The project address

Github.com/panle666/Go…