Home  >  Article  >  Backend Development  >  Golang implements restful

Golang implements restful

WBOY
WBOYOriginal
2023-05-22 12:08:071691browse

Golang is an efficient, fast, safe and reliable programming language. Its lightweight syntax, concurrent programming capabilities, and rich API library make it an ideal language for building high-performance, high-availability applications. In this article, we will introduce how to use Golang to implement RESTful API.

What is RESTful API?

REST (Representational State Transfer) is an architectural style and a design pattern for Web API. RESTful API is an API that communicates with clients using HTTP protocol. It allows using HTTP verbs (GET, POST, PUT, DELETE, etc.) to perform operations (read, create, update and delete resources) on the server. RESTful APIs are designed for scalability, extensibility, and reusability.

Use Golang to implement RESTful API

Below we will use Golang to implement a simple RESTful API. This API will use Gorilla Mux and Gorm to handle routing and database. Gorilla Mux is a powerful HTTP router and scheduler, and Gorm is a fast and simple ORM library.

First, we need to install these libraries. I'm using go mod to manage dependencies. In the project root directory, open a terminal and enter the following command:

go mod init example.com/restful-api
go get github.com/gorilla/mux
go get github.com/jinzhu/gorm
go get github.com/go-sql-driver/mysql

Now, we can start writing code. We need to create the following files:

  • main.go
  • models/user.go
  • handlers/user.go
  1. main.go

main.go is our entry file. We will register routes and start the server in this file. Here is the code:

package main

import (
    "log"
    "net/http"

    "example.com/restful-api/handlers"
    "github.com/gorilla/mux"
)

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

    r.HandleFunc("/users", handlers.GetUsers).Methods("GET")
    r.HandleFunc("/users", handlers.CreateUser).Methods("POST")
    r.HandleFunc("/users/{id}", handlers.GetUser).Methods("GET")
    r.HandleFunc("/users/{id}", handlers.UpdateUser).Methods("PUT")
    r.HandleFunc("/users/{id}", handlers.DeleteUser).Methods("DELETE")

    log.Fatal(http.ListenAndServe(":8080", r))
}

In this code, we use mux.NewRouter() to create a new router and create a new router for each HTTP method (GET, POST, PUT and DELETE ) to register a handler function.

  1. models/user.go

Next, we will define our user data model. We will write it in models/user.go. The following is the code:

package models

import "github.com/jinzhu/gorm"

type User struct {
    gorm.Model
    Name  string `gorm:"not null"`
    Email string `gorm:"not null;unique_index"`
    Age   int    `gorm:"not null"`
}

In this model, we use Gorm's Model structure. It contains common database record fields such as ID, CreatedAt and UpdatedAt fields. We have defined Name, Email and Age fields which will be stored in the database.

  1. handlers/user.go

Finally, we will write our handler function. We will write them in handlers/user.go. Here is the code:

package handlers

import (
    "encoding/json"
    "fmt"
    "net/http"
    "strconv"

    "example.com/restful-api/models"
    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
)

var db *gorm.DB

func init() {
    var err error
    db, err = gorm.Open("mysql", "{username}:{password}@tcp({host}:{port})/{database}")
    if err != nil {
        panic("failed to connect database")
    }
    db.AutoMigrate(&models.User{})
}

func GetUsers(w http.ResponseWriter, r *http.Request) {
    var users []models.User
    db.Find(&users)
    json.NewEncoder(w).Encode(users)
}

func GetUser(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    id, _ := strconv.Atoi(params["id"])
    var user models.User
    db.First(&user, id)
    json.NewEncoder(w).Encode(user)
}

func CreateUser(w http.ResponseWriter, r *http.Request) {
    var user models.User
    json.NewDecoder(r.Body).Decode(&user)
    db.Create(&user)
    json.NewEncoder(w).Encode(user)
}

func UpdateUser(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    id, _ := strconv.Atoi(params["id"])
    var user models.User
    db.First(&user, id)
    json.NewDecoder(r.Body).Decode(&user)
    db.Save(&user)
    json.NewEncoder(w).Encode(user)
}

func DeleteUser(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    id, _ := strconv.Atoi(params["id"])
    var user models.User
    db.Delete(&user, id)
    fmt.Fprintf(w, "User #%d deleted successfully", id)
}

We first use Gorm’s gorm.Open() method to connect to the database and automatically migrate our user model. Next, we wrote five processor functions: GetUsers(), GetUser(), CreateUser(), UpdateUser() and DeleteUser().

GetUsers() The function gets all users from the database and sends them back to the client as a JSON response.

GetUser()The function uses the ID in the URL parameter to find and return individual user information. We used the mux.Vars() method to extract the ID from the request.

CreateUser()The function reads JSON data from the request body and stores the user information into the database.

UpdateUser()The function reads JSON data from the request and updates the corresponding user information using the ID in the URL parameter.

DeleteUser()The function uses the ID in the URL parameter to delete the corresponding user from the database.

Now we have completed all the components of our RESTful API. We can test the API on the local port using tools like Postman or curl.

Summary

Golang is a powerful and easy-to-use language. It is very simple, fast and efficient to implement RESTful API using Golang. We can use Gorilla Mux and Gorm to handle routing and database operations. In this article, we demonstrate how to create a RESTful API using Golang, based on a simple example. Through this article, readers can quickly understand and learn how to use Golang to build RESTful APIs.

The above is the detailed content of Golang implements restful. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:golang delete variableNext article:golang delete variable