golang api build

WBOY
Release: 2023-05-21 14:11:07
Original
791 people have browsed it

Golang is a programming language specifically designed for building high-concurrency services and network applications. Golang has efficient concurrency and network programming capabilities, which makes it the first choice of many developers. To build a Golang API, we need to master many basic concepts and skills, from routing processing to database access and more. This article will introduce how to use Golang to build APIs.

1. Environment preparation

Before you start building the Golang API, you need to install Golang on your computer. You can download the latest version of Golang through the Golang official website (https://golang.org/), or install it through a package manager, such as apt-get or yum, etc. After the installation is complete, enter "go version" in the terminal to verify whether the installation was successful.

2. Dependency package installation

Use the "go get" command in the terminal to install the required dependency packages. Dependent packages are some libraries we often use in the API, such as "gorilla/mux" and "gorm". The installation method is as follows:

go get github.com/gorilla/mux 
go get github.com/jinzhu/gorm 
go get github.com/go-sql-driver/mysql
Copy after login

3. Routing processing

All API requests need to be completed through routing. One of the most popular routing packages in Golang is gorilla/mux, so we will use that as well.

In order to use gorilla/mux, we need to import the package and create a new mux object. In this example, we will create two routes, one to display the API homepage and another to handle our GET requests.

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/", Index)
    router.HandleFunc("/tasks", getTasks).Methods("GET")

    http.ListenAndServe(":8000", router)
}

func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome to my API!")
}

func getTasks(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "You have requested all tasks")
}
Copy after login

In the above code, we created two processing functions, Index and getTasks. The Index function is used to display the API homepage, and getTasks handles all GET requests.

4. Database access

Now we will add database functionality to the API. In this example, we will use a MySQL database and use the gorm library to manage the data.

First, we need to create a database connection. To do this, we need to create a Database struct that contains the connection details. Next, we will create a new "openDB" function to open the connection.

...

import (
    "database/sql"
    "log"

    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
)

type Database struct {
    *gorm.DB
}

func (db *Database) openDB() {
    dsn := "username:password@tcp(127.0.0.1:3306)/godb?charset=utf8&parseTime=True"
    conn, err := sql.Open("mysql", dsn)
    if err != nil {
        log.Fatal(err)
    }

    db.DB = gorm.Open("mysql", conn)
}
Copy after login

We now need to create a new Database object in the main function and open the connection using the openDB function.

db := new(Database)
db.openDB()
Copy after login

Next, we will create a Task Model to associate with our task list. A Model is just a regular Go struct that will be mapped to a table in our MySQL database.

type Task struct {
    Id      int    `gorm:"primary_key;auto_increment"`
    Name    string `gorm:"not null"`
    Content string `gorm:"not null"`
}
Copy after login

In order to create a new task, we will create a handler function called "createTask". This function will receive JSON data from the HTTP request, parse it, and insert it into our database.

func createTask(w http.ResponseWriter, r *http.Request) {
    db := new(Database)
    db.openDB()

    task := &Task{}
    task.Name = r.FormValue("name")
    task.Content = r.FormValue("content")

    db.Create(&task)
    fmt.Fprintln(w, "Task successfully created")
}
Copy after login

We see that the "createTask" function creates a new Database object and Task object at the beginning. It then parses the JSON data from the HTTP request and inserts it into the database by calling the db.Create() method.

Finally, we will update our route "router.HandleFunc" to include the new route.

router.HandleFunc("/tasks", createTask).Methods("POST")
Copy after login

5. Middleware

Middleware is a common technology used to perform operations before or after processing a request. They are widely used not only in Golang but also in other languages. Let’s see how to use middleware to add some additional functionality in Golang API.

In Golang, middleware is a function that takes an HTTP processing function as a parameter. They allow some logic to be executed before or after the request is processed. In the following example, we will create a middleware called "withLogging" that will log the details of all API requests.

func withLogging(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println(r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
}
Copy after login

We see that a new http.Handler function is returned in the function, which records the requested method and URL path. The next.ServeHTTP(w, r) statement calls the next handler, ensuring that the handler continues to process API requests.

Next, we'll update our routes and handlers to include the new logging middleware.

router := mux.NewRouter()

router.Use(withLogging)

router.HandleFunc("/", Index)
router.HandleFunc("/tasks", createTask).Methods("POST")
router.HandleFunc("/tasks", getTasks).Methods("GET")
Copy after login

Now, add the "router.Use(withLogging)" statement before the route, and we will execute the withLogging middleware on all routing requests.

6. Summary

In this article, we introduced how to use gorilla/mux to handle routing in Golang, use gorm to manage MySQL database, and how to use middleware to enhance our API. By understanding these basic concepts and skills, we can start building more complex Golang APIs.

The above is the detailed content of golang api build. 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!