Imperceptibly has updated to the ninth, I hope to help readers.

Originally published on ISLAND

Having gained a basic understanding of the concepts and functions in Gin and how to use them in code, let’s take a step back a long time. How long will it take? Presumably when you were learning Gin routing in Chapter 2.

Today, instead of working on templates, we’re going to start a new chapter, which we call restful.

What is 📍 restful

When it comes to restful, I believe many or even a large number of friends are familiar with it. If you already know it, you can go straight to the next chapter. But there are still many friends who are new to restful, so here is a brief introduction.

For example, our interface might be defined as get_user for obtaining the current user and /delete_user for deleting the current user. Using restful interfaces, we define /user as the interface for updating users, /user as the interface for retrieving users, and /user as the interface for deleting users.

????? . ?????

The first contact with friends must be a question mark, so I visit /user data is updated? Deleted? Or get a user? So a full restful interface is not just a url definition, but also a request method.

Remember the description in Chapter 2 of how GIN provides HTTP requests? So a complete restful request requires a request method. Our interface should be update request /user, get request /user for user, delete request /user interface for user deletion.

This is only a brief introduction to restful request methods.

🔖 first interface

Let’s now do a demonstration of the article interface, again connecting to the database, where the data is stored.

Create a new table, article, on the same database we used before, and connect to the database.

create table ` article`
(
	id int auto_increment
		primary key.type varchar(20) null.content text not null
);
Copy the code

First we need to have a model that corresponds to the table structure as well as the data binding for our receiving front end.

Create a new Model folder and create article. Go in the Model folder

type Article struct {
	Id      int    `json:"id"`
	Type    string `json:"type"`
	Content string `json:"content"`
}
Copy the code

Binding front-end data retrieval by annotating JSON.

Now you can complete the first function, adding an article to the database. Complete the code to add data to the data in article. Go. The code is not explained here, as before.

func (article Article) Insert(a) int {
	result, e := initDB.Db.Exec("insert into ` article` (type, content) values (? ,?) ;", article.Type, article.Content)
	ife ! =nil {
		log.Panicln("Failed to add articles", e.Error())
	}
	i, _ := result.LastInsertId()
	return int(i)
}
Copy the code

Completing the Model layer completes the handler

Under the handler new article/articleHandler. Go.

The first thing we need to do is get the data that comes through the front end. Bind the data with context.ShouldBindJSON. If the binding succeeds, the add method we wrote above is called to add. When done, JSON data is returned via context.JSON.

func Insert(context *gin.Context) {
	article := model.Article{}
	var id = - 1
	if e := context.ShouldBindJSON(&article); e == nil {
		id = article.Insert()
	}
	context.JSON(http.StatusOK, gin.H{
		"id": id,
	})
}
Copy the code

Finally, we complete the corresponding route.

Perfect the route configuration in SetupRouter in initRouter.

articleRouter := router.Group("")
	{
		// Add an article
		articleRouter.POST("/article", article.Insert)
	}
Copy the code

⭕ test

When that’s done, it’s time to run the tests.

Of course it’s best to write unit tests.

In the test folder, create the article_test.go test file.

package test

import (
	"GinHello/initRouter"
	"GinHello/model"
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gopkg.in/go-playground/assert.v1"
	"net/http"
	"net/http/httptest"
	"testing"
)

var router *gin.Engine

func init(a) {
	router = initRouter.SetupRouter()
}

func TestInsertArticle(t *testing.T) {
	article := model.Article{
		Type:    "go",
		Content: "hello gin",
	}
	marshal, _ := json.Marshal(article)
	w := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodPost, "/article", bytes.NewBufferString(string(marshal)))
	req.Header.Add("content-typ"."application/json")
	router.ServeHTTP(w, req)
	assert.Equal(t, w.Code, http.StatusOK)
	assert.NotEqual(t, "{id:-1}", w.Body.String())
}
Copy the code

Create an article object in the test case, assign it a value, use the JSON method to build the object and convert it to JSON, and finally make the request.

Run the test case, if our code is written correctly, the test passes, and the data is added to the database accordingly.

Of course, if you don’t want to write unit tests, you can do it via Postman, etc. Here is a brief introduction to GoLand Http testing tools.

Let’s create a new http_test folder and create a new.http file under the folder named article.http

Write the file, write as follows, specify our request address, specify the requested data. A run button appears to the left of POST. Click the Run button and the console returns results. When running this file, start our project.

POST http://localhost:8080/article
Content-Type: application/json

{
  "type": "go",
  "content": "Hello Go"
}
Copy the code

See the official documentation for other syntax rules for.http files.

This completes the first restful interface, and can also complete the rest of the interfaces. See Github code for additional interface examples.

✍ summary

This chapter mainly describes how to build a restful interface. Restful interfaces are becoming more and more important in today’s development. A large number of interfaces are restful. Github code to complete the query, add, delete and other interfaces, space is limited, not to expand on more.

👩💻 Sample code for this section

Github

Recommended reading

Gin(I):Hello Gin(II): Routing Router Gin(III): Template TMPL Gin(IV): Form submission checksum model binding Gin(V): Connection to MySQL Gin(VI): File upload Gin(VII): Use and definition of middleware Gin(8): use of cookies Gin(9): Generate restful interfaces

Personal public account

Personal public account has just been established, hope you give attention, will update Java, go, Kotlin and other related articles