Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Golang MVC Project Structure without Any Framework

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

We will create rest end point that will print messaged based on 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.

The strcuture as like below:

  • app/controllers:
  • This Folder contains all controller class and added into controller package.

  • app/models:
  • This folder contains all interfaces, structs and added into models package.

  • app/route:
  • This folder contains route file and added into route package.

  • app/helpers:
  • This folder contains helper class, constant class and added into helper package.

  • config/.env:
  • This folder contains configuration file, like we will add .env file for environment parameters of golang project.

Lets create Golang MVC Architecture Without Any Framework

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

We will create config folder under apmvc_example/app/ folder. We will create .env file that have key value pair of environment variable. We will access that file using joho/godotenv package.We will add below key/value pair for test:

site : "restapiexample.com"

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

Created Models folder under mvc_example/app/ folder and created types.go file.We will add 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 create User type struct that will contains array of user data.

Created Route folder under mvc_example/app/ folder.Added route.go file into this folder.We will add below code into 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 controllers folder into mvc_example/app/ folder.We will add 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 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 file is not loaded successfully, then you will get fatal error into console.We have access site variable using os.Getenv() method.

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

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

Conclusion:

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

The post Golang MVC Project Structure without Any Framework appeared first on Rest Api Example.



This post first appeared on Rest Api Example, please read the originial post: here

Share the post

Golang MVC Project Structure without Any Framework

×

Subscribe to Rest Api Example

Get updates delivered right to your inbox!

Thank you for your subscription

×