» Go: Building Full-Text Search API with ElasticSearch » 2. Index Documents » 2.1 Gin Server

Gin 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/fulltext-books

Its result:

go: creating new go.mod: module literank.com/fulltext-books

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 main.go:

package main

import (
	"net/http"

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

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

	// Define a route for the homepage
	router.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status": "ok",
		})
	})

	// 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] 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 server is runnong on port 8080 now.

Try visiting the URL http://localhost:8080/ in your browser or curl. It should display the json:

{
  "status": "ok"
}

Data model: Book

Data models represent the structure of the data that the API deals with.

Create domain/model/book.go:

Folder structures like domain/model/... is using 4 Layers Architecture Pattern, read more here.

package model

type Book struct {
	Title       string `json:"title"`
	Author      string `json:"author"`
	PublishedAt string `json:"published_at"`
	Content     string `json:"content"`
}