golang从http请求中读取xml格式的body,并转成json

文章目录

以下是在 Go 语言中从 HTTP 请求中读取 XML 格式的请求体,并将其转换为 JSON 的方法:

go 复制代码
package main

import (
    "encoding/json"
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type XMLData struct {
    // 根据你的 XML 结构定义字段
    Field1 string `xml:"field1"`
    Field2 string `xml:"field2"`
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    if r.Method!= http.MethodPost {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }

    // 读取 XML 请求体
    body, err := ioutil.ReadAll(r.Body)
    if err!= nil {
        http.Error(w, "Error reading request body", http.StatusBadRequest)
        return
    }

    var xmlData XMLData
    err = xml.Unmarshal(body, &xmlData)
    if err!= nil {
        http.Error(w, "Error unmarshalling XML", http.StatusBadRequest)
        return
    }

    // 将 XML 数据转换为 JSON
    jsonData, err := json.Marshal(xmlData)
    if err!= nil {
        http.Error(w, "Error marshalling to JSON", http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    w.Write(jsonData)
}

func main() {
    http.HandleFunc("/convert", handleRequest)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

在上述代码中:

  • 定义了一个结构体XMLData来表示 XML 的结构,你需要根据实际的 XML 结构修改这个结构体。
  • handleRequest函数处理 HTTP 请求。首先检查请求方法是否为 POST,然后读取请求体,使用xml.Unmarshal将 XML 数据解析到结构体中,最后使用json.Marshal将结构体转换为 JSON 格式并返回给客户端。

请注意,这只是一个简单的示例,实际应用中你可能需要处理更多的错误情况和不同的 XML 结构。

希望本文对你有所帮助!如果你有任何问题或建议,欢迎在评论区留言。

关注我看更多有意思的文章哦!👉👉

相关推荐
北斗落凡尘1 小时前
LangGraph 入门实战(11)--输出模式
后端·python·langchain
demo007x2 小时前
Hermes-Agent 技术架构
前端·后端·agent
__zRainy__4 小时前
Node系列 · Node基础:net 模块
后端·node.js
Diligently_4 小时前
Anolis 系统更新与密码设置&磁盘扩容
java·后端·spring
kyson_4 小时前
大文件切片上传:从“能传”到“可靠”的 Vue 3 + Java 全栈实现
后端
张龙6874 小时前
uv 全面指南:比 pip 快 100 倍的 Python 包管理器,从安装到团队落地
后端·python
用户40966601317515 小时前
Guava 不止有 Lists 和 Maps:Cache、EventBus、Multimap 实战
java·后端
DLYSB_5 小时前
从监控告警到现场处置:用 HTTP API、Modbus TCP 构建声光语音告警系统
网络协议·tcp/ip·http·报警灯
一只叫煤球的猫6 小时前
从 Java 21 到 Java 25:ThreadLocal 以外的选择—— ScopedValue
java·后端·架构