تخطَّ إلى المحتوى

نموذج Multipart/Urlencoded

استخدم c.PostForm() وc.DefaultPostForm() لقراءة القيم من إرسال النماذج. تعمل هذه الطرق مع كل من نوعي المحتوى application/x-www-form-urlencoded وmultipart/form-data — وهما الطريقتان القياسيتان التي تُرسل بهما المتصفحات بيانات النماذج.

  • c.PostForm("field") تُرجع القيمة أو سلسلة فارغة إذا كان الحقل مفقوداً.
  • c.DefaultPostForm("field", "fallback") تُرجع القيمة أو القيمة الافتراضية المحددة إذا كان الحقل مفقوداً.
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.POST("/form_post", func(c *gin.Context) {
message := c.PostForm("message")
nick := c.DefaultPostForm("nick", "anonymous")
c.JSON(200, gin.H{
"status": "posted",
"message": message,
"nick": nick,
})
})
router.Run(":8080")
}

اختبره

Terminal window
# URL-encoded form
curl -X POST http://localhost:8080/form_post \
-d "message=hello&nick=world"
# Output: {"message":"hello","nick":"world","status":"posted"}
# Multipart form
curl -X POST http://localhost:8080/form_post \
-F "message=hello" -F "nick=world"
# Output: {"message":"hello","nick":"world","status":"posted"}
# Missing nick -- falls back to default "anonymous"
curl -X POST http://localhost:8080/form_post \
-d "message=hello"
# Output: {"message":"hello","nick":"anonymous","status":"posted"}

انظر أيضاً