求教老师,请问apiHander中,暴露的方法怎么获取json请求,谢谢

来源:7-5 route 对外API的开发

崛起的架构师

2024-05-28

老师您好,打扰您,您教学apiHander中方法接收的有get,还有post是表单提交,我想知道post接收json请求方式,方法里怎么处理。例如:req *svcApi.Request对象怎么获取post json请求对象。感恩感谢。

message Pair {
string key = 1;
repeated string values = 2;
}
message Request {
string method = 1;
string path = 2;
map<string, Pair> header = 3;
map<string, Pair> get = 4;
map<string, Pair> post = 5;
string body = 6;
string url = 7;
}

写回答

1回答

Cap

2024-09-24

这个涉及到框架的底层,我大致的给代码和说明说下

package handler

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

    "github.com/go-micro/go-micro/v3"
    "your_project/proto/svcApi"  // 替换为您实际的 proto 生成的包路径
)

// APIHandler 结构体用于处理 API 请求
type APIHandler struct {
    // 可以在这里添加任何需要的依赖,比如服务客户端等
}

// NewAPIHandler 创建一个新的 APIHandler
func NewAPIHandler() *APIHandler {
    return &APIHandler{}
}

// HandlePostJSON 处理 POST JSON 请求
func (h *APIHandler) HandlePostJSON(req *svcApi.Request, rsp *svcApi.Response) error {
    // 检查请求方法
    if req.Method != http.MethodPost {
        return h.createErrorResponse(rsp, http.StatusMethodNotAllowed, "Method not allowed")
    }

    // 检查 Content-Type
    contentType := h.getContentType(req)
    if contentType != "application/json" {
        return h.createErrorResponse(rsp, http.StatusUnsupportedMediaType, "Unsupported Content-Type")
    }

    // 解析 JSON 数据
    var requestData map[string]interface{}
    err := json.Unmarshal([]byte(req.Body), &requestData)
    if err != nil {
        return h.createErrorResponse(rsp, http.StatusBadRequest, "Invalid JSON format")
    }

    // 处理请求数据
    responseData, err := h.processRequest(requestData)
    if err != nil {
        return h.createErrorResponse(rsp, http.StatusInternalServerError, "Error processing request")
    }

    // 创建成功响应
    return h.createSuccessResponse(rsp, responseData)
}

// 辅助方法

func (h *APIHandler) getContentType(req *svcApi.Request) string {
    if ctHeader, ok := req.Header["Content-Type"]; ok && len(ctHeader.Values) > 0 {
        return ctHeader.Values[0]
    }
    return ""
}

func (h *APIHandler) createErrorResponse(rsp *svcApi.Response, statusCode int, message string) error {
    rsp.StatusCode = int32(statusCode)
    rsp.Header = map[string]*svcApi.Pair{
        "Content-Type": {Values: []string{"application/json"}},
    }
    body, _ := json.Marshal(map[string]interface{}{
        "success": false,
        "message": message,
    })
    rsp.Body = string(body)
    return nil
}

func (h *APIHandler) createSuccessResponse(rsp *svcApi.Response, data interface{}) error {
    rsp.StatusCode = http.StatusOK
    rsp.Header = map[string]*svcApi.Pair{
        "Content-Type": {Values: []string{"application/json"}},
    }
    body, _ := json.Marshal(map[string]interface{}{
        "success": true,
        "data":    data,
    })
    rsp.Body = string(body)
    return nil
}

func (h *APIHandler) processRequest(requestData map[string]interface{}) (interface{}, error) {
    // 在这里实现您的业务逻辑
    // 例如:
    // return someService.DoSomething(requestData)
    
    // 这里只是一个示例实现
    return map[string]string{"message": "Request processed successfully"}, nil
}


0
1
崛起的架构师
感谢老师
2024-09-30
共1条回复

Go 开发者的涨薪通道,自主开发 PaaS 平台核心功能

云原生专家带来稀缺的 PaaS 平台实战,带你直击核心业务+技术

400 学习 · 169 问题

查看课程