Closed louishust closed 9 years ago
Easy, your error is located where you are declaring the struct:
type LoginJSON struct {
username string `json:"username" binding:"required"`
password string `json:"password" binding:"required"`
}
As part of GoLang, if the var's name start uncapitalized, it will be private, that's why neither Go or Gin don't let you access it content.
You just need to capitalize first letter of each variable you want to make public. Here is a full working example:
package main
import (
"github.com/gin-gonic/gin"
"fmt"
)
func main() {
g := gin.New()
// Logging middleware
g.Use(gin.Logger())
// Recovery middleware
g.Use(gin.Recovery())
g.POST("/", API_Login_Check)
// Serve
g.Run(":3000")
}
type LoginJSON struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
func API_Login_Check(c *gin.Context) {
var json LoginJSON
c.Bind(&json)
c.JSON(200, json)
// Print response
fmt.Println(json.Username, json.Password)
}
After starting the server you can try quickly with curl
CLI, like this:
curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/
Many thanks to @javierprovecho !
I tried your example works, but when I use ajax to pass the json data, it seems that the data is not passed.
The ajax function like below:
function authenticate(username, password) {
$.ajax
({
type: "POST",
//the url where you want to sent the userName and password to
url: "/login",
dataType: 'json',
async: false,
//json object to sent to the authentication url
data: '{"username": "' + username + '", "password" : "' + password + '"}',
success: function () {
//do any process for successful authentication here
}
});
}
And got the following error:
[GIN] 2014/11/16 - 10:07:14 | 200 | 212.866us | 127.0.0.1:57189 POST /login
Error #01: Required Username
Meta: Operation aborted
The POST is passed to the API_LoginCheck, But the data is missed!! When I use curl it works well, can you help me for this? I know that maybe I use ajax the wrong way,but i can not find the point. `##`
First of all you might be getting CORS issues which would result in that server response and also an error client-side. See the CORS middleware in the Go code below if you are indeed running into this issue.
Secondly, dataType
in the jQuery request object is the wrong option as it sets the Accept
header. You want to use contentType
which sets the content-type
header.
Here it is all together and working:
authenticate("user", "pass");
function authenticate(username, password) {
$.ajax({
type: "POST",
url: "http://localhost:3000/login",
contentType: "application/json",
async: false,
data: '{"username": "' + username + '", "password" : "' + password + '"}',
success: function (res) {
console.log(res);
}
});
}
package main
import (
"github.com/gin-gonic/gin"
"fmt"
)
func main() {
g := gin.New()
// Logging middleware
g.Use(gin.Logger())
// Recovery middleware
g.Use(gin.Recovery())
// CORS middleware
g.Use(CORSMiddleware())
g.POST("/login", LoginCheck)
// Serve
g.Run(":3000")
}
type LoginJSON struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
func LoginCheck(c *gin.Context) {
var json LoginJSON
c.Bind(&json)
c.JSON(200, json)
// Print response
fmt.Println(json.Username, json.Password)
}
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
if c.Request.Method == "OPTIONS" {
c.Abort(200)
return
}
c.Next()
}
}
Lots thanks to @javierprovecho , I change the "data-type" to "content-type", and it works, thank you very much for help!!
Glad it worked out for you!
Hi all, I tried JSON with gin, but it does not work! The html like below:
The js like below:
and the gin router function like below:
When run it, get the following error:
I'm new to gin and web develop, any idea will be appreciated.