Creating new Controller - Sharykhin/go-modular GitHub Wiki

You can create a new controller as in module as in controller package. The way of initializing the new controller is the same as for modules as for package controller, so let's look on example in package controller:

First of all you have to create a new file, ExampleController.go

package controller

import "net/http"
import errorComponent "project/todos/core/components/error"
import sessionComponent "project/todos/core/components/session"


type ExampleController struct {
	BaseController
}

func (ctrl *IndexController) IndexAction(res http.ResponseWriter, req *http.Request) error {

		
	flashMessage := ctrl.GetFlashMessages(res,req,"success")
		
	if err := ctrl.Render(res,req, "index", nil, struct {	
		Title string
		FlashMessage []interface{}
	}{	
		Title: "Exmaple controller",
		FlashMessage: flashMessage,
		
	}); err != nil {
		return err
	}
	return nil
}

func (ctrl *IndexController) CreateAction(res http.ResponseWriter, req *http.Request) error {

	if req.Method != "POST" {
		errorComponent.ErrorHandler(res, req, http.StatusMethodNotAllowed,"Method Not Allowed")
		return nil
		
	}	
	
	session, _ := sessionComponent.Store.Get(req, "session")
	session.AddFlash("Add flash message","success")
	session.Save(req,res)

	http.Redirect(res,req, "/" , http.StatusFound)
	return nil

}

As you can see we have defined two Actions: Index and Create. So you can put any logic into actions, it doesn't matter.