Post and Get API with Beego

Post and Get API with Beego

In our previous article we have discussed how to start with Beego framework in Golang. In this article, we will be discussing how we can create post and get api using Beego framework.

First of all create a directory (for example: user-service) and open it in your favorite code editor. Now, open terminal and run below command to create go module.
go mod init user-service

We are going to use below directory structure.
user-service
– model
– controller
– main.go

As we are going to create user-service, let create a model class user in user.go file inside model directory and paste below code.

package model

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

Now we have a model class, next step is to create a controller called UserController in controller directory in which we will define two functions
AddUser : It is a post api call which accept user in body and save it into a slice (users)
GetUsers : It is a get api call which returns all users stored in slice (users)

package controller

import (
	"user-service/model"
	"encoding/json"

	"github.com/beego/beego/v2/server/web"
)

var users []model.User = []model.User{}

type UserController struct {
	web.Controller
}

func (ctrl *UserController) AddUser() {
	input := model.User{}

	if err := json.Unmarshal(ctrl.Ctx.Input.RequestBody, &input); err != nil {
		ctrl.Data["json"] = err.Error()
	}

	users = append(users, input)

	ctrl.Data["json"] = input
	ctrl.ServeJSON()
}

func (ctrl *UserController) GetUsers() {
	ctrl.Data["json"] = users
	ctrl.ServeJSON()
}

Upto this point, we will have model and controller class for user-service. Now, we are going to create router for our apis (post and get). In main.go file we create main function and initialize our controller class and define our endpoints.

package main

import (
	"user-service/controller"

	"github.com/beego/beego/v2/server/web"
)

func main() {
	// create contr
	ctrl := &controller.UserController{}

	web.BConfig.CopyRequestBody = true

	web.Router("/user", ctrl, "post:AddUser")
	web.Router("/user", ctrl, "get:GetUsers")

	web.Run()
}

Note: use command go get github.com/beego/beego/v2/server/web in terminal in case you are getting error for Beego framework import.

Now we are ready to run our user-service. Use command go run main.go to run it. This will start a local server at your machine at port 8080. Open Postman and use our rest endpoints.

Output :
AddUser

GetUsers

Leave a Reply

Your email address will not be published. Required fields are marked *