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 结构。

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

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

相关推荐
武子康26 分钟前
Java-07 深入浅出 MyBatis数据库一对多关系模型实战:表结构设计与查询实现
java·后端
花椒技术1 小时前
企业内部 Agent 落地复盘:Gateway、Skill 和二次确认如何串起受控业务执行
后端·agent·ai编程
我是一颗柠檬3 小时前
【MySQL全面教学】MySQL事务与ACID Day9(2026年)
数据库·后端·mysql
枕星而眠3 小时前
数据结构八大排序详解(一):四大简单排序
c语言·数据结构·c++·后端
IT_陈寒3 小时前
React useEffect闭包陷阱差点把我整失业了
前端·人工智能·后端
basketball6163 小时前
HTTP协议返回状态码总结
网络·网络协议·http
苍何4 小时前
爆肝两周,我把 Codex 最全实战指南开源了
后端
bug菌4 小时前
【SpringBoot 3.x 第254节】夯爆了,数据库访问性能优化实战详解!
数据库·spring boot·后端
Rust研习社4 小时前
从碎片化到标准化:cargo-bp 如何重构 Rust 开发逻辑
后端·rust·编程语言
锋行天下5 小时前
一句mysql复杂查询搞崩一个壮汉
后端·mysql·go