dongxiangxie8181 2017-02-15 11:24
浏览 484

进入Gin-Gonic,从POST请求获取文本

I'm starting to develop a REST API using Go and package Gin-Gonic. The idea is to create a REST API that receives POST requests in a JSON format and redirects this call to another application (also a API). Here is a peace of code:

package main

import (
    "fmt"

    "github.com/gin-gonic/gin"
    "net/http"
)
func main() {
    r := gin.Default()
    r.GET("/status", func(c *gin.Context) {
        c.String(200, "on")
    })

    r.GET("/user/:name", func(c *gin.Context) {
        name := c.Param("name")
        c.String(http.StatusOK, "Hello %s", name)
    })

    r.GET("/user/:name/:action", func(c *gin.Context) {
        name := c.Param("name")
        action := c.Param("action")
        message := name + " is " + action
        c.String(http.StatusOK, message)
    })

    r.POST("/foo", func(c *gin.Context) {
        fmt.Printf("%s", "At least I got here")
        message := c.PostForm() //???
        c.JSON(200, gin.H{"status": message}) //???
    })
    r.Run(":8080") // listen an
}

At function r.Posts("/foo",...) I would like c.JSON to send me back the full JSON that I sent:

curl -H "Content-Type: application/json" -X POST -d '{"user":"xyz","password":"xyz"}' http://localhost:8080/foo

I've seen examples where they bind the JSON file by creating a struct with the same structure as the input JSON (check Gin-Gonic examples at https://github.com/gin-gonic/gin ). However I only need to resend the full string without taking care of the format. Any ideas?

  • 写回答

2条回答 默认 最新

  • dsam70528 2017-02-15 11:35
    关注

    Try this example:

    package main
    
    import (
        "fmt"
    
        "github.com/gin-gonic/gin"
        "net/http"
    )
    
    type LOGIN struct{
        USER string `json:"user" binding:"required"`
        PASSWORD string `json:"password" binding:"required"`
    }
    
    func main() {
        r := gin.Default()
        r.GET("/status", func(c *gin.Context) {
            c.String(200, "on")
        })
    
        r.GET("/user/:name", func(c *gin.Context) {
            name := c.Param("name")
            c.String(http.StatusOK, "Hello %s", name)
        })
    
        r.GET("/user/:name/:action", func(c *gin.Context) {
            name := c.Param("name")
            action := c.Param("action")
            message := name + " is " + action
            c.String(http.StatusOK, message)
        })
    
        r.POST("/foo", func(c *gin.Context) {
            var login LOGIN
            c.BindJSON($login)
            c.JSON(200, gin.H{"status": login.USER}) //???
        })
        r.Run(":8080") // listen an
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类