Skip to content

Instantly share code, notes, and snippets.

@birowo
Last active December 13, 2018 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save birowo/e3a3301b9f0233004ba9de2be758327b to your computer and use it in GitHub Desktop.
Save birowo/e3a3301b9f0233004ba9de2be758327b to your computer and use it in GitHub Desktop.
golang: contoh skrip untuk menangkap post data json pakai gin
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
type Struct struct {
/* setiap pakai json, huruf pertama dari field struct harus kapital,
misal dicontoh ini: Key1 bukan key1, dst */
Key1 string `json:"key1"`
Key2 string `json:"key2"`
}
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.Writer.WriteHeader(200)
c.Writer.Write([]byte(`<body><script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "/");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText)
}
};
xhr.send(JSON.stringify([{key1: "val1", key2: "val2"},{key1: "valA", key2: "valB"}]));
</script></body>`))
})
r.POST("/", func(c *gin.Context) {
var vSliceStruct []Struct
err := c.BindJSON(&vSliceStruct)
if err != nil {
println(err)
return
}
c.JSON(200, vSliceStruct)
fmt.Printf("%q", vSliceStruct)
})
r.Run(":8080")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment