Home > Backend Development > Golang > How to build a RESTful API and process JSON responses using Golang?

How to build a RESTful API and process JSON responses using Golang?

WBOY
Release: 2024-05-31 19:49:00
Original
1051 people have browsed it

How to build and process a RESTful API with JSON responses using Golang Steps: Create a Golang project and install Gorilla Mux. Define routes and handle HTTP requests. Install the JSON codec package to use the JSON codec. Handles requests based on the request method and converts the data to JSON and writes the response.

如何使用 Golang 构建 RESTful API 并处理 JSON 响应?

How to use Golang to build a RESTful API and process JSON responses

Prerequisites

  • Understand the basics of Golang
  • Familiar with JSON data format

Build RESTful API

1. Create a Golang project

go mod init <project-name>
Copy after login

2. Install Gorilla Mux Routing package

go get github.com/gorilla/mux
Copy after login

3. Define routing

import (
    "github.com/gorilla/mux"
    "net/http"
)

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", HomeHandler).Methods("GET")
    // ... 其他路由定义
    http.ListenAndServe(":8080", router)
}
Copy after login

4. Process HTTP request

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    // 根据请求方法处理请求
    switch r.Method {
    case "GET":
        // ... 处理 GET 请求
    case "POST":
        // ... 处理 POST 请求
    // ... 其他方法处理
    }
}
Copy after login

Process JSON response

1. Install the JSON codec package

go get github.com/json-iterator/go
Copy after login

2. Use the JSON codec

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

func WriteJSONResponse(w http.ResponseWriter, data interface{}) {
    w.Header().Set("Content-Type", "application/json")
    if err := json.NewEncoder(w).Encode(data); err != nil {
        // 处理错误
    }
}
Copy after login

Practical case

Example API: Get all users

Route definition:

router.HandleFunc("/users", GetAllUsersHandler).Methods("GET")
Copy after login

Request handler:

import (
    "net/http"
    "github.com/json-iterator/go"
)

// ...

func GetAllUsersHandler(w http.ResponseWriter, r *http.Request) {
    users := [...]UserModel{
        {ID: 1, Name: "John Doe"},
        {ID: 2, Name: "Jane Doe"},
    }

    // 将用户模型转换为 JSON 并写入响应
    WriteJSONResponse(w, users)
}
Copy after login

Client:

Send a GET request to the /users endpoint and parse the JSON response.

The above is the detailed content of How to build a RESTful API and process JSON responses using Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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