HTML Form MongoDB InsertOne – GinGonic Golang Framework 16

HTML Form MongoDB InsertOne – GinGonic Golang Framework 16

[sourcecode lang=”go” autolinks=”false” classname=”myclass” collapse=”false” firstline=”1″ gutter=”true” highlight=”1-3,6,9″ htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false” title=”Source Code main.go”]

//Mongodb insert data via html form(gingonic)
// first install go get go.mongodb.org/mongo-driver/mongo
package main
import (
"context"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// lets create context variable
var ctx = context.TODO()
// lets create collection variable
var collection *mongo.Collection
// initialize mongodb
func init() {
// 2nd value/parameter is url of mongodb
client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
// in result it gives client & err(ignored here)
// lets create database and collection(table)
collection = client.Database("anyname").Collection("anyname")
}
func main() {
// lets create gingonic server
r := gin.Default()
r.Static("/insert", "./static") // we will keep our html file in this folder
// lets create our routes
r.GET("/", func(c *gin.Context) {
// get data from form
name := c.Query("name")
value := c.Query("value")
// lets insert data into mongodb
collection.InsertOne(ctx, bson.D{{"name", name}, {"value", value}})
// lets send some response to user
//c.JSON(200, []string{name,value})
//c.String(200, "success message….")
c.String(200, "success… %s %s", name, value)
// you can use any of the above 3 …
})
r.Run()
}
[/sourcecode]

Source Code – index.html

[sourcecode lang=”html” autolinks=”false” classname=”myclass” collapse=”false” firstline=”1″ gutter=”true” highlight=”1-3,6,9″ htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false” title=”Source Code index.html” language=”sourcecode”]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert data into gingonic/mongodb</title>
</head>
<body>
<!– Create html form –>
<form action="/" method="get">
<!– input fields –one for value and one for name –>
<input type="text" name="name" id="">
<input type="text" name="value" id="">
<!– I need only 2 fields … you increse or decrease –>
<!– submit button –>
<button type="submit">submit</button>
</form>
</body>
</html>

[/sourcecode]

 

TAGS#

gin gonic tutorial
gin-gonic / examples
gin-gonic documentation
gin framework tutorial
gin web framework
gin router
golang gin context
gin router group

Tony BB
 

TonyBB is a Coach , marketer, hypnotist and a founder of RSKVF Production who specializes in providing simple, affordable, and easy to use solutions for Life.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: