Home >Backend Development >Golang >How to build a RESTful API and handle errors using Golang?

How to build a RESTful API and handle errors using Golang?

WBOY
WBOYOriginal
2024-05-31 19:48:001040browse

This article shows the steps to build a RESTful API using Golang, including importing the necessary packages, creating a router, defining handlers, registering routes, and starting the server. In addition, instructions are provided for handling error conditions, such as returning error messages and correct HTTP status codes.

如何使用 Golang 构建 RESTful API 并处理错误?

Use Golang to build a RESTful API and handle errors

Building a RESTful API in Golang is simple and efficient. This article will take you step by step to understand how to create an API and Handle common error scenarios.

1. Import necessary packages

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

    "github.com/gorilla/mux"
)

2. Create router

r := mux.NewRouter()

3. Define handler

func indexHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, World!")
}

func postHandler(w http.ResponseWriter, r *http.Request) {
    var data map[string]interface{}
    if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }

    log.Printf("Received data: %v", data)
    json.NewEncoder(w).Encode(map[string]interface{}{"status": "success"})
}

4. Register route

r.HandleFunc("/", indexHandler).Methods("GET")
r.HandleFunc("/post", postHandler).Methods("POST")

5. Start the server

http.ListenAndServe(":8080", r)

Practical case

Create a simple API to store and retrieve user data:

type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func userHandler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "GET":
        json.NewEncoder(w).Encode([]User{{Name: "John", Email: "john@example.com"}})
    case "POST":
        var user User
        if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
            http.Error(w, "Invalid JSON", http.StatusBadRequest)
            return
        }
        fmt.Fprint(w, "User created:", user)
    default:
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    }
}

Then register the route:

r.HandleFunc("/users", userHandler)

Now you can easily test the API using curl or other tools:

curl -X GET localhost:8080/users

The above is the detailed content of How to build a RESTful API and handle errors using Golang?. 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