golang处理HTTP JSON响应的便捷工具插件库go-respond的使用

golang处理HTTP JSON响应的便捷工具插件库go-respond的使用

go-respond是一个用于处理常见HTTP JSON响应的Go语言包。

安装

go get github.com/nicklaw5/go-respond

使用示例

go-respond的目标是简化准备JSON响应的繁琐工作。下面是一个简单示例:

package main

import (
    "net/http"

    resp "github.com/nicklaw5/go-respond"
)

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

func main() {
    http.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
        users := []User{
            {1, "Billy", "billy@example.com"},
            {2, "Joan", "joan@example.com"},
        }

        resp.NewResponse(w).Ok(users)
    })

    http.ListenAndServe(":8080", nil)
}

响应方法

响应代码 方法名
200 Ok()
201 Created()
202 Accepted()
204 NoContent()
400 BadRequest()
401 Unauthorized()
403 Forbidden()
404 NotFound()
405 MethodNotAllowed()
406 NotAcceptable()
409 Conflict()
410 Gone()
411 LengthRequired()
412 PreconditionFailed()
413 RequestEntityTooLarge()
415 UnsupportedMediaType()
422 UnprocessableEntity()
500 InternalServerError()
501 NotImplemented()
502 BadGateway()
503 ServiceUnavailable()
504 GatewayTimeout()

默认消息

有时你不需要返回特定的内容消息,但又不希望响应体为空。在这种情况下,你可以使用DefaultMessage()来响应包含相应状态码默认消息的JSON。

package main

import (
    "net/http"
    resp "github.com/nicklaw5/go-respond"
)

func main() {
    http.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
        // ...
        if !authenticated {
            resp.NewResponse(w).DefaultMessage().
                Unauthorized(nil)
        }
        // ...
    })
    http.ListenAndServe(":8080", nil)
}

这将响应{"status":401,"message":"Unauthorized"}

错误处理

处理JSON编组响应时可能发生的错误的最佳选择是使用Negroni的Recovery中间件。示例如下:

package main

import (
    "net/http"

    "github.com/urfave/negroni"
    resp "github.com/nicklaw5/go-respond"
)

type Response struct {
    Success bool `json:"success"`
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        resp.NewResponse(w).Ok(&Response{true})
    })

    n := negroni.New()
    recovery := negroni.NewRecovery()
    recovery.ErrorHandlerFunc = func(error interface{}) {
        // 处理意外错误
    }

    n.Use(recovery)
    n.UseHandler(mux)

    http.ListenAndServe(":8080", n)
}

许可证

本软件包根据MIT许可证条款分发。


更多关于golang处理HTTP JSON响应的便捷工具插件库go-respond的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang处理HTTP JSON响应的便捷工具插件库go-respond的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用go-respond简化Golang HTTP JSON响应处理

go-respond是一个轻量级的Golang库,专门用于简化HTTP JSON响应的构建和发送。它提供了一种更直观、更简洁的方式来构建常见的HTTP JSON响应。

安装

go get github.com/nicklaw5/go-respond

基本用法

1. 导入包

import "github.com/nicklaw5/go-respond/respond"

2. 在HTTP处理器中使用

func handler(w http.ResponseWriter, r *http.Request) {
    data := map[string]interface{}{
        "id":    1,
        "name": "John Doe",
        "email": "john@example.com",
    }
    
    // 发送200 OK响应
    respond.WithJSON(w, r, http.StatusOK, data)
}

主要功能

1. 标准响应

// 成功响应 (200)
respond.WithJSON(w, r, http.StatusOK, data)

// 创建成功 (201)
respond.WithJSON(w, r, http.StatusCreated, data)

// 无内容 (204)
respond.WithJSON(w, r, http.StatusNoContent, nil)

2. 错误响应

// 错误响应 (400)
respond.WithError(w, r, http.StatusBadRequest, "Invalid request")

// 未授权 (401)
respond.WithError(w, r, http.StatusUnauthorized, "Authentication required")

// 禁止访问 (403)
respond.WithError(w, r, http.StatusForbidden, "Access denied")

// 未找到 (404)
respond.WithError(w, r, http.StatusNotFound, "Resource not found")

// 服务器错误 (500)
respond.WithError(w, r, http.StatusInternalServerError, "Internal server error")

3. 分页响应

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

func getUsersHandler(w http.ResponseWriter, r *http.Request) {
    users := []User{
        {1, "Alice", "alice@example.com"},
        {2, "Bob", "bob@example.com"},
        {3, "Charlie", "charlie@example.com"},
    }
    
    // 分页响应
    respond.WithPaginatedJSON(w, r, http.StatusOK, users, 1, 10, 100)
}

4. 自定义响应

func customHandler(w http.ResponseWriter, r *http.Request) {
    // 自定义响应结构
    response := struct {
        Status  string      `json:"status"`
        Data    interface{} `json:"data"`
        Message string      `json:"message"`
    }{
        Status:  "success",
        Data:    someData,
        Message: "Operation completed",
    }
    
    respond.WithJSON(w, r, http.StatusOK, response)
}

实际示例

package main

import (
    "net/http"
    "github.com/nicklaw5/go-respond/respond"
)

type Product struct {
    ID    int     `json:"id"`
    Name  string  `json:"name"`
    Price float64 `json:"price"`
}

func main() {
    http.HandleFunc("/products", productsHandler)
    http.ListenAndServe(":8080", nil)
}

func productsHandler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "GET":
        getProducts(w, r)
    case "POST":
        createProduct(w, r)
    default:
        respond.WithError(w, r, http.StatusMethodNotAllowed, "Method not allowed")
    }
}

func getProducts(w http.ResponseWriter, r *http.Request) {
    products := []Product{
        {1, "Laptop", 999.99},
        {2, "Phone", 699.99},
        {3, "Tablet", 399.99},
    }
    
    // 分页响应示例
    respond.WithPaginatedJSON(w, r, http.StatusOK, products, 1, 10, 3)
}

func createProduct(w http.ResponseWriter, r *http.Request) {
    // 假设我们已经解析了请求体并验证了数据
    newProduct := Product{
        ID:    4,
        Name:  "Monitor",
        Price: 249.99,
    }
    
    // 创建成功响应
    respond.WithJSON(w, r, http.StatusCreated, map[string]interface{}{
        "product": newProduct,
        "message": "Product created successfully",
    })
}

优点

  1. 简洁性:减少了样板代码,使响应处理更加简洁
  2. 一致性:确保所有响应遵循相同的结构
  3. 灵活性:既可以使用预设的响应方法,也可以完全自定义
  4. 分页支持:内置分页响应支持,简化了常见API模式

go-respond是一个轻量级但功能强大的工具,特别适合构建RESTful API服务。它不会强制你使用特定的响应结构,而是提供了便捷的方法来构建符合你需求的响应。

回到顶部