首页 > 其他分享 >golang从http请求中读取xml格式的body,并转成json

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

时间:2024-10-13 15:54:22浏览次数:15  
标签:xml body http err golang XML Error

文章目录

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

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

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

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

标签:xml,body,http,err,golang,XML,Error
From: https://blog.csdn.net/woaijssss/article/details/142892044

相关文章

  • 软件构造,生成算式采用CSV、XML、JSON三种形式进行存储并读取。
    编写代码完成将生成的算式及习题长期保存下来,采用CSV、XML、JSON三种形式进行存储并读取。提交相关代码及运行截图。importrandomimportcsvimportjsonimportxml.etree.ElementTreeasETfromxml.domimportminidom#生成随机算式数据defgenerate_exercises(count......
  • JavaEE: 深入解析HTTP协议的奥秘(1)
    文章目录HTTPHTTP是什么HTTP协议抓包fiddle用法HTTP请求响应基本格式HTTPHTTP是什么HTTP全称为"超文本传输协议".HTTP不仅仅能传输文本,还能传输图片,传输音频文件,传输其他的各种数据.因此它广泛应用在日常开发的各种场景中.HTTP往往是基于传输层的......
  • HTTP协议
    虽然我们说,应用层协议是我们程序猿自己定的。但实际上,已经有大佬们定义了一些现成的,又非常好用的应用层协议,供我们直接参考使用.HTTP(超文本传输协议)就是其中之一,下面介绍HTTP协议认识URL域名:本质就是IP地址平时我们俗称的"网址"其实就是说的URL:统一资源定位......
  • com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery:jar:unknown was n
    com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery:jar:unknownwasnotfoundinhttp://maven.aliyun.com/nexus/content/repositories/central/duringapreviousattempt.Thisfailurewascachedinthelocalrepositoryandresolutionisnotreatte......