golang build blog

WBOY
Release: 2023-05-16 16:23:37
Original
642 people have browsed it

In recent years, Golang (Go language) has gradually become a popular language for Internet development due to its efficient running speed and simple syntax. As a very popular Internet application, blogging has also fully demonstrated the advantages of Golang. In this article, we will introduce how to use Golang to build a simple blog.

Step 1: Install Golang
First, we need to install the Golang environment locally. You can download the latest version of Golang by visiting the official website and install it according to the instructions on the official website. I will not go into details here. After the installation is complete, we need to configure the GOPATH environment variable.

Step 2: Install Gin
In order to build a blog more conveniently, we need to use Gin, a lightweight web framework. You can use the following command in the terminal to install:
go get -u github.com/gin-gonic/gin
After the installation is complete, we need to introduce it into our project.

Step 3: Database design
Next, we need to design a database to store our blog content. We can use relational databases such as MySQL or PostgreSQL, but here we choose to use SQLite. The reason for using SQLite is that it is small and easy to use, and does not require starting a separate server. You can install SQLite using the following command in the terminal:
go get -u github.com/mattn/go-sqlite3
After the installation is complete, we can establish a database connection through the following code:

db, err := sql.Open("sqlite3", "./blog.db")
if err != nil {
    panic(err)
}
defer db.Close()
Copy after login

The above code will first call the sql.Open() method to connect to the database, and at the end call the db.Close() method to release resources. You can set the path where the data file is stored by modifying the second parameter. Here we name the blog's data table posts. You can use the following SQL statement to create the posts data table:

CREATE TABLE posts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title VARCHAR(64) NOT NULL,
    content TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Copy after login

The above SQL statement creates a data table named posts, including id, title, content, created_at and updated_at five fields.

Step 4: Implement addition, deletion, modification and query
After we have the database, we can start to implement the addition, deletion, modification and query function. Here, we can design our interface based on the idea of ​​RESTful API. In the Gin framework, we use the four HTTP methods POST, GET, PUT and DELETE to correspond to add, query, update and delete operations respectively. The following is an example of using the Gin framework:

package main

import (
    "database/sql"
    "net/http"

    "github.com/gin-gonic/gin"
    _ "github.com/mattn/go-sqlite3"
)

type post struct {
    ID        int    `json:"id"`
    Title     string `json:"title"`
    Content   string `json:"content"`
    CreatedAt string `json:"created_at"`
    UpdatedAt string `json:"updated_at"`
}

func main() {
    r := gin.Default()

    db, err := sql.Open("sqlite3", "./blog.db")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    r.GET("/posts", func(c *gin.Context) {
        var p []post
        rows, err := db.Query("SELECT * FROM posts")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()

        for rows.Next() {
            var ps post
            rows.Scan(&ps.ID, &ps.Title, &ps.Content, &ps.CreatedAt, &ps.UpdatedAt)
            p = append(p, ps)
        }
        if err := rows.Err(); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        c.JSON(http.StatusOK, gin.H{"data": p})
    })

    r.POST("/posts", func(c *gin.Context) {
        var p post
        if err := c.ShouldBindJSON(&p); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        result, err := db.Exec("INSERT INTO posts (title, content) VALUES (?, ?)", p.Title, p.Content)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        p.ID, err = result.LastInsertId()
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        c.JSON(http.StatusOK, gin.H{"data": p})
    })

    r.GET("/posts/:id", func(c *gin.Context) {
        var p post

        row := db.QueryRow("SELECT * FROM posts WHERE id = ?", c.Param("id"))
        err := row.Scan(&p.ID, &p.Title, &p.Content, &p.CreatedAt, &p.UpdatedAt)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        c.JSON(http.StatusOK, gin.H{"data": p})
    })

    r.PUT("/posts/:id", func(c *gin.Context) {
        var p post
        if err := c.ShouldBindJSON(&p); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        result, err := db.Exec("UPDATE posts SET title = ?, content = ? WHERE id = ?", p.Title, p.Content, c.Param("id"))
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        p.ID, err = result.LastInsertId()
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        c.JSON(http.StatusOK, gin.H{"data": p})
    })

    r.DELETE("/posts/:id", func(c *gin.Context) {
        _, err := db.Exec("DELETE FROM posts WHERE id = ?", c.Param("id"))
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        c.JSON(http.StatusOK, gin.H{"data": "Post deleted"})
    })

    r.Run(":8080")
}
Copy after login

The above code implements the four methods of GET, POST, PUT and DELETE, and the corresponding request addresses are /posts, /posts/:id, /posts/ :id and /posts/:id. Among them, the GET method is used to query all articles, the POST method is used to add articles, the GET method (with parameters) is used to query articles with a specified ID, the PUT method is used to modify articles, and the DELETE method is used to delete articles.

Step 5: Start the service
After completing the above steps, we can use the following command in the terminal to start the service:
go run main.go
Service startup After success, we can enter http://localhost:8080/posts in the browser to view all articles.

Summary
Through the above steps, we successfully built a blog using Golang, and used the Gin framework and SQLite database to implement the data addition, deletion, modification and query functions. Of course, this is just a very basic example and you can extend it to suit your needs.

The above is the detailed content of golang build blog. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!