After completing the simple server startup in the previous article, this article will cover the database field writing and interface initialization of the blog system.

Connect to the local test database

If the local database environment has been set up, skip this step. Look below if you don’t have a local database environment. For the sake of simplicity and convenience, I am too lazy to install Mysql, Mysql uninstallation is a bit annoying, here use phpStudy integrated Mysql, do not want to use a key to uninstall, clean and convenient.

Open the official website of PHPStudy and download the corresponding installation package according to your own system to install

To start PHPStudy, click on Mysql directly

Open Navicat click Connect and select Mysql

Enter the connection nickname and password

Test Connection Test connection, successful, click Save save. At this point, the mysql environment is ok.

The directory structure

│ ├─ Configs │ ├─ Docs │ ├─ Global │ ├─ Go. Mod │ ├─ Internal │ ├─ Database Access Object) │ ├─ Middleware Http Middleware │ ├─ Middleware, ├─ Exercises, exercises, exercises, exercises, Exercises, Exercises, Exercises, Exercises, Exercises, Exercises, Exercises ├─ storage project generate temporary files ├─ third_party third-party resource toolCopy the code

Writing database fields


CREATE DATABASE
   IF NOT EXISTS go_server_mysqldb DEFAULT CHARACTER
  SET utf8mb4 DEFAULT COLLATEutf8mb4_general_ci; USE go_server_mysqldb; Create a tag table for articlesCREATE TABLE `blog_tag`
(
    `id`          int(10) unsigned NOT NULL AUTO_INCREMENT,
    `name`        varchar(100)        DEFAULT ' ' COMMENT 'Label name', # public partstart
    `created_on`  int(10) unsigned    DEFAULT '0' COMMENT 'Creation time',
    `created_by`  varchar(100)        DEFAULT ' ' COMMENT 'Founder',
    `modified_on` int(10) unsigned    DEFAULT '0' COMMENT 'Modification time',
    `modified_by` varchar(100)        DEFAULT ' ' COMMENT 'Modifier',
    `deleted_on`  int(10) unsigned    DEFAULT '0' COMMENT 'Delete time',
    `deleted_by`  varchar(100)        DEFAULT ' ' COMMENT 'Delete person',
    `is_del`      tinyint(3) unsigned DEFAULT '0' COMMENT 'Delete 0 = undeleted, 1 = deleted', # public partend
    `state`       tinyint(3) unsigned DEFAULT '1' COMMENT 'State 0 is disabled and state 1 is enabled'.PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='Tag Management'; Create column tableCREATE TABLE `blog_collection`
(
    `id`          int(10) unsigned NOT NULL AUTO_INCREMENT,
    `name`      varchar(100)        DEFAULT ' ' COMMENT 'Column name', # public partstart
    `created_on`  int(10) unsigned    DEFAULT '0' COMMENT 'Creation time',
    `created_by`  varchar(100)        DEFAULT ' ' COMMENT 'Founder',
    `modified_on` int(10) unsigned    DEFAULT '0' COMMENT 'Modification time',
    `modified_by` varchar(100)        DEFAULT ' ' COMMENT 'Modifier',
    `deleted_on`  int(10) unsigned    DEFAULT '0' COMMENT 'Delete time',
    `deleted_by`  varchar(100)        DEFAULT ' ' COMMENT 'Delete person',
    `is_del`      tinyint(3) unsigned DEFAULT '0' COMMENT 'Delete 0 = undeleted, 1 = deleted', # public partend
    `state`       tinyint(3) unsigned DEFAULT '1' COMMENT 'State 0 is disabled and state 1 is enabled'.PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='Column Management'; Create article tableCREATE TABLE `blog_article`
(
    `id`              int(10) unsigned NOT NULL AUTO_INCREMENT,
    `title`           varchar(100)        DEFAULT ' ' COMMENT 'Article Title',
    `desc`            varchar(300)        DEFAULT ' ' COMMENT 'Article Description',
    `cover_image_url` varchar(255)        DEFAULT ' ' COMMENT 'Cover picture address',
    `content_type`    tinyint(3) unsigned DEFAULT '1' COMMENT 'Article content type 0 is MD file type, 1 is DB TXT type',
    `content`         longtext COMMENT 'Article content',
    `content_url`     varchar(255)        DEFAULT ' ' COMMENT 'Article content address', # public partstart
    `created_on`      int(10) unsigned    DEFAULT '0' COMMENT 'Creation time',
    `created_by`      varchar(100)        DEFAULT ' ' COMMENT 'Founder',
    `modified_on`     int(10) unsigned    DEFAULT '0' COMMENT 'Modification time',
    `modified_by`     varchar(100)        DEFAULT ' ' COMMENT 'Modifier',
    `deleted_on`      int(10) unsigned    DEFAULT '0' COMMENT 'Delete time',
    `deleted_by`      varchar(100)        DEFAULT ' ' COMMENT 'Delete person',
    `is_del`          tinyint(3) unsigned DEFAULT '0' COMMENT 'Delete 0 = undeleted, 1 = deleted', # public partend
    `state`           tinyint(3) unsigned DEFAULT '1' COMMENT 'State 0 is disabled, state 1 is enabled'.PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='Article Management'; # article tag association tableCREATE TABLE `blog_article_tag`
(
    `id`          int(10) unsigned NOT NULL AUTO_INCREMENT,
    `article_id`  int(10) unsigned NOT NULL COMMENT 'the article id',
    `tag_id`      int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'tag id', # public partstart
    `created_on`  int(10) unsigned          DEFAULT '0' COMMENT 'Creation time',
    `created_by`  varchar(100)              DEFAULT ' ' COMMENT 'Founder',
    `modified_on` int(10) unsigned          DEFAULT '0' COMMENT 'Modification time',
    `modified_by` varchar(100)              DEFAULT ' ' COMMENT 'Modifier',
    `deleted_on`  int(10) unsigned          DEFAULT '0' COMMENT 'Delete time',
    `deleted_by`  varchar(100)              DEFAULT ' ' COMMENT 'Delete person',
    `is_del`      tinyint(3) unsigned       DEFAULT '0' COMMENT 'Delete 0 = undeleted, 1 = deleted', # public partend
    `state`       tinyint(3) unsigned       DEFAULT '1' COMMENT 'State 0 is disabled, state 1 is enabled'.PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='Article Tag Association Management'; Create column associative tableCREATE TABLE `blog_article_collection`
(
    `id`            int(10) unsigned NOT NULL AUTO_INCREMENT,
    `article_id`    int(10) unsigned NOT NULL COMMENT 'the article id',
    `collection_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'tag id', # public partstart
    `created_on`    int(10) unsigned          DEFAULT '0' COMMENT 'Creation time',
    `created_by`    varchar(100)              DEFAULT ' ' COMMENT 'Founder',
    `modified_on`   int(10) unsigned          DEFAULT '0' COMMENT 'Modification time',
    `modified_by`   varchar(100)              DEFAULT ' ' COMMENT 'Modifier',
    `deleted_on`    int(10) unsigned          DEFAULT '0' COMMENT 'Delete time',
    `deleted_by`    varchar(100)              DEFAULT ' ' COMMENT 'Delete person',
    `is_del`        tinyint(3) unsigned       DEFAULT '0' COMMENT 'Delete 0 = undeleted, 1 = deleted', # public partend
    `state`         tinyint(3) unsigned       DEFAULT '1' COMMENT 'State 0 is disabled, state 1 is enabled'.PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='Article Column Association Management'; # blog user info tableCREATE TABLE `blog_user`
(
    `id`               int(10) unsigned NOT NULL AUTO_INCREMENT,
    `name`             varchar(100)              DEFAULT ' ' COMMENT 'User name',
    `brief`            varchar(200)              DEFAULT ' ' COMMENT 'User signature',
    `avatar_url`       varchar(255)              DEFAULT ' ' COMMENT 'User profile picture',
    `uid`              varchar(100)     NOT NULL DEFAULT ' ' COMMENT 'the user uid',
    `account`          varchar(15)      NOT NULL DEFAULT ' ' COMMENT 'User account',
    `wx_account`       varchar(200)              DEFAULT ' ' COMMENT 'wechat Account',
    `github_address`   varchar(200)              DEFAULT ' ' COMMENT 'making address',
    `weibo_address`    varchar(200)              DEFAULT ' ' COMMENT 'Microblog Address',
    `bilibili_address` varchar(200)              DEFAULT ' ' COMMENT 'Station B address',
    `password_salt`    varchar(15)               DEFAULT ' ' COMMENT 'Password salt',
    `password`         varchar(18)      NOT NULL DEFAULT ' ' COMMENT 'password',
    `wx_id`            varchar(200)              DEFAULT ' ' COMMENT 'User wechat ID',
    `created_on`       int(10) unsigned          DEFAULT '0' COMMENT 'Creation time',
    `modified_on`      int(10) unsigned          DEFAULT '0' COMMENT 'Modification time',
    `deleted_on`       int(10) unsigned          DEFAULT '0' COMMENT 'Logout Time',
    `state`            tinyint(3) unsigned       DEFAULT '1' COMMENT 'Status 0 is disabled, status 1 is enabled, status 2 is logout'.PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='User Information Management';

Copy the code

Writing a data model

We create the model layer under the Model folder to hold the Model objects

package model

type Article struct{
   *Model
   Title string `json:"title"`
   Desc string `json:"desc"`
   CoverImageUrl string `json:"cover_image_url"`
   ContentType uint8 `json:"content_type"`
   Content string `json:"content"`
   ContentUrl string `json:"content_url"`
   State uint8 `json:"state"`
}

func (a Article) TableName(a) string{
   return "blog_article"
}
Copy the code
package model

type ArticleCollection struct{
   *Model
   CollectionID uint32 `json:"collection_id"`
   ArticleID uint32 `json:"article_id"`
   State uint8 `json:"state"`
}

func(ac * ArticleCollection) TableName(a) string{
   return "blog_article_collection"
}
Copy the code
package model

type ArticleTag struct{
   *Model
   TagID uint32 `json:"tag_id"`
   ArticleID uint32 `json:"article_id"`
   State uint8 `json:"state"`
}

func (at ArticleTag) TableName(a) string{
   return "blog_article_tag"
}
Copy the code
package model

// Collection article column model
type Collection struct{
   *Model
    Name string `json:"name"`
   State uint8 `json:"state"`
}

func (c Collection) TableName(a) string{
   return "blog_collection"
}
Copy the code
package model

// Model public Model
type Model struct {
   ID         uint32 `gorm:"primary_key" json:"id"`
   CreatedBy  string `json:"created_by"`
   ModifiedBy string `json:"modified_by"`
   DeletionBy string `json:"deleted_by"`
   CreatedOn  uint32 `json:"created_on"`
   ModifiedOn uint32 `json:"modified_on"`
   DeletedOn  uint32 `json:"deleted_on"`
   IsDel uint8 `json:"is_del"`
}
Copy the code
package model

type Tag struct{
   *Model
   Name string `json:"name"`
   State uint8 `json:"state"`
}

func (t Tag) TableName(a) string {
   return"blog_tag"
}
Copy the code
package model

type User struct {
   ID    uint32 `gorm:"primary_key" json:"id"`
   Name  string `json:"name"`
   Brief string `json:"brief"`
   AvatarUrl string `json:"avatar_url"`
   UID string `json:"uid"`
   Account string `json:"account"`
   WxAccount string `json:"wx_account"`
   GitHubAddress string `json:"github_address"`
   WeiBoAddress string `json:"weibo_address"`
   BilibiliAddress string `json:"bilibili_address"`
   PasswordSalt string `json:"password_salt"`
   Password string `json:"password"`
   WxID string `json:"wx_id"`
   CreatedOn  uint32 `json:"created_on"`
   ModifiedOn uint32 `json:"modified_on"`
   DeletedOn  uint32 `json:"deleted_on"`
   IsDel uint8 `json:"is_del"`
}

func (u User) TableName(a) string{
   return "blog_user"
}
Copy the code

Write route handling methods

package v1

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

type Article struct{}

func NewArticle(a) Article{
   return Article{}
}

func(t Article) Get(c *gin.Context){}
func(t Article) List(c *gin.Context){}
func(t Article) Create(c *gin.Context){}
func(t Article) Update(c *gin.Context){}
func(t Article) Delete(c *gin.Context){}
Copy the code
package v1

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

type Collection struct{}

func NewCollection(a) Collection{
   return Collection{}
}

func(u Collection) Get(c *gin.Context){}
func(u Collection) List(c *gin.Context){}
func(u Collection) Create(c *gin.Context){}
func(u Collection) Update(c *gin.Context){}
func(u Collection) Delete(c *gin.Context){}
Copy the code
package v1

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

type Tag struct{}

func NewTag(a) Tag{
   return Tag{}
}

func(t Tag) Get(c *gin.Context){}
func(t Tag) List(c *gin.Context){}
func(t Tag) Create(c *gin.Context){}
func(t Tag) Update(c *gin.Context){}
func(t Tag) Delete(c *gin.Context){}
Copy the code
package v1

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

type User struct{}

func NewUser(a) User{
   return User{}
}

func(u User) Get(c *gin.Context){}
func(u User) List(c *gin.Context){}
func(u User) Create(c *gin.Context){}
func(u User) Update(c *gin.Context){}
func(u User) Delete(c *gin.Context){}
Copy the code

Register the route processing method with the corresponding routing rule

The complete code

package routers

import (
   "github.com/gin-gonic/gin"
   v1 "myblog-server/internal/routers/api/v1"
)

func NewRouter(a) *gin.Engine {
   
   // Create the gin Engine instance
   r := gin.New()
   // Request log output
   r.Use(gin.Logger())
   // Exception catch processing
   r.Use(gin.Recovery())
    
   // Create a routing processing instance
   article := v1.NewArticle()
   tag := v1.NewTag()
   collection := v1.NewCollection()
   user := v1.NewUser()
    
   // Add a routing group
   apiv1 := r.Group("/api/v1")
   {
      apiv1.POST("/tags",tag.Create)
      apiv1.DELETE("/tags/:id",tag.Delete)
      apiv1.PUT("/tags/:id",tag.Update)
      apiv1.PATCH("/tags/:id/state",tag.Update)
      apiv1.GET("/tags",tag.List)

      apiv1.POST("/collections",collection.Create)
      apiv1.DELETE("/collections/:id",collection.Delete)
      apiv1.PUT("/collections/:id",collection.Update)
      apiv1.PATCH("/collections/:id/state",collection.Update)
      apiv1.GET("/collections",collection.List)

      apiv1.POST("/users",user.Create)
      apiv1.DELETE("/users/:id",user.Delete)
      apiv1.PUT("/users/:id",user.Update)
      apiv1.PATCH("/users/:id/state",user.Update)
      apiv1.GET("/users",user.List)
      apiv1.GET("/users/:id",user.Get)

      apiv1.POST("/articles",article.Create)
      apiv1.DELETE("/articles/:id",article.Delete)
      apiv1.PUT("/articles/:id",article.Update)
      apiv1.PATCH("/articles/:id/state",article.Update)
      apiv1.GET("/articles",article.List)
      apiv1.GET("/articles/:id",article.Get)
   }
   return r
}
Copy the code

Configure the startup portal main.go

package main

import (
   "fmt"
   "myblog-server/internal/routers"
   "net/http"
   "time"
)

func main(a) {
   // Instantiate the route handler
   router := routers.NewRouter()
   // Customize the HTTP Server
   s := &http.Server {
      // Set the listening port
       Addr : ": 8088".// Add the handler we wrote
       Handler: router,
       // Sets the maximum time allowed to read and write
       ReadTimeout : 10 * time.Second,
       WriteTimeout : 10*time.Second,
       // set the maximum number of bytes in the request header to 2^20bytes 1Mb
       MaxHeaderBytes: 1<<20,
   }
   err := s.ListenAndServe()
   iferr ! =nil {
      fmt.Println(err)
   }
}
Copy the code

Verify the start

Run the go run main.go command in the root directory

If the above information appears, it indicates that the route registration is normal. You can actually call it. If it is returned normally, it indicates that the route is successfully started.