3
votes

I want to create a function to process anykind of forms. I want it to be able to handle any kind of data types. Im trying to use a interface to do this task.

type Person struct {
    name        string 
    lastName    string
}


func HTMLForm(c *gin.Context) {
    var f Person
    c.ShouldBind(&f)
    c.JSON(http.StatusOK, f)
}

// with this function i get the correct info

// output: {"name":"john","lastName":"snow"}

func HTMLForm(c *gin.Context) {
    var f interface{}
    c.ShouldBind(&f)
    c.JSON(http.StatusOK, f)
}

// when i use the interface to make it usefull for any type of that
// i get null

// output: null

func HTMLForm(c *gin.Context) {
    var f interface{}
    ShouldBindJSON(f)
    c.JSON(http.StatusOK, f)
}

// output: null

I want to get, with the interface, the same output I get with "Person" data type.

// Another example of how i am using f

type Login struct {
    User     string 
    Password string 
}

func main() {
    router := gin.Default()

    router.POST("/loginForm", func(c *gin.Context) {
        var f interface{}

        if err := c.ShouldBind(&f); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusOK, f)
    })

    // Listen and serve on 0.0.0.0:8080
    router.Run(":8080")
}

// output: null

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Update

I want to try to explain my problem better. Maybe this update it's more clear.

// Golang code
package main

import (
    "net/http"

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

// Binding from JSON
type Login struct {
    User     string `form:"user" json:"user" xml:"user"  binding:"required"`
    Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

func main() {
    router := gin.Default()

    router.LoadHTMLGlob("templates/*")

    router.GET("/login", GetLogin)
    router.POST("/loginJSON", PostJSONForm)
    router.POST("/loginXML", PostXMLForm)
    router.POST("/loginForm", PostHTMLForm)

    /*
        sudo lsof -n -i :8080
        kill -9 <PID>
    */
    router.Run(":8080")
}

func GetLogin(c *gin.Context) {
    c.HTML(http.StatusOK, "login.tmpl", nil)
}

// Example for binding JSON ({"user": "manu", "password": "123"})
// curl -v -X POST http://localhost:8080/loginJSON -H 'content-type: application/json' '{ "user": "manu", "password"="123" }'
func PostJSONForm(c *gin.Context) {
    //var json Login
    var json interface{}
    //var form map[string]interface{}

    if err := c.ShouldBindJSON(&json); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    /*
        if json.User != "manu" || json.Password != "123" {
            c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
            return
        }
        c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
    */

    c.JSON(http.StatusOK, "json")
    c.JSON(http.StatusOK, json)
}

// Example for binding XML (
//  <?xml version="1.0" encoding="UTF-8"?>
//  <root>
//      <user>user</user>
//      <password>123</password>
//  </root>)
// curl -v -X POST http://localhost:8080/loginXML -H 'content-type: application/json' -d '{ "user": "manu", "password"="123" }'
func PostXMLForm(c *gin.Context) {
    //var xml Login
    var xml interface{}
    //var form map[string]interface{}

    if err := c.ShouldBindXML(&xml); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    /*
        if xml.User != "manu" || xml.Password != "123" {
            c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
            return
        }
        c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
    */

    c.JSON(http.StatusOK, "xml")
    c.JSON(http.StatusOK, xml)
}

// Example for binding a HTML form (user=manu&password=123)
// curl -v -X POST http://localhost:8080/loginForm -H 'content-type: application/json' -d '{ "user": "manu", "password":"123" }'
func PostHTMLForm(c *gin.Context) {
    //var form Login
    var form interface{}
    //var form map[string]interface{}

    // This will infer what binder to use depending on the content-type header.
    if err := c.ShouldBind(&form); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    /*
        if form.User != "manu" || form.Password != "123" {
            c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
            return
        }
        c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
    */

    c.JSON(http.StatusOK, "html")
    c.JSON(http.StatusOK, form)
}

//Template
<h1>Login</h1>
<form action="/loginForm" method="POST">
    <label>user:</label><br>
    <input type="text" name="user"><br>

    <label>password:</label><br>
    <input type="text" name="password"><br>

    <input type="submit">
</form>
  1. I have tried all this different variations. Just one works, I explain more below.

  2. It works perfect if I use "var form Login" instead of "var from interface{}". But I need it to be able to work with any data type, so I need it to work with interface{}.

  3. I have had a "successful" output, just with one of interface{} tries:

$ curl -X POST http://localhost:8080/loginForm -H 'content-type: application/json' -d '{ "user": "manu", "password":"123" }'

output:"html"{"password":"123","user":"manu"}

  1. But when I use it on a HTML form, on a browser, with that template I posted i get:

output: "html"null

  1. Im not sure if what I get (point 3) its really a sucessfull output. When I use the Login var, it works fine, with curl and brower, the output it's inverted:

$ curl -X POST http://localhost:8080/loginForm -H 'content-type: application/json' -d '{ "user": "manu", "password":"123" }'

ouput:"html"{"user":"manu","password":"123"}

This is all information I could get till now.

1
use map[string]interface{} instead of interface{}big pigeon

1 Answers

0
votes

Do you try to use ShouldBindJSON? Because it has to know which type your want to be

ShouldBind checks the Content-Type to select a binding engine automatically, Depending the "Content-Type" header different bindings are used:

from source code of gin:

// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
func (c *Context) ShouldBindJSON(obj interface{}) error {
    return c.ShouldBindWith(obj, binding.JSON)
}

Update: In your case, it work for me ?


router := gin.Default()

    router.POST("/loginForm", func(c *gin.Context) {
        var f interface{}

        if err := c.ShouldBindJSON(&f); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        log.Print(f)
        c.JSON(http.StatusOK, f)
    })

    // Listen and serve on 0.0.0.0:8080
    router.Run(":8080")

Example login

curl -X POST -H "Content-Type: application/json" \
     --data '{"username":"xyz","password":"xyz"}'  localhost:8080/loginForm

Result

[GIN-debug] POST   /loginForm                --> main.main.func1 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8080
map[password:xyz username:xyz]
[GIN] 2019/04/23 - 10:07:00 | 200 |     239.317µs |             ::1 | POST     /loginForm


//////////////////////////////////

package main

import (
    "net/http"

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

// Binding from JSON
type Login struct {
    User     string `form:"user" json:"user" xml:"user"  binding:"required"`
    Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

func main() {
    router := gin.Default()

    router.LoadHTMLGlob("templates/*")

    router.GET("/login", func(c *gin.Context) {
        c.HTML(http.StatusOK, "login.tmpl", nil)
    })

    // Example for binding a HTML form (user=manu&password=123)
    router.POST("/loginForm", func(c *gin.Context) {
        var form interface{}
        // This will infer what binder to use depending on the content-type header.
        if err := c.ShouldBind(&form); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusOK, form)
    })

    // Listen and serve on 0.0.0.0:8080
    router.Run(":8080")
}

//the template

<h1>Login</h1>
<form action="/loginForm" method="POST">
    <label>user:</label><br>
    <input type="text" name="user"><br>

    <label>password:</label><br>
    <input type="text" name="password"><br>

    <input type="submit">
</form>

//I get null when I use de HTML from, when I try the curl command, it works