Go语言中文手册 · 表单数据解析和绑定

admin 2024-08-15 16:39:47 编程 来源:ZONE.CI 全球网 0 阅读模式

1. 表单数据解析和绑定

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form action="http://localhost:8000/loginForm" method="post" enctype="application/x-www-form-urlencoded">
        用户名<input type="text" name="username"><br>
        密码<input type="password" name="password">
        <input type="submit" value="提交">
    </form>
</body>
</html>
package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

// 定义接收数据的结构体
type Login struct {
    // binding:"required"修饰的字段,若接收为空值,则报错,是必须字段
    User    string `form:"username" json:"user" uri:"user" xml:"user" binding:"required"`
    Pssword string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
}

func main() {
    // 1.创建路由
    // 默认使用了2个中间件Logger(), Recovery()
    r := gin.Default()
    // JSON绑定
    r.POST("/loginForm", func(c *gin.Context) {
        // 声明接收的变量
        var form Login
        // Bind()默认解析并绑定form格式
        // 根据请求头中content-type自动推断
        if err := c.Bind(&form); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        // 判断用户名密码是否正确
        if form.User != "root" || form.Pssword != "admin" {
            c.JSON(http.StatusBadRequest, gin.H{"status": "304"})
            return
        }
        c.JSON(http.StatusOK, gin.H{"status": "200"})
    })
    r.Run(":8000")
}

效果展示:

TypeScript学习笔记 编程

TypeScript学习笔记

TypeScript学习笔记[TOC]TypeScript概述TypeScript是微软开发的一个开源的编程语言,通过在JavaScript的基础上添加静态类型
高德地图JSAPI学习笔记 编程

高德地图JSAPI学习笔记

[toc]概述地图 JS API 2.0 是高德开放平台免费提供的第四代 Web 地图渲染引擎, 以 WebGL 为主要绘图手段,本着“更轻、更快、更易用”的服
golangTCPpush 编程

golangTCPpush

在当今互联网时代,即时通讯成为了人们生活中不可或缺的一部分。而实现即时通讯的关键技术之一就是TCP Push。作为一名专业的golang开发者,我们不仅需要掌握
nodegolang性能对比 编程

nodegolang性能对比

在当前的编程世界中,Node.js和Golang是两种备受瞩目的技术。它们都拥有出色的性能和能力,但在某些方面却存在差异。本文将对Node.js和Golang进
评论:0   参与:  16