» Go: Building Event-Driven Microservices with Kafka » 2. Producer: Web Service » 2.2 Gin Web Server

Gin Web Server

Create a module

Run the go mod init command, giving it the path of the module your code will be in.

go mod init literank.com/event-books

Its result:

go: creating new go.mod: module literank.com/event-books
go: to add module requirements and sums:
        go mod tidy

This command creates a go.mod file in which dependencies you add will be listed for tracking.

Installation

Download and install Gin framework:

go get -u github.com/gin-gonic/gin

This command updates the go.mod file and creates a go.sum file in your project.

Create templates

Create a folder named templates, and move index.html into the folder.

Tune its title:

- <h1 class="text-4xl font-bold">LiteRank Book Store</h1>
+ <h1 class="text-4xl font-bold">{{ .title }}</h1>

{{ .title }} is a template syntax used by the Go HTML template package. Gin, being built on top of this package, utilizes the same syntax for rendering HTML templates.

Create main.go:

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	// Create a new Gin router
	router := gin.Default()

	// Load HTML templates from the templates directory
	router.LoadHTMLGlob("templates/*.html")

	// Define a route for the homepage
	router.GET("/", func(c *gin.Context) {
		// Render the HTML template named "index.html"
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "LiteRank Book Store",
		})
	})

	// Run the server, default port is 8080
	router.Run()
}

Run the program like this:

go run main.go

You will get result lines like below:

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] Loaded HTML Templates (2): 
        - 
        - index.html

[GIN-debug] GET    /                         --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080

Your web server is runnong on port 8080 now.

Try visiting the URL http://localhost:8080/ in your browser. It should display the webpage we designed in the previous section.