In this tutorial, we’ll walk through the steps to create a simple web application using Beego and MongoDB as the database.
Prerequisites
- Go installed on your machine.
- MongoDB installed and running.
- Beego and Bee tool installed (
go get github.com/beego/bee/v2andgo get github.com/beego/beego/v2). - MongoDB driver for Go (
go get go.mongodb.org/mongo-driver).
Step 1: Create a New Beego Project
Open your terminal and create a new Beego project:
bee new beego-mongo-app cd beego-mongo-app
Step 2: Set Up MongoDB Connection
First, install the MongoDB driver for Go if you haven’t:
go get go.mongodb.org/mongo-driver/mongo
Create a file database/mongo.go to handle MongoDB connection:
package database
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
var Client *mongo.Client
var UserCollection *mongo.Collection
func InitMongo() {
var err error
Client, err = mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
err = Client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
UserCollection = Client.Database("beegodb").Collection("users")
}
Step 3: Define the Model
Create a models/user.go file to define the user model:
package models
type User struct {
ID string `json:"id" bson:"_id,omitempty"`
Name string `json:"name" bson:"name"`
Email string `json:"email" bson:"email"`
}
Step 4: Create the Controller
Create a controllers/user.go file to handle HTTP requests:
package controllers
import (
"beego-mongo-app/database"
"beego-mongo-app/models"
"context"
"encoding/json"
"github.com/beego/beego/v2/server/web"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"net/http"
)
type UserController struct {
web.Controller
}
func (c *UserController) Get() {
users := []models.User{}
cursor, err := database.UserCollection.Find(context.TODO(), bson.M{})
if err != nil {
c.Ctx.Output.SetStatus(http.StatusInternalServerError)
c.Ctx.Output.Body([]byte(err.Error()))
return
}
defer cursor.Close(context.TODO())
for cursor.Next(context.TODO()) {
var user models.User
cursor.Decode(&user)
users = append(users, user)
}
c.Data["json"] = users
c.ServeJSON()
}
func (c *UserController) Post() {
var user models.User
json.Unmarshal(c.Ctx.Input.RequestBody, &user)
_, err := database.UserCollection.InsertOne(context.TODO(), user)
if err != nil {
c.Ctx.Output.SetStatus(http.StatusInternalServerError)
c.Ctx.Output.Body([]byte(err.Error()))
return
}
c.Data["json"] = user
c.ServeJSON()
}
Step 5: Register Routes
Modify the routers/router.go file to register the routes:
package routers
import (
"beego-mongo-app/controllers"
"github.com/beego/beego/v2/server/web"
)
func init() {
web.Router("/user", &controllers.UserController{}, "get:Get;post:Post")
}
Step 6: Initialize MongoDB in Main
Modify the main.go file to initialize MongoDB:
package main
import (
"beego-mongo-app/database"
_ "beego-mongo-app/routers"
"github.com/beego/beego/v2/server/web"
)
func main() {
database.InitMongo()
web.Run()
}
Step 7: Run the Application
Start the application:
bee run
Testing the Application
You can test the application using a tool like Postman or curl.
- Get Users:
GET http://localhost:8080/user - Create User:
POST http://localhost:8080/userwith JSON body:{ "name": "John Doe", "email": "[email protected]" }
Conclusion
This tutorial covered the basics of setting up a web application with Beego and MongoDB. You can extend this application by adding more features, such as user authentication, more complex queries, and frontend integration. Beego’s extensive features and MongoDB’s flexibility make this combination a powerful choice for developing web applications in Go.