REST API Tutorial

Golang MVC Project Structure without Any Framework

Summary of learning

This Golang tutorial help to create MVC architecture for your golang project. There are a lot of go frameworks available that follow MVC architecture, but here we will create MVC based go project without any Golang framework, We will use core Golang to create structure.

This Golang tutorial help to create MVC architecture for your golang project. There are a lot of go frameworks available that follow MVC architecture, but here we will create MVC based go project without any Golang framework, We will use core Golang to create structure.

We will create the rest endpoint that will print messages based on the MVC structure go code. We will use http for client and server communication, MUX for routing, MUX package is the powerful URL router and dispatcher.

What MVC Pattern

The Model-View-Controller (MVC) pattern is a popular design pattern for building web applications.

There are three main components: the model, the view, and the controller. In a Go (Golang) project, you can structure your MVC as follows:

  1. Model: This component represents the data and business logic of the application. It handles the storage, retrieval, and manipulation of data. In Go, the model can be represented by structs and other data types.
  2. View: This component is responsible for presenting the data to the user. In Go, the view can be implemented using templates or other presentation libraries.
  3. Controller: This component acts as an intermediary between the model and the view. It receives user input, updates the model accordingly, and decides which view to display. In Go, the controller can be implemented using functions and methods.

Here’s an example of how you can structure a basic MVC project in Go:

  • app/controllers:

This folder contains all controller classes and is added to the controller package.

  • app/models:

This folder contains all interfaces, and structs and is added to the models package.

  • app/route:

This folder contains the route file and is added to the route package.

  • app/helpers:

This folder contains the helper class, and constant class, and is added to the helper package.

  • config/.env:

This folder contains a configuration file, like we will add a .env file for the environment parameters of golang project.

Finally, the main.go file is the entry point for the application, where you’ll configure routes, start the server and initialize dependencies.

Using Golang MVC for REST API development

We will create a go project under gopath working directory, We will create a mvc_example project and main.go file it into this folder.

We will create a config folder under a mvc_example/app/ folder. We will create a .env file that has a key-value pair of the environment variables. We will access that file using joho/godotenv package. We will add the below key/value pair for the test:

site : "restapiexample.com"

Load the .env file into the main function and access the env variable using key 'site', which will return ‘restapiexample.com’.

Created Models folder under mvc_example/app/ folder and created types.go file. We will add the below code into types.go file:

package models

type User struct {
   Data struct {
      ID        int    `json:"id"`
      FirstName string `json:"first_name"`
      LastName  string `json:"last_name"`
      Avatar    string `json:"avatar"`
   } `json:"data"`
}

We have created a User type struct that will contain an array of user data.

Created Route folder under mvc_example/app/ folder.Added route.go file into this folder. We will add below code to route.go file:

package route

import (
   "github.com/gorilla/mux"
   "mvc_example/app/controllers"
)
func GetRoutes() *mux.Router {
    routes := mux.NewRouter().StrictSlash(false)

    routes := routes.PathPrefix("/api/v1/").Subrouter()

    routes.HandleFunc("/hello", controllers.Hello).Methods("GET")

    return routes;
}

Let’s create the controller’s folder into mvc_example/app/ folder. We will add the below code into home.go file:

package controllers

import (
   "fmt"
   "net/http"
   "github.com/gorilla/mux"
   "mvc_example/app/models"
   "encoding/json"
   log "github.com/sirupsen/logrus"
)
func Hello(w http.ResponseWriter, r *http.Request) {
   fmt.Println("Hello, I am home controller!")
   w.WriteHeader(http.StatusOK)
   fmt.Fprintf(w, "Hello, I am home controller!")
}

Created main.go file under mvc_example/app/ folder. We will add the below code into main.go file:

package main

import (
   "github.com/joho/godotenv"
   log "github.com/sirupsen/logrus"
   "os"
   "mvc_example/app/route"
   "net/http"
)

func main() {
   log.Info("Applicatio has been started on : 8080")
   err := godotenv.Load('/config')
   if err != nil {
    log.Fatal("Error loading .env file")
   }

   key := os.Getenv("Site")
   log.Info(key)

   //creating instance of mux
   routes := route.GetRoutes()
   http.Handle("/", routes)
   log.Fatal(http.ListenAndServe(":8080", nil))
}

We have imported godotenv package to access .env file variable, if the file is not loaded successfully, then you will get a fatal error in the console. We have access a site variable using os.Getenv() method.

Also used route package to access routing functionality and handle all routes using GetRoutes() method.

We are running the server on the 8080 port, if this port has already taken other applications then you will get a fatal error.

Conclusion

I have created a simple MVC folder structure and created simple GET type rest call, You can access rest call using 'http://localhost:8080/api/v1/hello'.

If you have requirements that needs our attentioN

Please feel free to contact us

We would love to hear from you

Share with your network

Facebook
Twitter
LinkedIn
WhatsApp
Email

This tutorial is intended to cover all the essentials steps and insights to understand Golang MVC Project Structure without Any Framework

Genislab Technologies

Learn further