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
package main
import (
// 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 ...

Source Code – index.html

<!DOCTYPE html>
<html lang="en">
<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>
<!– 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>



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: