Create the engine

There are two ways to create a Gin engine:

gin.Default()
gin.New()
Copy the code

The difference between gin.default () and gin.new() is that gin.Default is the encapsulation of gin.New().

Simple to use

We implement the simplest program that requests and prints a Hello Gin!

func main(a) {
	engine := gin.Default()             // Create engine
	engine.GET("/hello".func(context *gin.Context) {    // Define the request interface and handle anonymous functions
		fmt.Println("Request path:", context.FullPath())
		context.Writer.Write([]byte("Hello Gin!"))})if err := engine.Run(": 8090"); err ! =nil {         // Start the engine and listen on port 8090
		log.Print(err)
	}
}
Copy the code

Let’s refine one more request using the generic method.

func main(a){}
engine := gin.Default()
	engine.Handle("GET"."/hello".func(context *gin.Context) {
		path := context.FullPath()
		fmt.Print(path)

		name := context.DefaultQuery("name"."hello")   // If there is no name key, assign the name variable to "hello".

    context.Writer.Write([]byte("hello " + name))
	})

	iferr := engine.Run(); err ! =nil {
		fmt.Println(err)
	}
}
Copy the code

Use a POST request to process the body data

// http://localhost/login POST request
	engine.Handle("POST"."login".func(context *gin.Context) {
		path := context.FullPath()
		fmt.Println(path)

		name := context.PostForm("name")
		pass := context.PostForm("pass")

		fmt.Println("name:", name, "pass:", pass)

		context.Writer.Write([]byte("name:" + name + "\npass:" + pass))
	})

// Use GetPostForm to get data
engine.POST("/user".func(context *gin.Context) {
		name, exist := context.GetPostForm("name")
		if exist {
			fmt.Println(name)
		}

		pass, exist := context.GetPostForm("pass")
		if exist {
			fmt.Println(pass)
		}

		context.Writer.Write([]byte("name:" + name + "\npass:" + pass))
	})
Copy the code

The Delete method

engine.DELETE("/user/:id".func(context *gin.Context) {
		UserID := context.Param("id")

		context.Writer.Write([]byte("delete:" + UserID))
	})
Copy the code