Skip to content

Commit aca97d4

Browse files
committed
added api/html prefix functionality
1 parent 0afc13e commit aca97d4

File tree

4 files changed

+138
-21
lines changed

4 files changed

+138
-21
lines changed

config/config.go

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,20 @@ var OAuth2TokenMap map[string]model.OAuth2MapToken
1313

1414
type HomerSettingServer struct {
1515
MAIN_SETTINGS struct {
16-
IsolateQuery string `default:""`
17-
IsolateGroup string `default:""`
18-
UseCaptureIDInAlias bool `default:"false"`
19-
DefaultAuth string `default:"internal"`
20-
EnableGravatar bool `default:"false"`
21-
GravatarUrl string `default:"https://www.gravatar.com/avatar/%s.jpg"`
22-
OAuth2Config oauth2.Config
23-
GlobalToken *oauth2.Token
24-
UserGroups []string `default:"[admin,user,support]"`
25-
SubscribeHttpClient *http.Client
26-
TimeoutHttpClient uint32 `default:"10"`
16+
IsolateQuery string `default:""`
17+
IsolateGroup string `default:""`
18+
UseCaptureIDInAlias bool `default:"false"`
19+
DefaultAuth string `default:"internal"`
20+
EnableGravatar bool `default:"false"`
21+
GravatarUrl string `default:"https://www.gravatar.com/avatar/%s.jpg"`
22+
OAuth2Config oauth2.Config
23+
GlobalToken *oauth2.Token
24+
UserGroups []string `default:"[admin,user,support]"`
25+
SubscribeHttpClient *http.Client
26+
TimeoutHttpClient uint32 `default:"10"`
27+
APIPrefix string `default:""`
28+
ApplyPrefixIndexHtml bool `default:"false"`
29+
RootPath string `default:"/usr/local/homer/dist"`
2730
}
2831

2932
GRAFANA_SETTINGS struct {

main.go

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ import (
3131
"encoding/json"
3232
"flag"
3333
"fmt"
34-
"io/ioutil"
3534
"net/http"
3635
"net/url"
3736
"os"
@@ -129,6 +128,7 @@ type CommandLineFlags struct {
129128
LogPathWebApp *string `json:"path_log_webapp"`
130129
LogName *string `json:"log_name_webapp"`
131130
APIPrefix *string `json:"api_prefix"`
131+
ApplyPrefixToIndex *bool `json:"apply_prefix_to_index"`
132132
WatchConfig *bool `json:"watch_config"`
133133
ShowCurrentConfig *bool `json:"show_current_config"`
134134
GenerateJwtSecret *bool `json:"generate_jwt_secret"`
@@ -194,6 +194,7 @@ func initFlags() {
194194
appFlags.LogName = flag.String("webapp-log-name", "", "the name prefix of the log file.")
195195
appFlags.LogPathWebApp = flag.String("webapp-log-path", "", "the path for the log file.")
196196
appFlags.APIPrefix = flag.String("webapp-api-prefix", "", "API prefix.")
197+
appFlags.ApplyPrefixToIndex = flag.Bool("apply-prefix-to-index", false, "Apply API/Html prefix to index page")
197198
appFlags.WatchConfig = flag.Bool("watch-config", false, "Watch the configuration for changes")
198199
appFlags.ShowCurrentConfig = flag.Bool("show-current-config", false, "print out the current config and exit")
199200

@@ -284,6 +285,14 @@ func main() {
284285
os.Exit(0)
285286
}
286287

288+
if *appFlags.APIPrefix != "" {
289+
config.Setting.MAIN_SETTINGS.APIPrefix = *appFlags.APIPrefix
290+
}
291+
292+
if *appFlags.ApplyPrefixToIndex || config.Setting.MAIN_SETTINGS.ApplyPrefixIndexHtml {
293+
heputils.ApplyPrefixIndexHtml(*appFlags.APIPrefix, config.Setting.MAIN_SETTINGS.RootPath)
294+
}
295+
287296
// configure to serve WebServices
288297
configureAsHTTPServer()
289298

@@ -496,6 +505,20 @@ func configureServiceObjects() {
496505
config.Setting.MAIN_SETTINGS.TimeoutHttpClient = viper.GetUint32("http_client.connection_timeout")
497506
}
498507

508+
if viper.IsSet("hhttp_settings.api_prefix") {
509+
config.Setting.MAIN_SETTINGS.APIPrefix = viper.GetString("http_settings.api_prefix")
510+
}
511+
512+
/***********************************/
513+
if viper.IsSet("http_settings.apply_prefix_to_index") {
514+
config.Setting.MAIN_SETTINGS.ApplyPrefixIndexHtml = viper.GetBool("http_settings.apply_prefix_to_index")
515+
}
516+
517+
/***********************************/
518+
if viper.IsSet("http_settings.root") {
519+
config.Setting.MAIN_SETTINGS.RootPath = viper.GetString("http_settings.root")
520+
}
521+
499522
/* check the auth type */
500523
if config.Setting.MAIN_SETTINGS.DefaultAuth == "" {
501524
config.Setting.MAIN_SETTINGS.DefaultAuth = "internal"
@@ -736,7 +759,7 @@ func configureAsHTTPServer() {
736759
e.GET("/doc/api/json", func(c echo.Context) error {
737760

738761
logger.Debug("Middle swagger ware: ", c.Request().RequestURI)
739-
dataJson, err := ioutil.ReadFile(config.Setting.SWAGGER.ApiJson)
762+
dataJson, err := os.ReadFile(config.Setting.SWAGGER.ApiJson)
740763
if err != nil {
741764
return httpresponse.CreateBadResponse(&c, http.StatusBadRequest, webmessages.SwaggerFileNotExistsError)
742765
}
@@ -748,13 +771,17 @@ func configureAsHTTPServer() {
748771
}
749772

750773
/* static */
751-
rootPath := viper.GetString("http_settings.root")
752-
if rootPath == "" {
753-
rootPath = "/usr/local/homer/dist"
774+
//Api Prefix
775+
if config.Setting.MAIN_SETTINGS.APIPrefix != "" {
776+
groupPrefix := e.Group(config.Setting.MAIN_SETTINGS.APIPrefix)
777+
groupPrefix.Use(middleware.StaticWithConfig(middleware.StaticConfig{
778+
Root: config.Setting.MAIN_SETTINGS.RootPath,
779+
HTML5: true,
780+
}))
754781
}
755782

756783
/* static */
757-
e.Use(middleware.Static(rootPath))
784+
e.Use(middleware.Static(config.Setting.MAIN_SETTINGS.RootPath))
758785

759786
/* enable guzip*/
760787
if gzipEnable := viper.GetBool("http_settings.gzip"); gzipEnable {
@@ -781,7 +808,13 @@ func configureAsHTTPServer() {
781808
Skipper: func(c echo.Context) bool {
782809

783810
if strings.HasSuffix(c.Request().RequestURI, ".js") {
784-
if heputils.FileExists(rootPath + c.Request().RequestURI + ".gz") {
811+
812+
//Prefix
813+
if *appFlags.APIPrefix != "" && strings.HasPrefix(c.Request().RequestURI, *appFlags.APIPrefix) {
814+
c.Request().RequestURI = strings.TrimPrefix(c.Request().RequestURI, *appFlags.APIPrefix)
815+
}
816+
817+
if heputils.FileExists(config.Setting.MAIN_SETTINGS.RootPath + c.Request().RequestURI + ".gz") {
785818
c.Response().Header().Set(echo.HeaderContentEncoding, "gzip")
786819
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJavaScript)
787820
return false
@@ -796,7 +829,7 @@ func configureAsHTTPServer() {
796829
}))
797830
}
798831

799-
registerGetRedirect(e, rootPath)
832+
registerGetRedirect(e, config.Setting.MAIN_SETTINGS.RootPath)
800833

801834
/* decoder */
802835
servicesObject.externalDecoder.Active = false
@@ -1775,7 +1808,7 @@ func sendIndexHtml(c echo.Context, path string) error {
17751808
return c.File(path + "/index.html")
17761809
}
17771810

1778-
content, err := ioutil.ReadFile(path + "/index.html")
1811+
content, err := os.ReadFile(path + "/index.html")
17791812
if err != nil {
17801813
logger.Debug("not found....", err.Error())
17811814
return c.String(http.StatusNotFound, "Not found")

utils/heputils/heputils.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"log"
99
"math/rand"
1010
"os"
11+
"path/filepath"
1112
"reflect"
1213
"regexp"
1314
"strconv"
@@ -383,3 +384,83 @@ func GetSQLEqualityOperator(isLike bool) string {
383384
}
384385
return "="
385386
}
387+
388+
func ApplyPrefixIndexHtml(prefix, root string) error {
389+
390+
indexHtml := filepath.Join(root, "index.html")
391+
392+
// Check if file exists in the rootpath of dist
393+
if FileExists(indexHtml) {
394+
395+
// Create the content with the configured prefix
396+
if prefix != "" && !strings.HasSuffix(prefix, "/") {
397+
prefix = prefix + "/"
398+
}
399+
400+
// Read the file content
401+
content, err := os.ReadFile(indexHtml)
402+
if err != nil {
403+
return fmt.Errorf("error reading file: %w", err)
404+
}
405+
406+
// Convert to string for easier manipulation
407+
htmlContent := string(content)
408+
409+
// Try different patterns to find and replace the PREFIX configuration
410+
411+
// Pattern 1: Complete window.GLOBAL_CONFIG with PREFIX assignment
412+
re1 := regexp.MustCompile(`window\.GLOBAL_CONFIG\s*=\s*\{\s*PREFIX:\s*"[^"]*"\s*\};`)
413+
newConfig := fmt.Sprintf(`window.GLOBAL_CONFIG={PREFIX:"%s"};`, prefix)
414+
415+
// Pattern 2: Just the PREFIX property
416+
re2 := regexp.MustCompile(`PREFIX:\s*"[^"]*"`)
417+
prefixValue := fmt.Sprintf(`PREFIX: "%s"`, prefix)
418+
419+
// Pattern 3: Commented PREFIX line
420+
re3 := regexp.MustCompile(`//\s*PREFIX:\s*"[^"]*"`)
421+
uncommentedPrefix := fmt.Sprintf(`PREFIX: "%s"`, prefix)
422+
423+
// Pattern 4: Empty GLOBAL_CONFIG
424+
re4 := regexp.MustCompile(`window\.GLOBAL_CONFIG\s*=\s*\{\s*\};`)
425+
configWithPrefix := fmt.Sprintf(`window.GLOBAL_CONFIG={PREFIX:"%s"};`, prefix)
426+
427+
// Pattern 5: GLOBAL_CONFIG with commented PREFIX
428+
re5 := regexp.MustCompile(`window\.GLOBAL_CONFIG\s*=\s*\{\s*//\s*PREFIX:\s*"[^"]*"\s*\};`)
429+
configWithUncommentedPrefix := fmt.Sprintf(`window.GLOBAL_CONFIG={PREFIX:"%s"};`, prefix)
430+
431+
// Try each pattern in sequence
432+
updatedContent := htmlContent
433+
434+
if re1.MatchString(htmlContent) {
435+
updatedContent = re1.ReplaceAllString(htmlContent, newConfig)
436+
} else if re5.MatchString(htmlContent) {
437+
// Replace GLOBAL_CONFIG with commented PREFIX
438+
updatedContent = re5.ReplaceAllString(htmlContent, configWithUncommentedPrefix)
439+
} else if re4.MatchString(htmlContent) {
440+
// Replace empty GLOBAL_CONFIG
441+
updatedContent = re4.ReplaceAllString(htmlContent, configWithPrefix)
442+
} else if re3.MatchString(htmlContent) {
443+
// Replace commented PREFIX
444+
updatedContent = re3.ReplaceAllString(htmlContent, uncommentedPrefix)
445+
} else if re2.MatchString(htmlContent) {
446+
// Replace PREFIX property
447+
updatedContent = re2.ReplaceAllString(htmlContent, prefixValue)
448+
}
449+
450+
// Check if a replacement was made
451+
if htmlContent == updatedContent {
452+
return fmt.Errorf("failed to match any PREFIX pattern in file %s", indexHtml)
453+
}
454+
455+
// Write the updated content back to file
456+
err = os.WriteFile(indexHtml, []byte(updatedContent), 0644)
457+
if err != nil {
458+
return fmt.Errorf("error writing file: %w", err)
459+
}
460+
461+
return nil
462+
463+
}
464+
465+
return nil
466+
}

version.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package main
22

33
// VERSION
4-
var VERSION_APPLICATION = "1.5.4"
4+
var VERSION_APPLICATION = "1.5.5"
55

66
// NAME
77
var NAME_APPLICATION = "homer-app"

0 commit comments

Comments
 (0)