Golang实现application/x-www-form-urlencoded到application/json的转换
Golang实现application/x-www-form-urlencoded到application/json的转换 我正在尝试将请求头“content-type”设置为“application/json”。 但是当我提交表单时,请求头中显示的“content-type”是“application/x-www-form-urlencoded”。
HTML中的表单标签
<form action="/home" method="POST">
<input name="email" id="email" type="email" placeholder="Your Email">
<input name="password" id="password" type="password" placeholder="Your Password">
<input type="submit" >
</form>
我在我的处理程序中使用了以下代码来设置内容类型
r.Header.Set("Content-Type", "application/json")
更多关于Golang实现application/x-www-form-urlencoded到application/json的转换的实战教程也可以访问 https://www.itying.com/category-94-b0.html
HTML 表单标签提交的数据是表单类型,使用 AJAX 提交 JSON 数据。
更多关于Golang实现application/x-www-form-urlencoded到application/json的转换的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
实际上,我试图做的是将表单值存储在我的用户模型中。 用户模型
type User struct {
Email string `json:"email"`
Password string `json:"password"`
}
在我的处理函数中:-
func home(w http.ResponseWriter, r *http.Request) {
var user User
r.Header.Set("Content-Type", "application/json")
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
fmt.Println("Error in decoding", err)
}
fmt.Printf("Your username :- %v \n", user.Email)
fmt.Printf("Your password :- %v \n", user.Password)
tpl.ExecuteTemplate(w, "home.gohtml", user)
}
但是,当我提交表单时,在解码到用户结构时出现以下错误信息:-
invalid character 'e' looking for beginning of value
在Go中处理表单提交时,浏览器会自动将Content-Type设置为application/x-www-form-urlencoded,这是HTML表单的默认行为。你无法通过客户端HTML代码直接改变这一点。不过,你可以在服务器端接收表单数据后,将其转换为JSON格式。
以下是一个示例,展示如何在Go服务器端接收application/x-www-form-urlencoded数据,并将其转换为JSON:
package main
import (
"encoding/json"
"net/http"
)
type FormData struct {
Email string `json:"email"`
Password string `json:"password"`
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
// 解析表单数据
if err := r.ParseForm(); err != nil {
http.Error(w, "Failed to parse form", http.StatusBadRequest)
return
}
// 提取表单字段
email := r.FormValue("email")
password := r.FormValue("password")
// 构建结构体
formData := FormData{
Email: email,
Password: password,
}
// 将结构体转换为JSON
jsonData, err := json.Marshal(formData)
if err != nil {
http.Error(w, "Failed to marshal JSON", http.StatusInternalServerError)
return
}
// 设置响应头为application/json
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func main() {
http.HandleFunc("/home", homeHandler)
http.ListenAndServe(":8080", nil)
}
如果你需要在客户端提交JSON数据,必须使用JavaScript来覆盖表单的默认提交行为,并使用fetch或XMLHttpRequest发送JSON数据。例如:
<form id="loginForm">
<input name="email" id="email" type="email" placeholder="Your Email">
<input name="password" id="password" type="password" placeholder="Your Password">
<input type="submit">
</form>
<script>
document.getElementById('loginForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = {
email: document.getElementById('email').value,
password: document.getElementById('password').value
};
fetch('/home', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
});
</script>
对应的Go处理程序:
func homeHandler(w http.ResponseWriter, r *http.Request) {
// 检查内容类型
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
return
}
var formData FormData
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&formData); err != nil {
http.Error(w, "Failed to decode JSON", http.StatusBadRequest)
return
}
// 处理数据...
jsonData, _ := json.Marshal(formData)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
这样就能确保客户端发送的是JSON数据,服务器端也能正确接收和处理。

