CRUD web server v Goli Golang

Tram Ho

In the previous article, we set up the basic login and registration function with Golang. In today’s article, we will complete a basic webserver with Golang by writing additional features, delete, edit, read (CRUD).

For convenience, let’s review the application’s directory structure.

The full source code you can refer to on Github

1. Middlewares

Like the concept of middlewares in many other platforms, the middlewares in webserver golang is a processing function, the code is between receiving request and returning response to the client. The tasks that middlewares usually undertake are user authentication, request filtering (avoiding malicious requests), data validation, etc.

In this article, we will mainly use middlewares authenticate tokens sent from clients, to authenticate users whether they are entitled to add, delete, edit or view?

The above code is a bit complicated, we will gradually learn shortly.

httprouter.Handle Method

We remember in the previous article, httprouter has methods to handle HTTP Methods that the client sends to the server such as GET , POST , …

In fact, the above methods are a shorter and more convenient way of writing the Handle method

Type Handle

In the above section, the last parameter of the method is the Handle data type

So functions with input parameters in the above form will be treated as a Handle functions. You know why the parameter http.Request is in the form of a pointer? The reason is that the data of the request sent from the client can be processed by a series of Handle functions (such as string middlewares). Therefore, the data needs to be changed directly via the cursor instead of making a copy and changing on it.

Summarizing

The CheckJwt Middlewares above will have the task of Verify token sent by the client, if the token is invalid, it will return an error. Otherwise, the next processing function (Handle) will be called to process the request.

When we want to use middlewares for routes, we will do the following example:

2. models / Post.go

We will create new Post models, each user on the system after logging in will have the right to add, edit, delete their own posts. You have the right to view all post or view the post you create.

Connecting to the db

Similar to collection users , we write the connect function to the posts collection

Step routes with middlewares

3. Processing jsonwebtoken from client

Extract information from jwt

  • The Extract function takes the token value in the header request , removing redundancy in the header (“Bearer string”).
  • The ExtractUsernameFromToken function extracts the username from the token’s value in order to delegate rights later on to add and delete route .

Verify jwt

The token after being sent by the client will be checked for validity, decrypted with the secret_key stored in the environment variable. jwt.Parse function is a bit complicated, if you want to learn more, you can read more at GoDocs .

4. Query posts

Get all posts

  • The first step is to connect to the posts collection
  • Define the result variable as an array bson.M (bson is a map)
  • Use the Find function of the mongoDB library to query the entire record in the posts collection
  • Handle error
  • Because the data variable stores the return value from the Find function as a pointer, we need to convert it into a bson form to return the client. (eg: &{ 0xc0003c6840 <nil> 0xc0000d8c40 0xc00037cb40 <nil>} ) Find prototype of the Find function:

  • We use the for function to browse data and decode each into a bson form

Get my posts

  • Similar to the previous section, the GetMyPosts function GetMyPosts only by extracting the username from the token and adding filter provided that the records have the creater username extract above.

5. Create post

  • Each post will have a unique id (uuidv4 form)
  • After creating any uid with the function uuid.NewV4() , we use the fmt.Sprintf function to convert the id into xxxx-xxxx-xxxx-xxx .
  • The following we are also quite familiar when connecting db and calling InsertOne function to add records to the db.

6. Edit post

  • The function takes id values ​​in params and title in request body.
  • Validate data
  • Connecting to the db
  • Look in the db to see if there are any records with the id values ​​that match the id , if not, return a 404.
  • If so, do we compare the creater field in the record with the username extract from the token to see if it overlaps? If different, return 403 for the client.
  • Next we use the UpdateOne function to update the value. The function returns 2 values, the first variable is a pointer, we do not need to handle it so leave a _ , just check to see if the update process has an error or not.

7. Delete post

  • The DeletePost function is similar to the edit function above, except that it uses the FindOneAndDelete function

References

https://godoc.org/go.mongodb.org/mongo-driver/mongo https://godoc.org/github.com/julienschmidt

https://www.alexedwards.net/blog/a-recap-of-request-handling https://www.alexedwards.net/blog/making-and-using-middleware

Share the news now

Source : Viblo