Navigate to that app folder and execute the following command:
$gomodinitapp$goget-ugithub.com/kataras/iris/v12@main# or @latest for the latest stable release.
Environment
Let's start by defining the available environments that our web-application can behave on.
We'll just work on two available environments, the "development" and the "production", as they define the two most common scenarios. The ReadEnv will read from the Env type of a system's environment variable (see main.go in the end of the page).
Create a environment/environment.go file and put the following contents:
packageenvironmentimport ("os""strings")const ( PROD Env="production" DEV Env="development")typeEnvstringfunc (e Env) String() string {returnstring(e)}funcReadEnv(key string, def Env) Env { v :=Getenv(key, def.String())if v =="" {return def } env :=Env(strings.ToLower(v))switch env {case PROD, DEV: // allowed.default:panic("unexpected environment "+ v) }return env}funcGetenv(key string, def string) string {if v := os.Getenv(key); v !="" {return v }return def}
Database
We will use two database management systems, the MySQL and the SQLite. The first one for "production" use and the other for "development".
Create a database/database.go file and copy-paste the following:
We'll need a service that will communicate with a database instance in behalf of our Controller(s).
In our case we will only need a single service, the Greet Service.
For the sake of the example, let's use two implementations of a greet service based on the Environment. The GreetService interface contains a single method of Say(input string) (output string, err error). Create a ./service/greet_service.go file and write the following code:
packageserviceimport ("fmt""app/database""app/environment")// GreetService example service.typeGreetServiceinterface {Say(input string) (string, error)}// NewGreetService returns a service backed with a "db" based on "env".funcNewGreetService(env environment.Env, db database.DB) GreetService { service :=&greeter{db: db, prefix: "Hello"}switch env {case environment.PROD:return servicecase environment.DEV:return&greeterWithLogging{service}default:panic("unknown environment") }}typegreeterstruct { prefix string db database.DB}func (s *greeter) Say(input string) (string, error) {if err := s.db.Exec("simulate a query..."); err !=nil {return"", err } result := s.prefix +" "+ inputreturn result, nil}typegreeterWithLoggingstruct {*greeter}func (s *greeterWithLogging) Say(input string) (string, error) { result, err := s.greeter.Say(input) fmt.Printf("result: %s\nerror: %v\n", result, err)return result, err}
The greeter will be used on "production" and the greeterWithLogging on "development". The GreetService depends on the Environment and the DB.
Models
Continue by creating our HTTP request and response models.
Create a model/request.go file and copy-paste the following code:
packagemodeltypeRequeststruct { Name string`url:"name"`}
The server will accept a URL Query Parameter of name (e.g. /greet?name=kataras) and will reply back with a JSON message.
Controller
MVC Controllers are responsible for controlling the flow of the application execution. When you make a request (means request a page) to MVC Application, a controller is responsible for returning the response to that request.
We will only need the GreetController for our mini web-application. Create a file at controller/greet_controller.go which looks like that:
The GreetController depends on the GreetService. It serves the GET: /greet index path through its Get method. The Get method accepts a model.Request which contains a single field name of Name which will be extracted from the URL Query Parameter 'name' (because it's a GET requst and its url:"name" struct field). And it will respond with a model.Response (JSON) or an error.
The mvc.Application.Register method registers one more dependencies, dependencies can depend on previously registered dependencies too. Thats the reason we pass, first, the Environment(DEV), then the NewDB which depends on that Environment, following by the NewGreetService function which depends on both the Environment(DEV) and the DB.
The mvc.Application.Handle registers a new controller, which depends on the GreetService, for the targeted sub-router of Party("/greet").
Optionally, replace the main.go's app.Register(environment.DEV with environment.PROD, restart the application and refresh. You will see that a new database (sqlite) and another service of (greeterWithLogging) will be binded to the GreetController. With a single change you achieve to completety change the result.