HTML Form MongoDB InsertOne – GinGonic Golang Framework 16
HTML Form MongoDB InsertOne – GinGonic Golang Framework 16
//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() }
Source Code – index.html
<!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>
golang gingonic framework videos tutorials series
TAGS#
gin gonic tutorial
gin-gonic / examples
gin-gonic documentation
gin framework tutorial
gin web framework
gin router
golang gin context
gin router group