httpservermdl.go 2.12 KiB
Newer Older
Sandeep S. Shewalkar's avatar
Sandeep S. Shewalkar committed
package httpservermdl

import (
	"path/filepath"

	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/constantmdl"
	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/filemdl"
	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/loggermdl"
Sandeep S. Shewalkar's avatar
Sandeep S. Shewalkar committed
	"github.com/gin-gonic/gin"
	"github.com/kardianos/osext"
Sandeep S. Shewalkar's avatar
Sandeep S. Shewalkar committed
)

// GetServer will return the webserver pointer
func GetServer() *gin.Engine {
	// TODO: use sync.Once
	server := gin.New()
	return server
}

// GetServerWithStaticConfig will return the webserver pointer.
// It will also register static middleware
func GetServerWithStaticConfig(staticDirectoryRelativePath string) *gin.Engine {
	// TODO: use sync.Once
	server := gin.New()
	staticPath := checkAndCreateStaticDirectory(staticDirectoryRelativePath)

	if staticPath != "" {
		staticGroup := server.Group(constantmdl.STATIC_URL)
		// 			//staticGroup.Use(jwt.Auth("models.JWTKey"))
		staticGroup.Static("/", staticPath)
	}

	return server
}

// checkAndCreateStaticDirectory will create static directory to
// serve the static contents. Directory will be created at the same location where executable is located
func checkAndCreateStaticDirectory(staticDirectoryRelativePath string) string {

	staticDirectoryPath := ""
	if staticDirectoryRelativePath == "" {
		staticDirectoryRelativePath = constantmdl.STATIC_DIRECTORY_NAME
	}
	executablePath, exePathError := osext.Executable()
	if exePathError != nil {
		loggermdl.LogError("error while fetching executable path : ", exePathError)
		return ""
	}

	dirPath := filepath.Dir(executablePath)
	staticDirectoryPath = dirPath + "/" + staticDirectoryRelativePath

	exists := filemdl.FileAvailabilityCheck(staticDirectoryPath)

	if exists {
		loggermdl.LogInfo("static directory already exists: ", staticDirectoryPath)
		return staticDirectoryPath
	}
	loggermdl.LogInfo("static directory does not exists. creating the new : ", staticDirectoryPath)
	directoryCreationError := filemdl.CreateDirectory(staticDirectoryPath)

	if directoryCreationError != nil {
		loggermdl.LogError("error while creating static directory : ", directoryCreationError)
		return ""
	}
	return staticDirectoryPath

	return ""
}