From a82b6812e3a0c69f79e2d9a98d19f3d9868dd1d8 Mon Sep 17 00:00:00 2001 From: Diana Date: Sat, 28 Sep 2024 17:40:42 -0500 Subject: [PATCH 01/40] get body request, validator fix --- context.go | 30 ++++++++++++++++++++++++++++++ validator.go | 12 ++++-------- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/context.go b/context.go index 30c750b..3d21cbc 100644 --- a/context.go +++ b/context.go @@ -68,6 +68,36 @@ func (c *Context) RequestParamExists(key string) bool { return c.Request.httpRequest.Form.Has(key) } +func (c *Context) GetRequesForm() interface{} { + return c.Request.httpRequest.Form +} + +func (c *Context) GetRequesBodyMap() map[string]interface{} { + var dat map[string]any + body := c.Request.httpRequest.Body + if body != nil { + if content, err := io.ReadAll(body); err == nil { + json.Unmarshal(content, &dat) + } + } + return dat +} + +// get json body and bind to dest interface +func (c *Context) GetRequesBodyStruct(dest interface{}) error { + body := c.Request.httpRequest.Body + if body != nil { + value := reflect.ValueOf(dest) + if value.Kind() != reflect.Ptr { + fmt.Println("dest is not a pointer") + return errors.New("dest is not a pointer") + } + err := json.NewDecoder(body).Decode(dest) + return err + } + return nil +} + func (c *Context) GetHeader(key string) string { return c.Request.httpRequest.Header.Get(key) } diff --git a/validator.go b/validator.go index 7d8eac8..ba4d8a2 100644 --- a/validator.go +++ b/validator.go @@ -33,18 +33,14 @@ func (v *Validator) Validate(data map[string]interface{}, rules map[string]inter vr = validationResult{} vr.hasFailed = false res := map[string]string{} - for key, val := range data { - _, ok := rules[key] - if !ok { - continue - } - rls, err := parseRules(rules[key]) + for rule_key, rule_val := range rules { + rls, err := parseRules(rule_val) if err != nil { panic(err.Error()) } - err = validation.Validate(val, rls...) + err = validation.Validate(data[rule_key], rls...) if err != nil { - res[key] = fmt.Sprintf("%v: %v", key, err.Error()) + res[rule_key] = fmt.Sprintf("%v: %v", rule_key, err.Error()) } } -- 2.39.5 From 2bffdcdcf7e40eb432cf26c0451ea18b2292561b Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Mon, 30 Sep 2024 09:12:38 -0500 Subject: [PATCH 02/40] start cookie session --- context.go | 9 ++ cookies.go | 238 ++++++++++++++++++++++++++++++++++ core.go | 8 +- template/components/head.html | 10 +- template/components/page.html | 17 +++ 5 files changed, 275 insertions(+), 7 deletions(-) create mode 100644 cookies.go create mode 100644 template/components/page.html diff --git a/context.go b/context.go index 30c750b..cc622be 100644 --- a/context.go +++ b/context.go @@ -72,6 +72,15 @@ func (c *Context) GetHeader(key string) string { return c.Request.httpRequest.Header.Get(key) } +func (c *Context) GetCookie() (UserCookie, error) { + + user, err := GetCookie(c.Request.httpRequest) + if err != nil { + return user, err + } + return user, nil +} + func (c *Context) GetUploadedFile(name string) *UploadedFileInfo { file, fileHeader, err := c.Request.httpRequest.FormFile(name) if err != nil { diff --git a/cookies.go b/cookies.go new file mode 100644 index 0000000..87503e7 --- /dev/null +++ b/cookies.go @@ -0,0 +1,238 @@ +// Copyright (c) 2024 Zeni Kim +// Use of this source code is governed by MIT-style +// license that can be found in the LICENSE file. + +package core + +import ( + "crypto/aes" + "crypto/cipher" + + "bytes" + "crypto/rand" + "encoding/base64" + "encoding/gob" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "strings" +) + +var ( + ErrValueTooLong = errors.New("cookie value too long") + ErrInvalidValue = errors.New("invalid cookie value") +) + +// Declare the User type. +type UserCookie struct { + Email string + Token string +} + +var secretcookie []byte + +func GetCookie(r *http.Request) (UserCookie, error) { + + var err error + // Create a new instance of a User type. + var user UserCookie + + secretcookie, err = hex.DecodeString("13d6b4dff8f84a10851021ec8608f814570d562c92fe6b5ec4c9f595bcb3234b") + if err != nil { + return user, err + } + + gobEncodedValue, err := CookieReadEncrypted(r, "goffee", secretcookie) + if err != nil { + return user, err + } + + // Create an strings.Reader containing the gob-encoded value. + reader := strings.NewReader(gobEncodedValue) + + // Decode it into the User type. Notice that we need to pass a *pointer* to + // the Decode() target here? + if err := gob.NewDecoder(reader).Decode(&user); err != nil { + return user, err + } + + return user, nil + +} + +func SetCookie(w http.ResponseWriter, email string, token string) error { + // Initialize a User struct containing the data that we want to store in the + // cookie. + var err error + + secretcookie, err = hex.DecodeString("13d6b4dff8f84a10851021ec8608f814570d562c92fe6b5ec4c9f595bcb3234b") + if err != nil { + return err + } + + user := UserCookie{Email: email, Token: token} + + // Initialize a buffer to hold the gob-encoded data. + var buf bytes.Buffer + + // Gob-encode the user data, storing the encoded output in the buffer. + err = gob.NewEncoder(&buf).Encode(&user) + if err != nil { + return err + } + + // Call buf.String() to get the gob-encoded value as a string and set it as + // the cookie value. + cookie := http.Cookie{ + Name: "goffee", + Value: buf.String(), + Path: "/", + MaxAge: 3600, + HttpOnly: true, + Secure: true, + SameSite: http.SameSiteLaxMode, + } + + // Write an encrypted cookie containing the gob-encoded data as normal. + err = CookieWriteEncrypted(w, cookie, secretcookie) + if err != nil { + return err + } + + fmt.Printf("Cookie set %v\n", email) + + return nil +} + +func CookieWrite(w http.ResponseWriter, cookie http.Cookie) error { + // Encode the cookie value using base64. + cookie.Value = base64.URLEncoding.EncodeToString([]byte(cookie.Value)) + + // Check the total length of the cookie contents. Return the ErrValueTooLong + // error if it's more than 4096 bytes. + if len(cookie.String()) > 4096 { + return ErrValueTooLong + } + + // Write the cookie as normal. + http.SetCookie(w, &cookie) + + return nil +} + +func CookieRead(r *http.Request, name string) (string, error) { + // Read the cookie as normal. + cookie, err := r.Cookie(name) + if err != nil { + return "", err + } + + // Decode the base64-encoded cookie value. If the cookie didn't contain a + // valid base64-encoded value, this operation will fail and we return an + // ErrInvalidValue error. + value, err := base64.URLEncoding.DecodeString(cookie.Value) + if err != nil { + return "", ErrInvalidValue + } + + // Return the decoded cookie value. + return string(value), nil +} + +func CookieWriteEncrypted(w http.ResponseWriter, cookie http.Cookie, secretKey []byte) error { + // Create a new AES cipher block from the secret key. + block, err := aes.NewCipher(secretKey) + if err != nil { + return err + } + + // Wrap the cipher block in Galois Counter Mode. + aesGCM, err := cipher.NewGCM(block) + if err != nil { + return err + } + + // Create a unique nonce containing 12 random bytes. + nonce := make([]byte, aesGCM.NonceSize()) + _, err = io.ReadFull(rand.Reader, nonce) + if err != nil { + return err + } + + // Prepare the plaintext input for encryption. Because we want to + // authenticate the cookie name as well as the value, we make this plaintext + // in the format "{cookie name}:{cookie value}". We use the : character as a + // separator because it is an invalid character for cookie names and + // therefore shouldn't appear in them. + plaintext := fmt.Sprintf("%s:%s", cookie.Name, cookie.Value) + + // Encrypt the data using aesGCM.Seal(). By passing the nonce as the first + // parameter, the encrypted data will be appended to the nonce — meaning + // that the returned encryptedValue variable will be in the format + // "{nonce}{encrypted plaintext data}". + encryptedValue := aesGCM.Seal(nonce, nonce, []byte(plaintext), nil) + + // Set the cookie value to the encryptedValue. + cookie.Value = string(encryptedValue) + + // Write the cookie as normal. + return CookieWrite(w, cookie) +} + +func CookieReadEncrypted(r *http.Request, name string, secretKey []byte) (string, error) { + // Read the encrypted value from the cookie as normal. + encryptedValue, err := CookieRead(r, name) + if err != nil { + return "", err + } + + // Create a new AES cipher block from the secret key. + block, err := aes.NewCipher(secretKey) + if err != nil { + return "", err + } + + // Wrap the cipher block in Galois Counter Mode. + aesGCM, err := cipher.NewGCM(block) + if err != nil { + return "", err + } + + // Get the nonce size. + nonceSize := aesGCM.NonceSize() + + // To avoid a potential 'index out of range' panic in the next step, we + // check that the length of the encrypted value is at least the nonce + // size. + if len(encryptedValue) < nonceSize { + return "", ErrInvalidValue + } + + // Split apart the nonce from the actual encrypted data. + nonce := encryptedValue[:nonceSize] + ciphertext := encryptedValue[nonceSize:] + + // Use aesGCM.Open() to decrypt and authenticate the data. If this fails, + // return a ErrInvalidValue error. + plaintext, err := aesGCM.Open(nil, []byte(nonce), []byte(ciphertext), nil) + if err != nil { + return "", ErrInvalidValue + } + + // The plaintext value is in the format "{cookie name}:{cookie value}". We + // use strings.Cut() to split it on the first ":" character. + expectedName, value, ok := strings.Cut(string(plaintext), ":") + if !ok { + return "", ErrInvalidValue + } + + // Check that the cookie name is the expected one and hasn't been changed. + if expectedName != name { + return "", ErrInvalidValue + } + + // Return the plaintext cookie value. + return value, nil +} diff --git a/core.go b/core.go index ba208d3..59691c6 100644 --- a/core.go +++ b/core.go @@ -98,9 +98,7 @@ func (app *App) Run(router *httprouter.Router) { TemplateEnable, _ := strconv.ParseBool(TemplateEnableStr) // if enabled, if TemplateEnable { - // add public path - publicPath := os.Getenv("TEMPLATE_PUBLIC") - router.ServeFiles("/public/*filepath", http.Dir(publicPath)) + router.ServeFiles("/public/*filepath", http.Dir("storage/public")) } useHttpsStr := os.Getenv("App_USE_HTTPS") @@ -183,6 +181,7 @@ func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httpr func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + ctx := &Context{ Request: &Request{ httpRequest: r, @@ -206,11 +205,13 @@ func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Ha GetEventsManager: resolveEventsManager(), GetLogger: resolveLogger(), } + ctx.prepare(ctx) rhs := app.combHandlers(h, ms) app.prepareChain(rhs) app.t = 0 app.chain.execute(ctx) + for _, header := range ctx.Response.headers { w.Header().Add(header.key, header.val) } @@ -223,6 +224,7 @@ func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Ha } else { ct = CONTENT_TYPE_HTML } + w.Header().Add(CONTENT_TYPE, ct) if ctx.Response.statusCode != 0 { w.WriteHeader(ctx.Response.statusCode) diff --git a/template/components/head.html b/template/components/head.html index cecc5ed..68aaca8 100644 --- a/template/components/head.html +++ b/template/components/head.html @@ -1,8 +1,10 @@ {{define "head"}} - - - {{.}} | Goffee - + + + + {{.}} | Goffee + + {{end}} \ No newline at end of file diff --git a/template/components/page.html b/template/components/page.html new file mode 100644 index 0000000..636487b --- /dev/null +++ b/template/components/page.html @@ -0,0 +1,17 @@ + + + + + + + My Website + + + + +
+

Welcome to My Website

+
+ + + \ No newline at end of file -- 2.39.5 From 015e85bf7b20a56381449cbf1ba1b580d3d1d360 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Mon, 7 Oct 2024 18:10:04 -0500 Subject: [PATCH 03/40] start theme core templates --- .../components/{button.go => form_button.go} | 2 +- .../{button.html => form_button.html} | 9 +++------ template/components/form_input.go | 12 ++++++++++++ template/components/form_input.html | 15 +++++++++++++++ template/components/page.html | 17 ----------------- template/components/page_card.go | 8 ++++++++ template/components/page_card.html | 11 +++++++++++ template/components/page_footer.html | 6 ++++++ .../components/{head.html => page_head.html} | 3 ++- template/components/page_page.html | 14 ++++++++++++++ template/components/title.go | 5 ----- template/components/title.html | 5 ----- 12 files changed, 72 insertions(+), 35 deletions(-) rename template/components/{button.go => form_button.go} (83%) rename template/components/{button.html => form_button.html} (89%) create mode 100644 template/components/form_input.go create mode 100644 template/components/form_input.html delete mode 100644 template/components/page.html create mode 100644 template/components/page_card.go create mode 100644 template/components/page_card.html create mode 100644 template/components/page_footer.html rename template/components/{head.html => page_head.html} (75%) create mode 100644 template/components/page_page.html delete mode 100644 template/components/title.go delete mode 100644 template/components/title.html diff --git a/template/components/button.go b/template/components/form_button.go similarity index 83% rename from template/components/button.go rename to template/components/form_button.go index 0c52a38..2cfee00 100644 --- a/template/components/button.go +++ b/template/components/form_button.go @@ -1,6 +1,6 @@ package components -type Button struct { +type FormButton struct { Text string Link string Icon string diff --git a/template/components/button.html b/template/components/form_button.html similarity index 89% rename from template/components/button.html rename to template/components/form_button.html index 6590905..5e1d68c 100644 --- a/template/components/button.html +++ b/template/components/form_button.html @@ -1,7 +1,6 @@ -{{define "button"}} - {{if eq .Icon "gear"}} @@ -17,6 +16,4 @@ {{end}} - - {{end}} \ No newline at end of file diff --git a/template/components/form_input.go b/template/components/form_input.go new file mode 100644 index 0000000..0ce7ce4 --- /dev/null +++ b/template/components/form_input.go @@ -0,0 +1,12 @@ +package components + +type FormInput struct { + ID string + Label string + Type string + Placeholder string + Value string + Hint string + Error string + IsDisabled bool +} diff --git a/template/components/form_input.html b/template/components/form_input.html new file mode 100644 index 0000000..b79ae87 --- /dev/null +++ b/template/components/form_input.html @@ -0,0 +1,15 @@ +{{define "form_input"}} +
+ + + {{if ne .Hint ""}}{{.Hint}}{{end}} + {{if ne .Error ""}}
{{.Error}}
{{end}} +
+{{end}} \ No newline at end of file diff --git a/template/components/page.html b/template/components/page.html deleted file mode 100644 index 636487b..0000000 --- a/template/components/page.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - My Website - - - - -
-

Welcome to My Website

-
- - - \ No newline at end of file diff --git a/template/components/page_card.go b/template/components/page_card.go new file mode 100644 index 0000000..7f9b504 --- /dev/null +++ b/template/components/page_card.go @@ -0,0 +1,8 @@ +package components + +type PageCard struct { + CardTitle string + CardSubTitle string + CardBody string + CardLink string +} diff --git a/template/components/page_card.html b/template/components/page_card.html new file mode 100644 index 0000000..9ef8821 --- /dev/null +++ b/template/components/page_card.html @@ -0,0 +1,11 @@ +{{define "page_card"}} +
+
+ {{if .CardTitle}}
{{.CardTitle}}
{{end}} + {{if .CardSubTitle}}
{{.CardSubTitle}}
{{end}} + {{if .CardBody}}

{{.CardBody}}

{{end}} + {{block "page_card_content" .}}{{end}} + {{if .CardLink}}Card link{{end}} +
+
+{{end}} \ No newline at end of file diff --git a/template/components/page_footer.html b/template/components/page_footer.html new file mode 100644 index 0000000..20b7f38 --- /dev/null +++ b/template/components/page_footer.html @@ -0,0 +1,6 @@ +{{define "page_footer"}} +
+ +
+ +{{end}} \ No newline at end of file diff --git a/template/components/head.html b/template/components/page_head.html similarity index 75% rename from template/components/head.html rename to template/components/page_head.html index 68aaca8..e589e84 100644 --- a/template/components/head.html +++ b/template/components/page_head.html @@ -1,4 +1,4 @@ -{{define "head"}} +{{define "page_head"}} @@ -6,5 +6,6 @@ {{.}} | Goffee + {{end}} \ No newline at end of file diff --git a/template/components/page_page.html b/template/components/page_page.html new file mode 100644 index 0000000..2c83582 --- /dev/null +++ b/template/components/page_page.html @@ -0,0 +1,14 @@ + + + {{template "page_head" "Goffee"}} + +
+ {{block "page_content" .}} +
+

Use this file as base inside cup application

+
+ {{end}} + {{template "page_footer"}} +
+ + \ No newline at end of file diff --git a/template/components/title.go b/template/components/title.go deleted file mode 100644 index 0e68b6a..0000000 --- a/template/components/title.go +++ /dev/null @@ -1,5 +0,0 @@ -package components - -type Title struct { - Label string -} diff --git a/template/components/title.html b/template/components/title.html deleted file mode 100644 index eef5bf3..0000000 --- a/template/components/title.html +++ /dev/null @@ -1,5 +0,0 @@ -{{define "title"}} -
-

{{.Label}}

-
-{{end}} \ No newline at end of file -- 2.39.5 From 8f17bf6a8c879a514a2029c4c8c65fce141f6aac Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Tue, 8 Oct 2024 07:58:42 -0500 Subject: [PATCH 04/40] add form components --- template/components/form_checkbox.go | 14 ++++++++++++++ template/components/form_checkbox.html | 11 +++++++++++ template/components/form_radio.go | 15 +++++++++++++++ template/components/form_radio.html | 11 +++++++++++ template/components/form_select.go | 13 +++++++++++++ template/components/form_select.html | 10 ++++++++++ template/components/form_textarea.go | 7 +++++++ template/components/form_textarea.html | 6 ++++++ 8 files changed, 87 insertions(+) create mode 100644 template/components/form_checkbox.go create mode 100644 template/components/form_checkbox.html create mode 100644 template/components/form_radio.go create mode 100644 template/components/form_radio.html create mode 100644 template/components/form_select.go create mode 100644 template/components/form_select.html create mode 100644 template/components/form_textarea.go create mode 100644 template/components/form_textarea.html diff --git a/template/components/form_checkbox.go b/template/components/form_checkbox.go new file mode 100644 index 0000000..819da82 --- /dev/null +++ b/template/components/form_checkbox.go @@ -0,0 +1,14 @@ +package components + +type FormCheckbox struct { + Label string + AllCheckbox []FormCheckboxItem +} + +type FormCheckboxItem struct { + ID string + Name string + Value string + Label string + IsChecked bool +} diff --git a/template/components/form_checkbox.html b/template/components/form_checkbox.html new file mode 100644 index 0000000..9a8d845 --- /dev/null +++ b/template/components/form_checkbox.html @@ -0,0 +1,11 @@ +{{define "form_checkbox"}} +
+ + {{range $options := .AllCheckbox}} +
+ + +
+ {{end}} +
+{{end}} \ No newline at end of file diff --git a/template/components/form_radio.go b/template/components/form_radio.go new file mode 100644 index 0000000..e8e923c --- /dev/null +++ b/template/components/form_radio.go @@ -0,0 +1,15 @@ +package components + +type FormRadio struct { + Label string + AllRadios []FormRadioItem +} + +type FormRadioItem struct { + ID string + Name string + Value string + Label string + IsDisabled bool + IsChecked bool +} diff --git a/template/components/form_radio.html b/template/components/form_radio.html new file mode 100644 index 0000000..a0c26cd --- /dev/null +++ b/template/components/form_radio.html @@ -0,0 +1,11 @@ +{{define "form_radio"}} +
+ + {{range $options := .AllRadios}} +
+ + +
+ {{end}} +
+{{end}} \ No newline at end of file diff --git a/template/components/form_select.go b/template/components/form_select.go new file mode 100644 index 0000000..db94fe3 --- /dev/null +++ b/template/components/form_select.go @@ -0,0 +1,13 @@ +package components + +type FormSelect struct { + ID string + SelectedOption FormSelectOption + Label string + AllOptions []FormSelectOption +} + +type FormSelectOption struct { + Value string + Caption string +} diff --git a/template/components/form_select.html b/template/components/form_select.html new file mode 100644 index 0000000..6317e6b --- /dev/null +++ b/template/components/form_select.html @@ -0,0 +1,10 @@ +{{define "form_select"}} +
+ + +
+{{end}} \ No newline at end of file diff --git a/template/components/form_textarea.go b/template/components/form_textarea.go new file mode 100644 index 0000000..8fbaf51 --- /dev/null +++ b/template/components/form_textarea.go @@ -0,0 +1,7 @@ +package components + +type FormTextarea struct { + ID string + Label string + AllOptions []FormSelectOption +} diff --git a/template/components/form_textarea.html b/template/components/form_textarea.html new file mode 100644 index 0000000..5372a42 --- /dev/null +++ b/template/components/form_textarea.html @@ -0,0 +1,6 @@ +{{define "form_textarea"}} +
+ + +
+{{end}} \ No newline at end of file -- 2.39.5 From 7073cd1c21913816445c2fc9a6e0294a5429122c Mon Sep 17 00:00:00 2001 From: Diana Date: Sat, 12 Oct 2024 13:01:52 -0500 Subject: [PATCH 05/40] components: buttons, dropdown, href, nav --- template/components/form_button.go | 3 +-- template/components/form_button.html | 35 +++++++++++++------------- template/components/form_dropdown.go | 15 +++++++++++ template/components/form_dropdown.html | 16 ++++++++++++ template/components/form_href.go | 10 ++++++++ template/components/form_href.html | 6 +++++ template/components/page_footer.html | 1 + template/components/page_nav.go | 16 ++++++++++++ template/components/page_nav.html | 23 +++++++++++++++++ 9 files changed, 106 insertions(+), 19 deletions(-) create mode 100644 template/components/form_dropdown.go create mode 100644 template/components/form_dropdown.html create mode 100644 template/components/form_href.go create mode 100644 template/components/form_href.html create mode 100644 template/components/page_nav.go create mode 100644 template/components/page_nav.html diff --git a/template/components/form_button.go b/template/components/form_button.go index 2cfee00..658306e 100644 --- a/template/components/form_button.go +++ b/template/components/form_button.go @@ -2,9 +2,8 @@ package components type FormButton struct { Text string - Link string Icon string IsSubmit bool - IsPrimary bool + TypeClass string // type primary, secondary, success, danger, warning, info, light, dark, link, outline-primary IsDisabled bool } diff --git a/template/components/form_button.html b/template/components/form_button.html index 5e1d68c..7594613 100644 --- a/template/components/form_button.html +++ b/template/components/form_button.html @@ -1,19 +1,20 @@ {{define "form_button"}} - - - {{if eq .Icon "gear"}} - - - - - {{else if eq .Icon "arrow-right"}} - - - - {{else if eq .Icon "plus"}} - - - - {{end}} + + + {{if eq .Icon "gear"}} + + + + + {{else if eq .Icon "arrow-right"}} + + + + {{else if eq .Icon "plus"}} + + + + {{end}} {{end}} \ No newline at end of file diff --git a/template/components/form_dropdown.go b/template/components/form_dropdown.go new file mode 100644 index 0000000..b80d8f1 --- /dev/null +++ b/template/components/form_dropdown.go @@ -0,0 +1,15 @@ +package components + +type FormDropdown struct { + Label string + TypeClass string + IsDisabled bool + Items []FormDropdownItem +} + +type FormDropdownItem struct { + Text string + Link string + IsDisabled bool + IsActive bool +} diff --git a/template/components/form_dropdown.html b/template/components/form_dropdown.html new file mode 100644 index 0000000..2c6827b --- /dev/null +++ b/template/components/form_dropdown.html @@ -0,0 +1,16 @@ +{{define "form_dropdown_item"}} +
  • {{.Text}}
  • +{{end}} + +{{define "form_dropdown"}} + +{{end}} \ No newline at end of file diff --git a/template/components/form_href.go b/template/components/form_href.go new file mode 100644 index 0000000..25dbee3 --- /dev/null +++ b/template/components/form_href.go @@ -0,0 +1,10 @@ +package components + +type FormHref struct { + Text string + Link string + Icon string + IsButton bool + TypeClass string // type primary, secondary, success, danger, warning, info, light, dark, link + IsDisabled bool +} diff --git a/template/components/form_href.html b/template/components/form_href.html new file mode 100644 index 0000000..dc9adb3 --- /dev/null +++ b/template/components/form_href.html @@ -0,0 +1,6 @@ +{{define "form_href"}} + + {{.Text}} + +{{end}} \ No newline at end of file diff --git a/template/components/page_footer.html b/template/components/page_footer.html index 20b7f38..6421f3e 100644 --- a/template/components/page_footer.html +++ b/template/components/page_footer.html @@ -2,5 +2,6 @@
    + {{end}} \ No newline at end of file diff --git a/template/components/page_nav.go b/template/components/page_nav.go new file mode 100644 index 0000000..2ed9319 --- /dev/null +++ b/template/components/page_nav.go @@ -0,0 +1,16 @@ +package components + +type PageNav struct { + NavClass string // nav-pills + NavItems []PageNavItem + IsVertical bool + IsTab bool +} + +type PageNavItem struct { + Text string + Link string + IsDisabled bool + IsActive bool + ChildItems []PageNavItem +} diff --git a/template/components/page_nav.html b/template/components/page_nav.html new file mode 100644 index 0000000..5bb0b83 --- /dev/null +++ b/template/components/page_nav.html @@ -0,0 +1,23 @@ +{{define "page_nav"}} + +{{end}} -- 2.39.5 From 1c1740d97b4ce8540434f84f30474c4fc3f98cbe Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Mon, 14 Oct 2024 12:13:51 -0500 Subject: [PATCH 06/40] base table --- template/components/content_table.go | 17 +++++++++++++++++ template/components/content_table.html | 12 ++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 template/components/content_table.go create mode 100644 template/components/content_table.html diff --git a/template/components/content_table.go b/template/components/content_table.go new file mode 100644 index 0000000..66c7e1f --- /dev/null +++ b/template/components/content_table.go @@ -0,0 +1,17 @@ +package components + +type ContentTable struct { + ID string + AllTH []ContentTableTH + AllTD [][]ContentTableTD +} + +type ContentTableTH struct { + ID string + Value string +} + +type ContentTableTD struct { + ID string + Value string +} diff --git a/template/components/content_table.html b/template/components/content_table.html new file mode 100644 index 0000000..68e34f6 --- /dev/null +++ b/template/components/content_table.html @@ -0,0 +1,12 @@ +{{define "content_table"}} + + + + {{range $index, $col := .AllTH}}{{end}} + + + +{{range .AllTD}}{{range .}}{{end}}{{end}} + +
    {{ $col.Value }}
    {{ .Value }}
    +{{end}} \ No newline at end of file -- 2.39.5 From a904773babab29b9e24d40cf183b8a7a1ee92f0e Mon Sep 17 00:00:00 2001 From: Diana Date: Tue, 15 Oct 2024 16:06:49 -0500 Subject: [PATCH 07/40] Badge --- template/components/content_badge.go | 7 +++++++ template/components/content_badge.html | 7 +++++++ 2 files changed, 14 insertions(+) create mode 100644 template/components/content_badge.go create mode 100644 template/components/content_badge.html diff --git a/template/components/content_badge.go b/template/components/content_badge.go new file mode 100644 index 0000000..7da7147 --- /dev/null +++ b/template/components/content_badge.go @@ -0,0 +1,7 @@ +package components + +type ContentBadge struct { + Text string + TypeClass string // type primary, secondary, success, danger, warning, info, light, dark, (default secondary) + IsOutline bool +} diff --git a/template/components/content_badge.html b/template/components/content_badge.html new file mode 100644 index 0000000..6f72cf7 --- /dev/null +++ b/template/components/content_badge.html @@ -0,0 +1,7 @@ +{{define "content_badge"}} + {{.Text}} +{{end}} \ No newline at end of file -- 2.39.5 From f398ebb02dbc0d9510dab1f2588ffd0b5f6c1405 Mon Sep 17 00:00:00 2001 From: Diana Date: Tue, 15 Oct 2024 16:07:18 -0500 Subject: [PATCH 08/40] dropdown, href is content --- template/components/content_dropdown.go | 15 +++++++++++++++ .../{form_dropdown.html => content_dropdown.html} | 6 +++--- .../components/{form_href.go => content_href.go} | 2 +- .../{form_href.html => content_href.html} | 2 +- template/components/form_dropdown.go | 15 --------------- 5 files changed, 20 insertions(+), 20 deletions(-) create mode 100644 template/components/content_dropdown.go rename template/components/{form_dropdown.html => content_dropdown.html} (79%) rename template/components/{form_href.go => content_href.go} (88%) rename template/components/{form_href.html => content_href.html} (88%) delete mode 100644 template/components/form_dropdown.go diff --git a/template/components/content_dropdown.go b/template/components/content_dropdown.go new file mode 100644 index 0000000..1040060 --- /dev/null +++ b/template/components/content_dropdown.go @@ -0,0 +1,15 @@ +package components + +type ContentDropdown struct { + Label string + TypeClass string // type primary, secondary, success, danger, warning, info, light, dark, link, outline-primary + IsDisabled bool + Items []ContentDropdownItem +} + +type ContentDropdownItem struct { + Text string + Link string + IsDisabled bool + IsActive bool +} diff --git a/template/components/form_dropdown.html b/template/components/content_dropdown.html similarity index 79% rename from template/components/form_dropdown.html rename to template/components/content_dropdown.html index 2c6827b..ce83a26 100644 --- a/template/components/form_dropdown.html +++ b/template/components/content_dropdown.html @@ -1,15 +1,15 @@ -{{define "form_dropdown_item"}} +{{define "content_dropdown_item"}}
  • {{.Text}}
  • {{end}} -{{define "form_dropdown"}} +{{define "content_dropdown"}} diff --git a/template/components/form_href.go b/template/components/content_href.go similarity index 88% rename from template/components/form_href.go rename to template/components/content_href.go index 25dbee3..143ca80 100644 --- a/template/components/form_href.go +++ b/template/components/content_href.go @@ -1,6 +1,6 @@ package components -type FormHref struct { +type ContentHref struct { Text string Link string Icon string diff --git a/template/components/form_href.html b/template/components/content_href.html similarity index 88% rename from template/components/form_href.html rename to template/components/content_href.html index dc9adb3..f4980ac 100644 --- a/template/components/form_href.html +++ b/template/components/content_href.html @@ -1,4 +1,4 @@ -{{define "form_href"}} +{{define "content_href"}} {{.Text}} diff --git a/template/components/form_dropdown.go b/template/components/form_dropdown.go deleted file mode 100644 index b80d8f1..0000000 --- a/template/components/form_dropdown.go +++ /dev/null @@ -1,15 +0,0 @@ -package components - -type FormDropdown struct { - Label string - TypeClass string - IsDisabled bool - Items []FormDropdownItem -} - -type FormDropdownItem struct { - Text string - Link string - IsDisabled bool - IsActive bool -} -- 2.39.5 From 458ad520ca19f7301741fcc02b9c6a6306157837 Mon Sep 17 00:00:00 2001 From: Diana Date: Tue, 15 Oct 2024 16:09:17 -0500 Subject: [PATCH 09/40] Input required, table (class, href, badge) --- template/components/content_table.go | 15 +++++++++------ template/components/content_table.html | 19 ++++++++++++++++--- template/components/form_input.go | 1 + template/components/form_input.html | 3 +++ template/components/page_nav.go | 2 +- template/components/page_nav.html | 2 +- 6 files changed, 31 insertions(+), 11 deletions(-) diff --git a/template/components/content_table.go b/template/components/content_table.go index 66c7e1f..1cb7024 100644 --- a/template/components/content_table.go +++ b/template/components/content_table.go @@ -1,17 +1,20 @@ package components type ContentTable struct { - ID string - AllTH []ContentTableTH - AllTD [][]ContentTableTD + ID string + TableClass string // table-primary, table-secondary,.. table-striped table-bordered + HeadClass string // table-dark table-light + AllTH []ContentTableTH + AllTD [][]ContentTableTD } type ContentTableTH struct { - ID string - Value string + ID string + ValueType string // -> default string, href, badge + Value string } type ContentTableTD struct { ID string - Value string + Value interface{} // string or component struct according ValueType } diff --git a/template/components/content_table.html b/template/components/content_table.html index 68e34f6..ce19344 100644 --- a/template/components/content_table.html +++ b/template/components/content_table.html @@ -1,12 +1,25 @@ {{define "content_table"}} - - +
    + {{range $index, $col := .AllTH}}{{end}} -{{range .AllTD}}{{range .}}{{end}}{{end}} + {{range .AllTD}} + {{range $index, $item := .}} + {{end}} + {{end}}
    {{ $col.Value }}
    {{ .Value }}
    + {{ with $x := index $.AllTH $index }} + {{ if eq $x.ValueType "href"}} + {{template "content_href" $item.Value}} + {{ else if eq $x.ValueType "badge"}} + {{template "content_badge" $item.Value}} + {{ else }} + {{ $item.Value }} + {{end}} + {{end}} +
    {{end}} \ No newline at end of file diff --git a/template/components/form_input.go b/template/components/form_input.go index 0ce7ce4..e27910f 100644 --- a/template/components/form_input.go +++ b/template/components/form_input.go @@ -9,4 +9,5 @@ type FormInput struct { Hint string Error string IsDisabled bool + IsRequired bool } diff --git a/template/components/form_input.html b/template/components/form_input.html index b79ae87..8159896 100644 --- a/template/components/form_input.html +++ b/template/components/form_input.html @@ -5,6 +5,9 @@ {{if eq .IsDisabled true}} disabled {{end}} + {{if eq .IsRequired true}} + required + {{end}} {{if ne .Value ""}} value="{{.Value}}" {{end}} diff --git a/template/components/page_nav.go b/template/components/page_nav.go index 2ed9319..862d1c8 100644 --- a/template/components/page_nav.go +++ b/template/components/page_nav.go @@ -1,7 +1,7 @@ package components type PageNav struct { - NavClass string // nav-pills + NavClass string // nav-pills, nav-underline NavItems []PageNavItem IsVertical bool IsTab bool diff --git a/template/components/page_nav.html b/template/components/page_nav.html index 5bb0b83..08faaf4 100644 --- a/template/components/page_nav.html +++ b/template/components/page_nav.html @@ -8,7 +8,7 @@ class="nav-link dropdown-toggle {{if eq .IsActive true}}active{{end}} {{if eq .IsDisabled true}}disabled{{end}}">{{$item.Text}}
    -- 2.39.5 From bf84e14bb12060a12d9e6581a39b26547823a92c Mon Sep 17 00:00:00 2001 From: Diana Date: Tue, 15 Oct 2024 16:09:31 -0500 Subject: [PATCH 10/40] component list --- template/components/content_list.go | 19 +++++++++++++++++++ template/components/content_list.html | 14 ++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 template/components/content_list.go create mode 100644 template/components/content_list.html diff --git a/template/components/content_list.go b/template/components/content_list.go new file mode 100644 index 0000000..34bfb49 --- /dev/null +++ b/template/components/content_list.go @@ -0,0 +1,19 @@ +package components + +type ContentList struct { + Items []ContentListItem +} + +type ContentListItem struct { + Text string + Description string + EndElement string + //Link string + TypeClass string // primary, secondary, success, danger, warning, info, light, dark + IsDisabled bool + //IsActive bool +} + +//link +//border +// badge diff --git a/template/components/content_list.html b/template/components/content_list.html new file mode 100644 index 0000000..31af60b --- /dev/null +++ b/template/components/content_list.html @@ -0,0 +1,14 @@ +{{define "content_list"}} +
      + {{ range .Items}} +
    • {{.Text}}

      {{.EndElement}}
      + {{.Description}} +
    • + {{end}} +
    + + + +{{end}} \ No newline at end of file -- 2.39.5 From cc74165659377ebef96443030f33fbeafb9774ff Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Tue, 15 Oct 2024 22:00:46 -0500 Subject: [PATCH 11/40] add cookie secret as env, fix components --- cookies.go | 49 +++++++++++++++++++++----- template/components/content_table.html | 2 +- template/components/form_textarea.go | 6 ++-- template/components/form_textarea.html | 2 +- 4 files changed, 46 insertions(+), 13 deletions(-) diff --git a/cookies.go b/cookies.go index 87503e7..8c03c10 100644 --- a/cookies.go +++ b/cookies.go @@ -5,10 +5,9 @@ package core import ( + "bytes" "crypto/aes" "crypto/cipher" - - "bytes" "crypto/rand" "encoding/base64" "encoding/gob" @@ -17,6 +16,8 @@ import ( "fmt" "io" "net/http" + "os" + "strconv" "strings" ) @@ -39,9 +40,24 @@ func GetCookie(r *http.Request) (UserCookie, error) { // Create a new instance of a User type. var user UserCookie - secretcookie, err = hex.DecodeString("13d6b4dff8f84a10851021ec8608f814570d562c92fe6b5ec4c9f595bcb3234b") - if err != nil { - return user, err + // check if template engine is enable + TemplateEnableStr := os.Getenv("TEMPLATE_ENABLE") + if TemplateEnableStr == "" { + TemplateEnableStr = "false" + } + TemplateEnable, _ := strconv.ParseBool(TemplateEnableStr) + // if enabled, + if TemplateEnable { + cookie_secret := os.Getenv("COOKIE_SECRET") + if cookie_secret == "" { + panic("cookie secret key is not set") + } + secretcookie, err = hex.DecodeString(cookie_secret) + if err != nil { + return user, err + } + } else { + panic("Templates are disabled") } gobEncodedValue, err := CookieReadEncrypted(r, "goffee", secretcookie) @@ -67,7 +83,26 @@ func SetCookie(w http.ResponseWriter, email string, token string) error { // cookie. var err error - secretcookie, err = hex.DecodeString("13d6b4dff8f84a10851021ec8608f814570d562c92fe6b5ec4c9f595bcb3234b") + // check if template engine is enable + TemplateEnableStr := os.Getenv("TEMPLATE_ENABLE") + if TemplateEnableStr == "" { + TemplateEnableStr = "false" + } + TemplateEnable, _ := strconv.ParseBool(TemplateEnableStr) + // if enabled, + if TemplateEnable { + cookie_secret := os.Getenv("COOKIE_SECRET") + if cookie_secret == "" { + panic("cookie secret key is not set") + } + secretcookie, err = hex.DecodeString(cookie_secret) + if err != nil { + return err + } + } else { + panic("Templates are disabled") + } + if err != nil { return err } @@ -101,8 +136,6 @@ func SetCookie(w http.ResponseWriter, email string, token string) error { return err } - fmt.Printf("Cookie set %v\n", email) - return nil } diff --git a/template/components/content_table.html b/template/components/content_table.html index 68e34f6..f7c2f89 100644 --- a/template/components/content_table.html +++ b/template/components/content_table.html @@ -6,7 +6,7 @@ -{{range .AllTD}}{{range .}}{{ .Value }}{{end}}{{end}} +{{- range .AllTD}}{{range .}}{{ .Value }}{{end}}{{- end}} {{end}} \ No newline at end of file diff --git a/template/components/form_textarea.go b/template/components/form_textarea.go index 8fbaf51..818ae02 100644 --- a/template/components/form_textarea.go +++ b/template/components/form_textarea.go @@ -1,7 +1,7 @@ package components type FormTextarea struct { - ID string - Label string - AllOptions []FormSelectOption + ID string + Label string + Value string } diff --git a/template/components/form_textarea.html b/template/components/form_textarea.html index 5372a42..23559ab 100644 --- a/template/components/form_textarea.html +++ b/template/components/form_textarea.html @@ -1,6 +1,6 @@ {{define "form_textarea"}}
    - +
    {{end}} \ No newline at end of file -- 2.39.5 From be138b2fb4b5e983a35129a598e3a11a8c01e337 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Tue, 15 Oct 2024 22:15:20 -0500 Subject: [PATCH 12/40] add middle line --- template/components/content_table.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/template/components/content_table.html b/template/components/content_table.html index ce19344..2bf559d 100644 --- a/template/components/content_table.html +++ b/template/components/content_table.html @@ -6,7 +6,7 @@ - {{range .AllTD}} + {{- range .AllTD}} {{range $index, $item := .}} {{ with $x := index $.AllTH $index }} {{ if eq $x.ValueType "href"}} @@ -19,7 +19,7 @@ {{end}} {{end}} - {{end}} + {{- end}} -{{end}} \ No newline at end of file +{{end}} -- 2.39.5 From 7218f26d68c6470d0a9573b6883c8b12d8229a05 Mon Sep 17 00:00:00 2001 From: Diana Date: Mon, 21 Oct 2024 17:25:50 -0500 Subject: [PATCH 13/40] component switch --- template/components/form_switch.go | 8 ++++++++ template/components/form_switch.html | 7 +++++++ 2 files changed, 15 insertions(+) create mode 100644 template/components/form_switch.go create mode 100644 template/components/form_switch.html diff --git a/template/components/form_switch.go b/template/components/form_switch.go new file mode 100644 index 0000000..9d43744 --- /dev/null +++ b/template/components/form_switch.go @@ -0,0 +1,8 @@ +package components + +type FormSwitch struct { + ID string + Label string + IsChecked bool + IsDisabled bool +} diff --git a/template/components/form_switch.html b/template/components/form_switch.html new file mode 100644 index 0000000..4841ffe --- /dev/null +++ b/template/components/form_switch.html @@ -0,0 +1,7 @@ +{{define "form_switch"}} + +
    + + +
    +{{end}} -- 2.39.5 From 59ea47dcd686809234a3e73d931a1ebc62e27f18 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Sun, 27 Oct 2024 12:54:34 -0500 Subject: [PATCH 14/40] detail table --- template/components/content_tabledetail.go | 16 +++++++++++ template/components/content_tabledetail.html | 29 ++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 template/components/content_tabledetail.go create mode 100644 template/components/content_tabledetail.html diff --git a/template/components/content_tabledetail.go b/template/components/content_tabledetail.go new file mode 100644 index 0000000..61848b8 --- /dev/null +++ b/template/components/content_tabledetail.go @@ -0,0 +1,16 @@ +package components + +type ContentTabledetail struct { + ID string + TableClass string // table-primary, table-secondary,.. table-striped table-bordered + HeadClass string // table-dark table-light + Title string + AllTD []ContentTabledetailTD +} + +type ContentTabledetailTD struct { + ID string + Caption string + ValueType string // -> default string, href, badge + Value interface{} // string or component struct according ValueType +} diff --git a/template/components/content_tabledetail.html b/template/components/content_tabledetail.html new file mode 100644 index 0000000..636191c --- /dev/null +++ b/template/components/content_tabledetail.html @@ -0,0 +1,29 @@ +{{define "content_tabledetail"}} + + {{$stylecell := "table-success"}} + {{if .HeadClass }}{{$stylecell = .HeadClass}}{{end}} + {{if .Title }} + + + + + + {{end}} + + {{range $item := .AllTD}} + + + + + {{end}} + +
    {{ .Title }}
    {{ $item.Caption }} + {{ if eq $item.ValueType "href"}} + {{template "content_href" $item.Value}} + {{ else if eq $item.ValueType "badge"}} + {{template "content_badge" $item.Value}} + {{ else }} + {{ $item.Value }} + {{end}} +
    +{{end}} -- 2.39.5 From 7c92148ae4faa1c1c123bf7131e16d65e176b018 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Mon, 28 Oct 2024 11:33:06 -0500 Subject: [PATCH 15/40] add core services, add graph service, add component graph --- consts.go | 3 + core.go | 12 +++ go.mod | 7 +- go.sum | 14 ++- graph.go | 140 +++++++++++++++++++++++++ template/components/content_graph.go | 8 ++ template/components/content_graph.html | 3 + 7 files changed, 183 insertions(+), 4 deletions(-) create mode 100644 graph.go create mode 100644 template/components/content_graph.go create mode 100644 template/components/content_graph.html diff --git a/consts.go b/consts.go index 5669217..d93318e 100644 --- a/consts.go +++ b/consts.go @@ -11,6 +11,9 @@ const CONTENT_TYPE string = "content-Type" const CONTENT_TYPE_HTML string = "text/html; charset=utf-8" const CONTENT_TYPE_JSON string = "application/json" const CONTENT_TYPE_TEXT string = "text/plain" +const CONTENT_TYPE_IMAGEPNG string = "image/png" +const CONTENT_TYPE_IMAGEJPG string = "image/jpeg" +const CONTENT_TYPE_IMAGESVGXML string = "image/svg+xml" const CONTENT_TYPE_MULTIPART_FORM_DATA string = "multipart/form-data;" const LOCALHOST string = "http://localhost" const TEST_STR string = "Testing!" diff --git a/core.go b/core.go index 59691c6..a2c8a2a 100644 --- a/core.go +++ b/core.go @@ -176,6 +176,18 @@ func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httpr router.HEAD(route.Path, app.makeHTTPRouterHandlerFunc(route.Controller, route.Hooks)) } } + + // check if use letsencrypt + UseCoreServicesStr := os.Getenv("App_USE_CORESERVICES") + if UseCoreServicesStr == "" { + UseCoreServicesStr = "false" + } + UseCoreServices, _ := strconv.ParseBool(UseCoreServicesStr) + if UseCoreServices { + // Register router for graphs + router.GET("/coregraph/*graph", Graph) + } + return router } diff --git a/go.mod b/go.mod index a3e044e..2c18ebd 100644 --- a/go.mod +++ b/go.mod @@ -4,9 +4,10 @@ replace git.smarteching.com/goffee/core/logger => ./logger replace git.smarteching.com/goffee/core/env => ./env -go 1.20 +go 1.23.1 require ( + git.smarteching.com/zeni/go-chart/v2 v2.1.4 github.com/brianvoe/gofakeit/v6 v6.21.0 github.com/golang-jwt/jwt/v5 v5.0.0 github.com/google/uuid v1.3.0 @@ -26,6 +27,7 @@ require ( github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/go-chi/chi/v5 v5.0.8 // indirect github.com/go-sql-driver/mysql v1.7.0 // indirect + github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/pgx/v5 v5.3.1 // indirect @@ -37,8 +39,9 @@ require ( github.com/pkg/errors v0.9.1 // indirect github.com/sendgrid/rest v2.6.9+incompatible // indirect github.com/sendgrid/sendgrid-go v3.12.0+incompatible // indirect + golang.org/x/image v0.21.0 // indirect golang.org/x/net v0.10.0 // indirect - golang.org/x/text v0.11.0 // indirect + golang.org/x/text v0.19.0 // indirect ) require ( diff --git a/go.sum b/go.sum index 4aedeaa..21aed15 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +git.smarteching.com/zeni/go-chart/v2 v2.1.4 h1:pF06+F6eqJLIG8uMiTVPR5TygPGMjM/FHMzTxmu5V/Q= +git.smarteching.com/zeni/go-chart/v2 v2.1.4/go.mod h1:b3ueW9h3pGGXyhkormZAvilHaG4+mQti+bMNPdQBeOQ= github.com/SparkPost/gosparkpost v0.2.0 h1:yzhHQT7cE+rqzd5tANNC74j+2x3lrPznqPJrxC1yR8s= github.com/SparkPost/gosparkpost v0.2.0/go.mod h1:S9WKcGeou7cbPpx0kTIgo8Q69WZvUmVeVzbD+djalJ4= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= @@ -5,7 +7,9 @@ github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:W github.com/brianvoe/gofakeit/v6 v6.21.0 h1:tNkm9yxEbpuPK8Bx39tT4sSc5i9SUGiciLdNix+VDQY= github.com/brianvoe/gofakeit/v6 v6.21.0/go.mod h1:Ow6qC71xtwm79anlwKRlWZW6zVq9D2XHE4QSSMP/rU8= github.com/bsm/ginkgo/v2 v2.7.0 h1:ItPMPH90RbmZJt5GtkcNvIRuGEdwlBItdNVoyzaNQao= +github.com/bsm/ginkgo/v2 v2.7.0/go.mod h1:AiKlXPm7ItEHNc/2+OkrNG4E0ITzojb9/xWzvQ9XZ9w= github.com/bsm/gomega v1.26.0 h1:LhQm+AFcgV2M0WyKroMASzAzCAJVpAxQXv4SaI9a69Y= +github.com/bsm/gomega v1.26.0/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/buger/jsonparser v1.0.0/go.mod h1:tgcrVJ81GPSF0mz+0nu1Xaz0fazGPrmmJfJtxjbHhUQ= github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a/go.mod h1:2GxOXOlEPAMFPfp014mK1SWq8G8BN8o7/dfYqJrVGn8= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= @@ -31,6 +35,8 @@ github.com/go-test/deep v1.0.2/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3a github.com/gogs/chardet v0.0.0-20150115103509-2404f7772561/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14= github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE= github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -83,21 +89,25 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= +golang.org/x/image v0.21.0 h1:c5qV36ajHpdj4Qi0GnE0jUc/yuo33OLFaa0d+crTD5s= +golang.org/x/image v0.21.0/go.mod h1:vUbsLavqK/W303ZroQQVKQ+Af3Yl6Uz1Ppu5J/cLz78= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= -golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= +golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gorm.io/driver/mysql v1.5.1 h1:WUEH5VF9obL/lTtzjmML/5e6VfFR/788coz2uaVCAZw= gorm.io/driver/mysql v1.5.1/go.mod h1:Jo3Xu7mMhCyj8dlrb3WoCaRd1FhsVh+yMXb1jUInf5o= gorm.io/driver/postgres v1.5.2 h1:ytTDxxEv+MplXOfFe3Lzm7SjG09fcdb3Z/c056DTBx0= diff --git a/graph.go b/graph.go new file mode 100644 index 0000000..1ca21b8 --- /dev/null +++ b/graph.go @@ -0,0 +1,140 @@ +// Copyright (c) 2024 Zeni Kim +// Use of this source code is governed by MIT-style +// license that can be found in the LICENSE file. + +package core + +import ( + "fmt" + "net/http" + "strconv" + "strings" + + "git.smarteching.com/zeni/go-chart/v2" + "github.com/julienschmidt/httprouter" +) + +func Graph(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + + // $_GET values + + service := ps.ByName("graph") + + if service != "" { + + //serv := strings.TrimPrefix(service, "/") + serv := strings.Split(service, "/") + + switch serv[1] { + + case "graph": + + kindg := serv[2] + + if kindg != "" { + + switch kindg { + // case graph pie + case "pie": + + queryValues := r.URL.Query() + labels := strings.Split(queryValues.Get("l"), "|") + values := strings.Split(queryValues.Get("v"), "|") + + qtyl := len(labels) + qtyv := len(values) + + // cjeck qty and equal values from url + if qtyl < 2 { + fmt.Fprintf(w, "Missing captions in pie") + return + } + if qtyv != qtyl { + fmt.Fprintf(w, "Labels and values mismatch") + return + } + + var cvalues []chart.Value + var row chart.Value + // fill values + for index, line := range labels { + valuefloat, _ := strconv.ParseFloat(values[index], 64) + row.Value = valuefloat + row.Label = line + cvalues = append(cvalues, row) + } + + pie := chart.PieChart{ + Width: 512, + Height: 512, + Values: cvalues, + } + w.Header().Set("Content-Type", "image/png") + err := pie.Render(chart.PNG, w) + if err != nil { + fmt.Printf("Error rendering pie chart: %v\n", err) + } + + // case graph bar + case "bar": + + queryValues := r.URL.Query() + labels := strings.Split(queryValues.Get("l"), "|") + values := strings.Split(queryValues.Get("v"), "|") + + qtyl := len(labels) + qtyv := len(values) + + // cjeck qty and equal values from url + if qtyl < 2 { + fmt.Fprintf(w, "Missing captions in pie") + return + } + if qtyv != qtyl { + fmt.Fprintf(w, "Labels and values mismatch") + return + } + + var cvalues []chart.Value + var row chart.Value + // fill values + for index, line := range labels { + valuefloat, _ := strconv.ParseFloat(values[index], 64) + row.Value = valuefloat + row.Label = line + cvalues = append(cvalues, row) + } + + bar := chart.BarChart{ + Height: 512, + BarWidth: 50, + Bars: cvalues, + } + w.Header().Set("Content-Type", "image/png") + err := bar.Render(chart.PNG, w) + if err != nil { + fmt.Printf("Error rendering pie chart: %v\n", err) + } + + default: + fmt.Fprintf(w, "Unknown graph %s!\n", kindg) + } + + } else { + fmt.Fprintf(w, "Kind graph not exists") + } + // + + default: + + fmt.Fprintf(w, "Unknown option in core service %s!\n", ps.ByName("serv")) + + } + fmt.Fprintf(w, "Service %s!\n", serv) + + } else { + + fmt.Fprintf(w, "Unknown core service %s!\n", ps.ByName("graph")) + } + +} diff --git a/template/components/content_graph.go b/template/components/content_graph.go new file mode 100644 index 0000000..3c01f97 --- /dev/null +++ b/template/components/content_graph.go @@ -0,0 +1,8 @@ +package components + +type ContentGraph struct { + Graph string // pie, bar + Labels string + Values string + Alt string +} diff --git a/template/components/content_graph.html b/template/components/content_graph.html new file mode 100644 index 0000000..4664137 --- /dev/null +++ b/template/components/content_graph.html @@ -0,0 +1,3 @@ +{{define "content_graph"}} + {{.Alt}} +{{end}} \ No newline at end of file -- 2.39.5 From cd04230f29d3f2e3a1811ac9682c32de912b54f8 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Mon, 28 Oct 2024 12:11:24 -0500 Subject: [PATCH 16/40] remove secure to enable remote cookie --- cookies.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cookies.go b/cookies.go index 8c03c10..ce17dd2 100644 --- a/cookies.go +++ b/cookies.go @@ -126,7 +126,6 @@ func SetCookie(w http.ResponseWriter, email string, token string) error { Path: "/", MaxAge: 3600, HttpOnly: true, - Secure: true, SameSite: http.SameSiteLaxMode, } -- 2.39.5 From 00adaed6a876186f16cbc617acf1ac7ed8914282 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Tue, 29 Oct 2024 06:50:14 -0500 Subject: [PATCH 17/40] add prod mode --- core.go | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/core.go b/core.go index a2c8a2a..d449635 100644 --- a/core.go +++ b/core.go @@ -36,6 +36,7 @@ var cacheC CacheConfig var db *gorm.DB var mailer *Mailer var basePath string +var runMode string var disableEvents bool = false //go:embed all:template @@ -107,11 +108,13 @@ func (app *App) Run(router *httprouter.Router) { } useHttps, _ := strconv.ParseBool(useHttpsStr) - fmt.Printf("Welcome to Goffee\n") - if useHttps { - fmt.Printf("Listening on https \nWaiting for requests...\n") - } else { - fmt.Printf("Listening on port %s\nWaiting for requests...\n", portNumber) + if runMode == "dev" { + fmt.Printf("Welcome to Goffee\n") + if useHttps { + fmt.Printf("Listening on https \nWaiting for requests...\n") + } else { + fmt.Printf("Listening on port %s\nWaiting for requests...\n", portNumber) + } } // check if use letsencrypt @@ -177,7 +180,7 @@ func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httpr } } - // check if use letsencrypt + // check if enable core services UseCoreServicesStr := os.Getenv("App_USE_CORESERVICES") if UseCoreServicesStr == "" { UseCoreServicesStr = "false" @@ -571,6 +574,10 @@ func (app *App) SetBasePath(path string) { basePath = path } +func (app *App) SetRunMode(runmode string) { + runMode = runmode +} + func DisableEvents() { disableEvents = true } -- 2.39.5 From 852d647f097b8d9fea3cf4f4b2e9a0ff57bbcb0a Mon Sep 17 00:00:00 2001 From: Diana Date: Tue, 29 Oct 2024 10:00:24 -0500 Subject: [PATCH 18/40] href add target --- template/components/content_href.go | 1 + template/components/content_href.html | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/template/components/content_href.go b/template/components/content_href.go index 143ca80..99cc6be 100644 --- a/template/components/content_href.go +++ b/template/components/content_href.go @@ -3,6 +3,7 @@ package components type ContentHref struct { Text string Link string + Target string // _blank _parent _self _top Icon string IsButton bool TypeClass string // type primary, secondary, success, danger, warning, info, light, dark, link diff --git a/template/components/content_href.html b/template/components/content_href.html index f4980ac..8537874 100644 --- a/template/components/content_href.html +++ b/template/components/content_href.html @@ -1,5 +1,6 @@ {{define "content_href"}} - {{.Text}} -- 2.39.5 From 1657c19cc4d4d8e4c8e14e2bbce6c9c4bf61215a Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Tue, 29 Oct 2024 12:30:05 -0500 Subject: [PATCH 19/40] add ID to dropdown item --- template/components/content_dropdown.go | 1 + template/components/content_dropdown.html | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/template/components/content_dropdown.go b/template/components/content_dropdown.go index 1040060..78c41c7 100644 --- a/template/components/content_dropdown.go +++ b/template/components/content_dropdown.go @@ -10,6 +10,7 @@ type ContentDropdown struct { type ContentDropdownItem struct { Text string Link string + ID string IsDisabled bool IsActive bool } diff --git a/template/components/content_dropdown.html b/template/components/content_dropdown.html index ce83a26..458a423 100644 --- a/template/components/content_dropdown.html +++ b/template/components/content_dropdown.html @@ -1,5 +1,5 @@ {{define "content_dropdown_item"}} -
  • {{.Text}}
  • +
  • {{.Text}}
  • {{end}} {{define "content_dropdown"}} -- 2.39.5 From 8950cb539a7a749c25d2eb8159635060c0a51884 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Fri, 22 Nov 2024 16:25:06 -0500 Subject: [PATCH 20/40] change to temporary --- core.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core.go b/core.go index d449635..df6254a 100644 --- a/core.go +++ b/core.go @@ -245,7 +245,7 @@ func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Ha w.WriteHeader(ctx.Response.statusCode) } if ctx.Response.redirectTo != "" { - http.Redirect(w, r, ctx.Response.redirectTo, http.StatusPermanentRedirect) + http.Redirect(w, r, ctx.Response.redirectTo, http.StatusTemporaryRedirect) } else { w.Write(ctx.Response.body) } -- 2.39.5 From 5896e6e6174c2b84d7628822483838c036f207ac Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Fri, 6 Dec 2024 04:55:43 -0500 Subject: [PATCH 21/40] add ID to button --- template/components/form_button.go | 2 ++ template/components/form_button.html | 2 +- template/components/form_input.go | 19 ++++++++++--------- template/components/form_input.html | 3 +++ 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/template/components/form_button.go b/template/components/form_button.go index 658306e..4b451bf 100644 --- a/template/components/form_button.go +++ b/template/components/form_button.go @@ -1,6 +1,8 @@ package components type FormButton struct { + ID string + Value string Text string Icon string IsSubmit bool diff --git a/template/components/form_button.html b/template/components/form_button.html index 7594613..b58a9ed 100644 --- a/template/components/form_button.html +++ b/template/components/form_button.html @@ -1,5 +1,5 @@ {{define "form_button"}} - diff --git a/template/components/form_input.go b/template/components/form_input.go index e27910f..d1264ec 100644 --- a/template/components/form_input.go +++ b/template/components/form_input.go @@ -1,13 +1,14 @@ package components type FormInput struct { - ID string - Label string - Type string - Placeholder string - Value string - Hint string - Error string - IsDisabled bool - IsRequired bool + ID string + Label string + Type string + Placeholder string + Value string + Hint string + Error string + IsDisabled bool + Autocomplete bool + IsRequired bool } diff --git a/template/components/form_input.html b/template/components/form_input.html index 8159896..6103b76 100644 --- a/template/components/form_input.html +++ b/template/components/form_input.html @@ -8,6 +8,9 @@ {{if eq .IsRequired true}} required {{end}} + {{if eq .Autocomplete false}} + autocomplete="off" + {{end}} {{if ne .Value ""}} value="{{.Value}}" {{end}} -- 2.39.5 From 5d737c6b10f642c631499dc732f16bbb8041acc5 Mon Sep 17 00:00:00 2001 From: jacs Date: Sun, 8 Dec 2024 00:24:44 -0500 Subject: [PATCH 22/40] add buffer pdf response --- response.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/response.go b/response.go index 7c03b15..525023a 100644 --- a/response.go +++ b/response.go @@ -27,6 +27,17 @@ type header struct { val string } +// TODO add doc +func (rs *Response) BufferPDF(name string, b bytes.Buffer) *Response { + + if rs.isTerminated == false { + rs.HttpResponseWriter.Header().Add("Content-Type", "application/pdf") + rs.HttpResponseWriter.Header().Add("Content-Disposition", "attachment; filename="+name) + b.WriteTo(rs.HttpResponseWriter) + } + return rs +} + // TODO add doc func (rs *Response) Any(body any) *Response { if rs.isTerminated == false { -- 2.39.5 From 2076b4b35bf00549782d39d8f39a0674d708480a Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Sun, 8 Dec 2024 08:52:35 -0500 Subject: [PATCH 23/40] add ID to dropdown --- template/components/content_dropdown.go | 1 + 1 file changed, 1 insertion(+) diff --git a/template/components/content_dropdown.go b/template/components/content_dropdown.go index 78c41c7..65eb21f 100644 --- a/template/components/content_dropdown.go +++ b/template/components/content_dropdown.go @@ -1,6 +1,7 @@ package components type ContentDropdown struct { + ID string Label string TypeClass string // type primary, secondary, success, danger, warning, info, light, dark, link, outline-primary IsDisabled bool -- 2.39.5 From 90564daa5bdc4010c9b95c563cb9d0d8623492e0 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Tue, 17 Dec 2024 14:26:57 -0500 Subject: [PATCH 24/40] improve GetRequestForm, extend templates --- context.go | 5 +++-- template/components/content_table.go | 2 +- template/components/content_table.html | 4 ++++ template/components/form_checkbox.html | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/context.go b/context.go index ad1321d..fba3e7a 100644 --- a/context.go +++ b/context.go @@ -68,8 +68,9 @@ func (c *Context) RequestParamExists(key string) bool { return c.Request.httpRequest.Form.Has(key) } -func (c *Context) GetRequesForm() interface{} { - return c.Request.httpRequest.Form +func (c *Context) GetRequesForm(key string) interface{} { + c.Request.httpRequest.ParseForm() + return c.Request.httpRequest.Form[key] } func (c *Context) GetRequesBodyMap() map[string]interface{} { diff --git a/template/components/content_table.go b/template/components/content_table.go index 1cb7024..9e77908 100644 --- a/template/components/content_table.go +++ b/template/components/content_table.go @@ -10,7 +10,7 @@ type ContentTable struct { type ContentTableTH struct { ID string - ValueType string // -> default string, href, badge + ValueType string // -> default string, href, badge, list, checkbox Value string } diff --git a/template/components/content_table.html b/template/components/content_table.html index 2bf559d..e5aaf50 100644 --- a/template/components/content_table.html +++ b/template/components/content_table.html @@ -13,6 +13,10 @@ {{template "content_href" $item.Value}} {{ else if eq $x.ValueType "badge"}} {{template "content_badge" $item.Value}} + {{ else if eq $x.ValueType "list"}} + {{template "content_list" $item.Value}} + {{ else if eq $x.ValueType "checkbox"}} + {{template "form_checkbox" $item.Value}} {{ else }} {{ $item.Value }} {{end}} diff --git a/template/components/form_checkbox.html b/template/components/form_checkbox.html index 9a8d845..992cff0 100644 --- a/template/components/form_checkbox.html +++ b/template/components/form_checkbox.html @@ -1,6 +1,6 @@ {{define "form_checkbox"}}
    - + {{ if .Label }}{{end}} {{range $options := .AllCheckbox}}
    -- 2.39.5 From 4968da25f3cbd3a98aeffb6da904192256668f11 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Sun, 22 Dec 2024 10:42:56 -0500 Subject: [PATCH 25/40] change BufferPDF to BufferFile to support any kind of file --- response.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/response.go b/response.go index 525023a..2b1047b 100644 --- a/response.go +++ b/response.go @@ -28,10 +28,10 @@ type header struct { } // TODO add doc -func (rs *Response) BufferPDF(name string, b bytes.Buffer) *Response { +func (rs *Response) BufferFile(name string, filetype string, b bytes.Buffer) *Response { if rs.isTerminated == false { - rs.HttpResponseWriter.Header().Add("Content-Type", "application/pdf") + rs.HttpResponseWriter.Header().Add("Content-Type", filetype) rs.HttpResponseWriter.Header().Add("Content-Disposition", "attachment; filename="+name) b.WriteTo(rs.HttpResponseWriter) } -- 2.39.5 From b274d3268f3cf79d43d8e3c57051d5b33ed45abe Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Mon, 23 Dec 2024 23:11:49 -0500 Subject: [PATCH 26/40] add base queue system --- context.go | 9 +++++++++ go.mod | 10 ++++++++-- go.sum | 16 ++++++++++++++++ queue.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 queue.go diff --git a/context.go b/context.go index fba3e7a..7020e84 100644 --- a/context.go +++ b/context.go @@ -19,6 +19,7 @@ import ( "syscall" "git.smarteching.com/goffee/core/logger" + "github.com/hibiken/asynq" "gorm.io/gorm" ) @@ -112,6 +113,14 @@ func (c *Context) GetCookie() (UserCookie, error) { return user, nil } +func (c *Context) GetQueueClient() *asynq.Client { + + redisAddr := fmt.Sprintf("%v:%v", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PORT")) + client := asynq.NewClient(asynq.RedisClientOpt{Addr: redisAddr}) + + return client +} + func (c *Context) GetUploadedFile(name string) *UploadedFileInfo { file, fileHeader, err := c.Request.httpRequest.FormFile(name) if err != nil { diff --git a/go.mod b/go.mod index 2c18ebd..c603849 100644 --- a/go.mod +++ b/go.mod @@ -10,11 +10,11 @@ require ( git.smarteching.com/zeni/go-chart/v2 v2.1.4 github.com/brianvoe/gofakeit/v6 v6.21.0 github.com/golang-jwt/jwt/v5 v5.0.0 - github.com/google/uuid v1.3.0 + github.com/google/uuid v1.6.0 github.com/harranali/mailing v1.2.0 github.com/joho/godotenv v1.5.1 github.com/julienschmidt/httprouter v1.3.0 - github.com/redis/go-redis/v9 v9.0.5 + github.com/redis/go-redis/v9 v9.7.0 golang.org/x/crypto v0.11.0 gorm.io/driver/mysql v1.5.1 gorm.io/driver/postgres v1.5.2 @@ -28,6 +28,7 @@ require ( github.com/go-chi/chi/v5 v5.0.8 // indirect github.com/go-sql-driver/mysql v1.7.0 // indirect github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect + github.com/hibiken/asynq v0.25.1 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/pgx/v5 v5.3.1 // indirect @@ -37,11 +38,16 @@ require ( github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/robfig/cron/v3 v3.0.1 // indirect github.com/sendgrid/rest v2.6.9+incompatible // indirect github.com/sendgrid/sendgrid-go v3.12.0+incompatible // indirect + github.com/spf13/cast v1.7.0 // indirect golang.org/x/image v0.21.0 // indirect golang.org/x/net v0.10.0 // indirect + golang.org/x/sys v0.27.0 // indirect golang.org/x/text v0.19.0 // indirect + golang.org/x/time v0.8.0 // indirect + google.golang.org/protobuf v1.35.2 // indirect ) require ( diff --git a/go.sum b/go.sum index 21aed15..8b77517 100644 --- a/go.sum +++ b/go.sum @@ -40,8 +40,12 @@ github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGw github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/harranali/mailing v1.2.0 h1:ihIyJwB8hyRVcdk+v465wk1PHMrSrgJqo/kMd+gZClY= github.com/harranali/mailing v1.2.0/go.mod h1:4a5N3yG98pZKluMpmcYlTtll7bisvOfGQEMIng3VQk4= +github.com/hibiken/asynq v0.25.1 h1:phj028N0nm15n8O2ims+IvJ2gz4k2auvermngh9JhTw= +github.com/hibiken/asynq v0.25.1/go.mod h1:pazWNOLBu0FEynQRBvHA26qdIKRSmfdIfUm4HdsLmXg= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= @@ -79,11 +83,17 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/redis/go-redis/v9 v9.0.5 h1:CuQcn5HIEeK7BgElubPP8CGtE0KakrnbBSTLjathl5o= github.com/redis/go-redis/v9 v9.0.5/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk= +github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E= +github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw= +github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= +github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/saintfish/chardet v0.0.0-20120816061221-3af4cd4741ca/go.mod h1:uugorj2VCxiV1x+LzaIdVa9b4S4qGAcH6cbhh4qVxOU= github.com/sendgrid/rest v2.6.9+incompatible h1:1EyIcsNdn9KIisLW50MKwmSRSK+ekueiEMJ7NEoxJo0= github.com/sendgrid/rest v2.6.9+incompatible/go.mod h1:kXX7q3jZtJXK5c5qK83bSGMdV6tsOE70KbHoqJls4lE= github.com/sendgrid/sendgrid-go v3.12.0+incompatible h1:/N2vx18Fg1KmQOh6zESc5FJB8pYwt5QFBDflYPh1KVg= github.com/sendgrid/sendgrid-go v3.12.0+incompatible/go.mod h1:QRQt+LX/NmgVEvmdRw0VT/QgUn499+iza2FnDca9fg8= +github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w= +github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= @@ -99,11 +109,17 @@ golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= +golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg= +golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io= +google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/queue.go b/queue.go new file mode 100644 index 0000000..da303df --- /dev/null +++ b/queue.go @@ -0,0 +1,49 @@ +// Copyright (c) 2024 Zeni Kim +// Use of this source code is governed by MIT-style +// license that can be found in the LICENSE file. + +package core + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/hibiken/asynq" +) + +type Asynqtask func(context.Context, *asynq.Task) error + +type Queuemux struct { + themux *asynq.ServeMux +} + +func (q *Queuemux) QueueInit() { + q.themux = asynq.NewServeMux() +} + +func (q *Queuemux) AddWork(pattern string, work Asynqtask) { + q.themux.HandleFunc(pattern, work) +} + +func (q *Queuemux) RunQueueserver() { + + redisAddr := fmt.Sprintf("%v:%v", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PORT")) + + srv := asynq.NewServer( + asynq.RedisClientOpt{Addr: redisAddr}, + asynq.Config{Concurrency: 10, + // Optionally specify multiple queues with different priority. + Queues: map[string]int{ + "critical": 6, + "default": 3, + "low": 1, + }, + }, + ) + + if err := srv.Run(q.themux); err != nil { + log.Fatal(err) + } +} -- 2.39.5 From 0db37d31b86cf8dc0844497d5537b6e1fa65feb0 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Mon, 23 Dec 2024 23:41:27 -0500 Subject: [PATCH 27/40] add config option to disable queues --- config.go | 4 ++++ queue.go | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/config.go b/config.go index f214e84..c481de2 100644 --- a/config.go +++ b/config.go @@ -22,6 +22,10 @@ type GormConfig struct { EnableGorm bool } +type QueueConfig struct { + EnableQueue bool +} + type CacheConfig struct { EnableCache bool } diff --git a/queue.go b/queue.go index da303df..8725844 100644 --- a/queue.go +++ b/queue.go @@ -1,4 +1,4 @@ -// Copyright (c) 2024 Zeni Kim +// Copyright (c) 2025 Zeni Kim // Use of this source code is governed by MIT-style // license that can be found in the LICENSE file. -- 2.39.5 From 695f1f57badb49f1436e7ad1d602332924d0f2e2 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Mon, 24 Feb 2025 09:59:07 -0500 Subject: [PATCH 28/40] add documentation --- .gitignore | 3 ++- README.md | 5 ++--- cache.go | 8 ++++++++ cookies.go | 17 +++++++++++++++- core.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++ queue.go | 3 +++ response.go | 24 +++++++++++++--------- router.go | 13 ++++++++++++ 8 files changed, 116 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index e6c34ba..191579c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ tmp -.DS_STore \ No newline at end of file +.DS_STore +.idea diff --git a/README.md b/README.md index 42f1bf9..73e7ccc 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ -# GoCondor Core -![Build Status](https://github.com/gocondor/core/actions/workflows/build-main.yml/badge.svg) ![Test Status](https://github.com/gocondor/core/actions/workflows/test-main.yml/badge.svg) [![Coverage Status](https://coveralls.io/repos/github/gocondor/core/badge.svg?branch=main)](https://coveralls.io/github/gocondor/core?branch=main&cache=false) [![GoDoc](https://godoc.org/github.com/gocondor/core?status.svg)](https://godoc.org/github.com/gocondor/core) [![Go Report Card](https://goreportcard.com/badge/github.com/gocondor/core)](https://goreportcard.com/report/github.com/gocondor/core) +# Goffee Core -The core packages of GoCondor framework +The core packages of Goffee framework diff --git a/cache.go b/cache.go index 04e818c..4f32bcd 100644 --- a/cache.go +++ b/cache.go @@ -16,6 +16,9 @@ type Cache struct { redis *redis.Client } +// NewCache initializes a new Cache instance with the provided configuration and connects to a Redis database. +// If caching is enabled in the provided configuration but the connection to Redis fails, it causes a panic. +// Returns a pointer to the initialized Cache structure. func NewCache(cacheConfig CacheConfig) *Cache { ctx = context.Background() dbStr := os.Getenv("REDIS_DB") @@ -40,6 +43,7 @@ func NewCache(cacheConfig CacheConfig) *Cache { } } +// Set stores a key-value pair in the Redis cache with no expiration. Returns an error if the operation fails. func (c *Cache) Set(key string, value string) error { err := c.redis.Set(ctx, key, value, 0).Err() if err != nil { @@ -48,6 +52,8 @@ func (c *Cache) Set(key string, value string) error { return nil } +// SetWithExpiration stores a key-value pair in the cache with a specified expiration duration. +// Returns an error if the operation fails. func (c *Cache) SetWithExpiration(key string, value string, expiration time.Duration) error { err := c.redis.Set(ctx, key, value, expiration).Err() if err != nil { @@ -56,6 +62,7 @@ func (c *Cache) SetWithExpiration(key string, value string, expiration time.Dura return nil } +// Get retrieves the value associated with the provided key from the cache. Returns an error if the operation fails. func (c *Cache) Get(key string) (string, error) { result, err := c.redis.Get(ctx, key).Result() if err != nil { @@ -64,6 +71,7 @@ func (c *Cache) Get(key string) (string, error) { return result, nil } +// Delete removes the specified key from the cache and returns an error if the operation fails. func (c *Cache) Delete(key string) error { err := c.redis.Del(ctx, key).Err() if err != nil { diff --git a/cookies.go b/cookies.go index ce17dd2..4e51470 100644 --- a/cookies.go +++ b/cookies.go @@ -21,19 +21,24 @@ import ( "strings" ) +// ErrValueTooLong indicates that the cookie value exceeds the allowed length limit. +// ErrInvalidValue signifies that the cookie value is in an invalid format. var ( ErrValueTooLong = errors.New("cookie value too long") ErrInvalidValue = errors.New("invalid cookie value") ) -// Declare the User type. +// UserCookie represents a structure to hold user-specific data stored in a cookie, including Email and Token fields. type UserCookie struct { Email string Token string } +// secretcookie is a global variable used to store the decoded secret key for encrypting and decrypting cookies. var secretcookie []byte +// GetCookie retrieves and decrypts the user cookie from the provided HTTP request and returns it as a UserCookie. +// Returns an error if the cookie retrieval, decryption, or decoding process fails. func GetCookie(r *http.Request) (UserCookie, error) { var err error @@ -78,6 +83,7 @@ func GetCookie(r *http.Request) (UserCookie, error) { } +// SetCookie sets an encrypted cookie with a user's email and token, using gob encoding for data serialization. func SetCookie(w http.ResponseWriter, email string, token string) error { // Initialize a User struct containing the data that we want to store in the // cookie. @@ -138,6 +144,8 @@ func SetCookie(w http.ResponseWriter, email string, token string) error { return nil } +// CookieWrite writes a secure HTTP cookie to the response writer after base64 encoding its value. +// Returns ErrValueTooLong if the cookie string exceeds the 4096-byte size limit. func CookieWrite(w http.ResponseWriter, cookie http.Cookie) error { // Encode the cookie value using base64. cookie.Value = base64.URLEncoding.EncodeToString([]byte(cookie.Value)) @@ -154,6 +162,8 @@ func CookieWrite(w http.ResponseWriter, cookie http.Cookie) error { return nil } +// CookieRead retrieves a base64-encoded cookie value by name from the HTTP request and decodes it. +// Returns the decoded value as a string or an error if the cookie is not found or the value is invalid. func CookieRead(r *http.Request, name string) (string, error) { // Read the cookie as normal. cookie, err := r.Cookie(name) @@ -173,6 +183,9 @@ func CookieRead(r *http.Request, name string) (string, error) { return string(value), nil } +// CookieWriteEncrypted encrypts the cookie's value using AES-GCM and writes it to the HTTP response writer. +// The cookie name is authenticated along with its value. +// It returns an error if encryption fails or the cookie exceeds the maximum allowed length. func CookieWriteEncrypted(w http.ResponseWriter, cookie http.Cookie, secretKey []byte) error { // Create a new AES cipher block from the secret key. block, err := aes.NewCipher(secretKey) @@ -213,6 +226,8 @@ func CookieWriteEncrypted(w http.ResponseWriter, cookie http.Cookie, secretKey [ return CookieWrite(w, cookie) } +// CookieReadEncrypted reads an encrypted cookie, decrypts its value using AES-GCM, and validates its name before returning. +// Returns the plaintext cookie value or an error if decryption or validation fails. func CookieReadEncrypted(r *http.Request, name string, secretKey []byte) (string, error) { // Read the encrypted value from the cookie as normal. encryptedValue, err := CookieRead(r, name) diff --git a/core.go b/core.go index df6254a..3c80602 100644 --- a/core.go +++ b/core.go @@ -39,13 +39,17 @@ var basePath string var runMode string var disableEvents bool = false +// components_resources holds embedded file system data, typically for templates or other embedded resources. +// //go:embed all:template var components_resources embed.FS +// configContainer is a configuration structure that holds request-specific configurations for the application. type configContainer struct { Request RequestConfig } +// App is a struct representing the main application container and its core components. type App struct { t int // for tracking hooks chain *chain @@ -53,8 +57,10 @@ type App struct { Config *configContainer } +// app is a global instance of the App structure used to manage application configuration and lifecycle. var app *App +// New initializes and returns a new instance of the App structure with default configurations and chain. func New() *App { app = &App{ chain: &chain{}, @@ -66,24 +72,29 @@ func New() *App { return app } +// ResolveApp returns the global instance of the App, providing access to its methods and configuration components. func ResolveApp() *App { return app } +// SetLogsDriver sets the logging driver to be used by the application. func (app *App) SetLogsDriver(d logger.LogsDriver) { logsDriver = &d } +// Bootstrap initializes the application by setting up the logger, router, and events manager. func (app *App) Bootstrap() { loggr = logger.NewLogger(*logsDriver) NewRouter() NewEventsManager() } +// RegisterTemplates initializes the application template system by embedding provided templates for rendering views. func (app *App) RegisterTemplates(templates_resources embed.FS) { NewTemplates(components_resources, templates_resources) } +// Run initializes the application's router, configures HTTPS if enabled, and starts the HTTP/HTTPS server. func (app *App) Run(router *httprouter.Router) { portNumber := os.Getenv("App_HTTP_PORT") if portNumber == "" { @@ -156,6 +167,9 @@ func (app *App) Run(router *httprouter.Router) { log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", portNumber), router)) } +// RegisterRoutes sets up and registers HTTP routes and their handlers to the provided router, enabling request processing. +// It assigns appropriate methods, controllers, and hooks, while handling core services, errors, and fallback behaviors. +// Returns the configured router instance. func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httprouter.Router { router.PanicHandler = panicHandler router.NotFound = notFoundHandler{} @@ -194,6 +208,7 @@ func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httpr return router } +// makeHTTPRouterHandlerFunc creates an httprouter.Handle that handles HTTP requests with the specified controller and hooks. func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { @@ -260,9 +275,13 @@ func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Ha } } +// notFoundHandler is a type that implements the http.Handler interface to handle HTTP 404 Not Found errors. type notFoundHandler struct{} + +// methodNotAllowed is a type that implements http.Handler to handle HTTP 405 Method Not Allowed errors. type methodNotAllowed struct{} +// ServeHTTP handles HTTP requests by responding with a 404 status code and a JSON-formatted "Not Found" message. func (n notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) res := "{\"message\": \"Not Found\"}" @@ -272,6 +291,7 @@ func (n notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte(res)) } +// ServeHTTP handles HTTP requests with method not allowed status and logs the occurrence and stack trace. func (n methodNotAllowed) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusMethodNotAllowed) res := "{\"message\": \"Method not allowed\"}" @@ -281,6 +301,7 @@ func (n methodNotAllowed) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte(res)) } +// panicHandler handles panics during HTTP request processing, logs errors, and formats responses based on environment settings. var panicHandler = func(w http.ResponseWriter, r *http.Request, e interface{}) { isDebugModeStr := os.Getenv("APP_DEBUG_MODE") isDebugMode, err := strconv.ParseBool(isDebugModeStr) @@ -315,10 +336,12 @@ var panicHandler = func(w http.ResponseWriter, r *http.Request, e interface{}) { w.Write([]byte(res)) } +// UseHook registers a Hook middleware function by attaching it to the global Hooks instance. func UseHook(mw Hook) { ResolveHooks().Attach(mw) } +// Next advances to the next middleware or controller in the chain and invokes it with the given context if available. func (app *App) Next(c *Context) { app.t = app.t + 1 n := app.chain.getByIndex(app.t) @@ -335,14 +358,17 @@ func (app *App) Next(c *Context) { } } +// chain represents a sequence of nodes, where each node is an interface, used for executing a series of operations. type chain struct { nodes []interface{} } +// reset clears all nodes in the chain, resetting it to an empty state. func (cn *chain) reset() { cn.nodes = []interface{}{} } +// getByIndex retrieves an element from the chain's nodes slice by its index. Returns nil if the index is out of range. func (c *chain) getByIndex(i int) interface{} { for k := range c.nodes { if k == i { @@ -353,6 +379,7 @@ func (c *chain) getByIndex(i int) interface{} { return nil } +// prepareChain appends all hooks from the provided list and the application's Hooks to the chain's nodes. func (app *App) prepareChain(hs []interface{}) { mw := app.hooks.GetHooks() for _, v := range mw { @@ -363,6 +390,7 @@ func (app *App) prepareChain(hs []interface{}) { } } +// execute executes the first node in the chain, invoking it as either a Hook or Controller if applicable. func (cn *chain) execute(ctx *Context) { i := cn.getByIndex(0) if i != nil { @@ -378,6 +406,7 @@ func (cn *chain) execute(ctx *Context) { } } +// combHandlers combines a controller and a slice of hooks into a single slice of interfaces in reversed order. func (app *App) combHandlers(h Controller, mw []Hook) []interface{} { var rev []interface{} for _, k := range mw { @@ -387,6 +416,8 @@ func (app *App) combHandlers(h Controller, mw []Hook) []interface{} { return rev } +// getGormFunc returns a function that provides a *gorm.DB instance, ensuring gorm is enabled in the configuration. +// If gorm is not enabled, it panics with an appropriate message. func getGormFunc() func() *gorm.DB { f := func() *gorm.DB { if !gormC.EnableGorm { @@ -397,6 +428,9 @@ func getGormFunc() func() *gorm.DB { return f } +// NewGorm initializes and returns a new gorm.DB instance based on the selected database driver specified in environment variables. +// Supported drivers include MySQL, PostgreSQL, and SQLite. +// Panics if the database driver is not specified or if a connection error occurs. func NewGorm() *gorm.DB { var err error switch os.Getenv("DB_DRIVER") { @@ -421,6 +455,7 @@ func NewGorm() *gorm.DB { return db } +// ResolveGorm initializes and returns a singleton instance of *gorm.DB, creating it if it doesn't already exist. func ResolveGorm() *gorm.DB { if db != nil { return db @@ -429,6 +464,8 @@ func ResolveGorm() *gorm.DB { return db } +// resolveCache returns a function that provides a *Cache instance when invoked. +// Panics if caching is not enabled in the configuration. func resolveCache() func() *Cache { f := func() *Cache { if !cacheC.EnableCache { @@ -439,6 +476,8 @@ func resolveCache() func() *Cache { return f } +// postgresConnect establishes a connection to a PostgreSQL database using environment variables for configuration. +// It returns a pointer to a gorm.DB instance or an error if the connection fails. func postgresConnect() (*gorm.DB, error) { dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=%v TimeZone=%v", os.Getenv("POSTGRES_HOST"), @@ -452,6 +491,8 @@ func postgresConnect() (*gorm.DB, error) { return gorm.Open(postgres.Open(dsn), &gorm.Config{}) } +// mysqlConnect establishes a connection to a MySQL database using credentials and configurations from environment variables. +// Returns a *gorm.DB instance on success or an error if the connection fails. func mysqlConnect() (*gorm.DB, error) { dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v&parseTime=True&loc=Local", os.Getenv("MYSQL_USERNAME"), @@ -471,6 +512,9 @@ func mysqlConnect() (*gorm.DB, error) { }), &gorm.Config{}) } +// getJWT returns a function that initializes and provides a *JWT instance configured with environment variables. +// The JWT instance is created using a secret signing key and a lifespan derived from the environment. +// Panics if the signing key is not set or if the lifespan cannot be parsed. func getJWT() func() *JWT { f := func() *JWT { secret := os.Getenv("JWT_SECRET") @@ -494,6 +538,7 @@ func getJWT() func() *JWT { return f } +// getValidator returns a closure that instantiates and provides a new instance of Validator. func getValidator() func() *Validator { f := func() *Validator { return &Validator{} @@ -501,6 +546,7 @@ func getValidator() func() *Validator { return f } +// resloveHashing returns a function that initializes and provides a pointer to a new instance of the Hashing struct. func resloveHashing() func() *Hashing { f := func() *Hashing { return &Hashing{} @@ -508,6 +554,7 @@ func resloveHashing() func() *Hashing { return f } +// resolveMailer initializes and returns a function that provides a singleton Mailer instance based on the configured driver. func resolveMailer() func() *Mailer { f := func() *Mailer { if mailer != nil { @@ -536,6 +583,7 @@ func resolveMailer() func() *Mailer { return f } +// resolveEventsManager creates and returns a function that resolves the singleton instance of EventsManager. func resolveEventsManager() func() *EventsManager { f := func() *EventsManager { return ResolveEventsManager() @@ -543,6 +591,7 @@ func resolveEventsManager() func() *EventsManager { return f } +// resolveLogger returns a function that provides access to the initialized logger instance when invoked. func resolveLogger() func() *logger.Logger { f := func() *logger.Logger { return loggr @@ -550,6 +599,7 @@ func resolveLogger() func() *logger.Logger { return f } +// MakeDirs creates the specified directories under the base path with the provided permissions (0766). func (app *App) MakeDirs(dirs ...string) { o := syscall.Umask(0) defer syscall.Umask(o) @@ -558,30 +608,37 @@ func (app *App) MakeDirs(dirs ...string) { } } +// SetRequestConfig sets the configuration for the request in the application instance. func (app *App) SetRequestConfig(r RequestConfig) { requestC = r } +// SetGormConfig sets the GormConfig for the application, overriding the current configuration with the provided value. func (app *App) SetGormConfig(g GormConfig) { gormC = g } +// SetCacheConfig sets the cache configuration for the application using the provided CacheConfig parameter. func (app *App) SetCacheConfig(c CacheConfig) { cacheC = c } +// SetBasePath sets the base path for the application, which is used as a prefix for file and directory operations. func (app *App) SetBasePath(path string) { basePath = path } +// SetRunMode sets the application run mode to the specified value. func (app *App) SetRunMode(runmode string) { runMode = runmode } +// DisableEvents sets the global variable `disableEvents` to true, disabling the handling or triggering of events. func DisableEvents() { disableEvents = true } +// EnableEvents sets the global variable `disableEvents` to false, effectively enabling event handling. func EnableEvents() { disableEvents = false } diff --git a/queue.go b/queue.go index 8725844..905a6ed 100644 --- a/queue.go +++ b/queue.go @@ -27,6 +27,9 @@ func (q *Queuemux) AddWork(pattern string, work Asynqtask) { q.themux.HandleFunc(pattern, work) } +// RunQueueserver starts the queue server with predefined configurations and handles tasks using the assigned ServeMux. +// Configures the queue server with concurrency limits and priority-based queue management. +// Logs and terminates the program if the server fails to run. func (q *Queuemux) RunQueueserver() { redisAddr := fmt.Sprintf("%v:%v", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PORT")) diff --git a/response.go b/response.go index 2b1047b..46f31ee 100644 --- a/response.go +++ b/response.go @@ -11,6 +11,7 @@ import ( "net/http" ) +// Response represents an HTTP response to be sent to the client, including headers, body, status code, and metadata. type Response struct { headers []header body []byte @@ -22,12 +23,13 @@ type Response struct { HttpResponseWriter http.ResponseWriter } +// header represents a single HTTP header with a key-value pair. type header struct { key string val string } -// TODO add doc +// writes the contents of a buffer to the HTTP response with specified file name and type if not terminated. func (rs *Response) BufferFile(name string, filetype string, b bytes.Buffer) *Response { if rs.isTerminated == false { @@ -38,7 +40,7 @@ func (rs *Response) BufferFile(name string, filetype string, b bytes.Buffer) *Re return rs } -// TODO add doc +// sets the response's content type to HTML and assigns the provided body as the response body if not terminated. func (rs *Response) Any(body any) *Response { if rs.isTerminated == false { rs.contentType = CONTENT_TYPE_HTML @@ -48,7 +50,7 @@ func (rs *Response) Any(body any) *Response { return rs } -// TODO add doc +// sets the response's content type to JSON and assigns the provided string as the body if the response is not terminated. func (rs *Response) Json(body string) *Response { if rs.isTerminated == false { rs.contentType = CONTENT_TYPE_JSON @@ -57,7 +59,7 @@ func (rs *Response) Json(body string) *Response { return rs } -// TODO add doc +// sets the response's content type to plain text and assigns the provided string as the body if not terminated. func (rs *Response) Text(body string) *Response { if rs.isTerminated == false { rs.contentType = CONTENT_TYPE_TEXT @@ -66,7 +68,7 @@ func (rs *Response) Text(body string) *Response { return rs } -// TODO add doc +// sets the response's content type to HTML and assigns the provided string as the body if the response is not terminated. func (rs *Response) HTML(body string) *Response { if rs.isTerminated == false { rs.contentType = CONTENT_TYPE_HTML @@ -75,7 +77,7 @@ func (rs *Response) HTML(body string) *Response { return rs } -// TODO add doc +// renders the specified template with the provided data and writes the result to the HTTP response if not terminated. func (rs *Response) Template(name string, data interface{}) *Response { var buffer bytes.Buffer if rs.isTerminated == false { @@ -89,7 +91,7 @@ func (rs *Response) Template(name string, data interface{}) *Response { return rs } -// TODO add doc +// sets the response status code if the response is not yet terminated. Returns the updated Response object. func (rs *Response) SetStatusCode(code int) *Response { if rs.isTerminated == false { rs.statusCode = code @@ -98,7 +100,7 @@ func (rs *Response) SetStatusCode(code int) *Response { return rs } -// TODO add doc +// sets a custom content type for the response if it is not terminated. Returns the updated Response object. func (rs *Response) SetContentType(c string) *Response { if rs.isTerminated == false { rs.overrideContentType = c @@ -107,7 +109,7 @@ func (rs *Response) SetContentType(c string) *Response { return rs } -// TODO add doc +// adds or updates a header to the response if it is not terminated. Returns the updated Response object. func (rs *Response) SetHeader(key string, val string) *Response { if rs.isTerminated == false { h := header{ @@ -119,10 +121,12 @@ func (rs *Response) SetHeader(key string, val string) *Response { return rs } +// terminates the response processing, preventing any further modifications or actions. func (rs *Response) ForceSendResponse() { rs.isTerminated = true } +// updates the redirect URL for the response and returns the modified Response. Validates the URL before setting it. func (rs *Response) Redirect(url string) *Response { validator := resolveValidator() v := validator.Validate(map[string]interface{}{ @@ -142,6 +146,7 @@ func (rs *Response) Redirect(url string) *Response { return rs } +// converts various primitive data types to their string representation or triggers a panic for unsupported types. func (rs *Response) castBasicVarsToString(data interface{}) string { switch dataType := data.(type) { case string: @@ -199,6 +204,7 @@ func (rs *Response) castBasicVarsToString(data interface{}) string { } } +// reinitializes the Response object to its default state, clearing its body, headers, and resetting other properties. func (rs *Response) reset() { rs.body = nil rs.statusCode = http.StatusOK diff --git a/router.go b/router.go index 24141b4..163f22a 100644 --- a/router.go +++ b/router.go @@ -5,6 +5,7 @@ package core +// Route defines an HTTP route with a method, path, controller function, and optional hooks for customization. type Route struct { Method string Path string @@ -12,12 +13,15 @@ type Route struct { Hooks []Hook } +// Router represents a structure for storing and managing routes in the application. type Router struct { Routes []Route } +// router is a global instance of the Router struct used to manage and resolve application routes. var router *Router +// NewRouter initializes and returns a new Router instance with an empty slice of routes. func NewRouter() *Router { router = &Router{ []Route{}, @@ -25,10 +29,12 @@ func NewRouter() *Router { return router } +// ResolveRouter returns the singleton instance of the Router. It initializes and manages HTTP routes configuration. func ResolveRouter() *Router { return router } +// Get registers a GET route with the specified path, controller, and optional hooks, returning the updated Router. func (r *Router) Get(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: GET, @@ -39,6 +45,7 @@ func (r *Router) Get(path string, controller Controller, hooks ...Hook) *Router return r } +// Post registers a route with the HTTP POST method, associating it with the given path, controller, and optional hooks. func (r *Router) Post(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: POST, @@ -49,6 +56,7 @@ func (r *Router) Post(path string, controller Controller, hooks ...Hook) *Router return r } +// Delete registers a DELETE HTTP method route with the specified path, controller, and optional hooks. func (r *Router) Delete(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: DELETE, @@ -59,6 +67,7 @@ func (r *Router) Delete(path string, controller Controller, hooks ...Hook) *Rout return r } +// Patch registers a new route with the HTTP PATCH method, a specified path, a controller, and optional hooks. func (r *Router) Patch(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: PATCH, @@ -69,6 +78,7 @@ func (r *Router) Patch(path string, controller Controller, hooks ...Hook) *Route return r } +// Put registers a new route with the HTTP PUT method, associating it to the given path, controller, and optional hooks. func (r *Router) Put(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: PUT, @@ -79,6 +89,7 @@ func (r *Router) Put(path string, controller Controller, hooks ...Hook) *Router return r } +// Options registers a new route with the OPTIONS HTTP method, a specified path, controller, and optional hooks. func (r *Router) Options(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: OPTIONS, @@ -89,6 +100,7 @@ func (r *Router) Options(path string, controller Controller, hooks ...Hook) *Rou return r } +// Head registers a route with the HTTP HEAD method, associates it with a path, controller, and optional hooks. func (r *Router) Head(path string, controller Controller, hooks ...Hook) *Router { r.Routes = append(r.Routes, Route{ Method: HEAD, @@ -99,6 +111,7 @@ func (r *Router) Head(path string, controller Controller, hooks ...Hook) *Router return r } +// GetRoutes returns a slice of Route objects currently registered within the Router. func (r *Router) GetRoutes() []Route { return r.Routes } -- 2.39.5 From 3b6fa12911c90fb5d4da30523c9a530512d3c261 Mon Sep 17 00:00:00 2001 From: Jose Antonio Cely Saidiza Date: Wed, 5 Mar 2025 15:12:11 -0500 Subject: [PATCH 29/40] change panic by err --- context.go | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/context.go b/context.go index 7020e84..c603030 100644 --- a/context.go +++ b/context.go @@ -121,34 +121,43 @@ func (c *Context) GetQueueClient() *asynq.Client { return client } -func (c *Context) GetUploadedFile(name string) *UploadedFileInfo { +func (c *Context) GetUploadedFile(name string) (*UploadedFileInfo, error) { file, fileHeader, err := c.Request.httpRequest.FormFile(name) if err != nil { - panic(fmt.Sprintf("error with file,[%v]", err.Error())) + return nil, fmt.Errorf("error retrieving file: %v", err) } defer file.Close() + + // Extract the file extension ext := strings.TrimPrefix(path.Ext(fileHeader.Filename), ".") tmpFilePath := filepath.Join(os.TempDir(), fileHeader.Filename) tmpFile, err := os.Create(tmpFilePath) if err != nil { - panic(fmt.Sprintf("error with file,[%v]", err.Error())) + return nil, fmt.Errorf("error creating temporary file: %v", err) } + defer tmpFile.Close() + // Copy the uploaded file content to the temporary file buff := make([]byte, 100) for { n, err := file.Read(buff) if err != nil && err != io.EOF { - panic("error with uploaded file") + return nil, fmt.Errorf("error reading uploaded file: %v", err) } if n == 0 { break } - n, _ = tmpFile.Write(buff[:n]) + _, err = tmpFile.Write(buff[:n]) + if err != nil { + return nil, fmt.Errorf("error writing to temporary file: %v", err) + } } + + // Get file info for the temporary file tmpFileInfo, err := os.Stat(tmpFilePath) if err != nil { - panic(fmt.Sprintf("error with file,[%v]", err.Error())) + return nil, fmt.Errorf("error getting file info: %v", err) } - defer tmpFile.Close() + uploadedFileInfo := &UploadedFileInfo{ FullPath: tmpFilePath, Name: fileHeader.Filename, @@ -156,7 +165,7 @@ func (c *Context) GetUploadedFile(name string) *UploadedFileInfo { Extension: ext, Size: int(tmpFileInfo.Size()), } - return uploadedFileInfo + return uploadedFileInfo, nil } func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error { @@ -185,7 +194,7 @@ func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error { for { n, err := srcFile.Read(buff) if err != nil && err != io.EOF { - panic(fmt.Sprintf("error moving file %v", sourceFilePath)) + return fmt.Errorf("error moving file: %v", sourceFilePath) } if n == 0 { break @@ -229,7 +238,7 @@ func (c *Context) CopyFile(sourceFilePath string, destFolderPath string) error { for { n, err := srcFile.Read(buff) if err != nil && err != io.EOF { - panic(fmt.Sprintf("error moving file %v", sourceFilePath)) + return fmt.Errorf("error moving file: %v", sourceFilePath) } if n == 0 { break -- 2.39.5 From 790c840f767695c0ebdff0cb8be7b7991274df18 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Tue, 18 Mar 2025 20:14:52 -0500 Subject: [PATCH 30/40] split if --- core.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core.go b/core.go index 3c80602..cb31680 100644 --- a/core.go +++ b/core.go @@ -104,8 +104,8 @@ func (app *App) Run(router *httprouter.Router) { // check if template engine is enable TemplateEnableStr := os.Getenv("TEMPLATE_ENABLE") - if TemplateEnableStr == "" { - TemplateEnableStr = "false" + if "" == TemplateEnableStr { + TemplateEnableStr = 'false' } TemplateEnable, _ := strconv.ParseBool(TemplateEnableStr) // if enabled, @@ -119,7 +119,7 @@ func (app *App) Run(router *httprouter.Router) { } useHttps, _ := strconv.ParseBool(useHttpsStr) - if runMode == "dev" { + if "dev" == runMode { fmt.Printf("Welcome to Goffee\n") if useHttps { fmt.Printf("Listening on https \nWaiting for requests...\n") -- 2.39.5 From 1a39c666a38bee0dd4ea4395476277789707bcdf Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Tue, 18 Mar 2025 23:43:09 -0500 Subject: [PATCH 31/40] fix --- core.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core.go b/core.go index cb31680..967eaca 100644 --- a/core.go +++ b/core.go @@ -105,7 +105,7 @@ func (app *App) Run(router *httprouter.Router) { // check if template engine is enable TemplateEnableStr := os.Getenv("TEMPLATE_ENABLE") if "" == TemplateEnableStr { - TemplateEnableStr = 'false' + TemplateEnableStr = "false" } TemplateEnable, _ := strconv.ParseBool(TemplateEnableStr) // if enabled, -- 2.39.5 From db3c510f9a1d7a47f908cf902c2afee108b06501 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Thu, 27 Mar 2025 12:12:49 -0500 Subject: [PATCH 32/40] add img and class to table template, new responnse buffer inline --- response.go | 10 ++++++++++ template/components/content_table.go | 7 ++++--- template/components/content_table.html | 4 +++- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/response.go b/response.go index 46f31ee..d6202c7 100644 --- a/response.go +++ b/response.go @@ -40,6 +40,16 @@ func (rs *Response) BufferFile(name string, filetype string, b bytes.Buffer) *Re return rs } +// writes the contents of a buffer to the HTTP response with specified file name and type if not terminated. +func (rs *Response) BufferInline(name string, filetype string, b bytes.Buffer) *Response { + + if rs.isTerminated == false { + rs.HttpResponseWriter.Header().Add("Content-Type", filetype) + b.WriteTo(rs.HttpResponseWriter) + } + return rs +} + // sets the response's content type to HTML and assigns the provided body as the response body if not terminated. func (rs *Response) Any(body any) *Response { if rs.isTerminated == false { diff --git a/template/components/content_table.go b/template/components/content_table.go index 9e77908..eb0199e 100644 --- a/template/components/content_table.go +++ b/template/components/content_table.go @@ -9,9 +9,10 @@ type ContentTable struct { } type ContentTableTH struct { - ID string - ValueType string // -> default string, href, badge, list, checkbox - Value string + ID string + ValueType string // -> default string, href, badge, list, checkbox + Value string + ValueClass string } type ContentTableTD struct { diff --git a/template/components/content_table.html b/template/components/content_table.html index e5aaf50..656e7e0 100644 --- a/template/components/content_table.html +++ b/template/components/content_table.html @@ -16,7 +16,9 @@ {{ else if eq $x.ValueType "list"}} {{template "content_list" $item.Value}} {{ else if eq $x.ValueType "checkbox"}} - {{template "form_checkbox" $item.Value}} + {{template "form_checkbox" $item.Value}} + {{ else if eq $x.ValueType "image"}} + {{ else }} {{ $item.Value }} {{end}} -- 2.39.5 From cc8c79fe3dba908321c4e31206db8efab890769c Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Thu, 27 Mar 2025 12:19:18 -0500 Subject: [PATCH 33/40] add img and class to table template --- template/components/content_table.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/template/components/content_table.go b/template/components/content_table.go index eb0199e..5c6a21b 100644 --- a/template/components/content_table.go +++ b/template/components/content_table.go @@ -9,13 +9,13 @@ type ContentTable struct { } type ContentTableTH struct { - ID string - ValueType string // -> default string, href, badge, list, checkbox - Value string - ValueClass string + ID string + ValueType string // -> default string, href, badge, list, checkbox + Value string } type ContentTableTD struct { - ID string - Value interface{} // string or component struct according ValueType + ID string + Value interface{} // string or component struct according ValueType + ValueClass string } -- 2.39.5 From 259f2f4b79e53325c94b0428e7e81444b280fefc Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Thu, 27 Mar 2025 12:41:17 -0500 Subject: [PATCH 34/40] add img and class to table template --- template/components/content_table.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/template/components/content_table.html b/template/components/content_table.html index 656e7e0..36f9b8b 100644 --- a/template/components/content_table.html +++ b/template/components/content_table.html @@ -7,7 +7,7 @@ {{- range .AllTD}} - {{range $index, $item := .}} + {{range $index, $item := .}} {{ with $x := index $.AllTH $index }} {{ if eq $x.ValueType "href"}} {{template "content_href" $item.Value}} @@ -18,7 +18,7 @@ {{ else if eq $x.ValueType "checkbox"}} {{template "form_checkbox" $item.Value}} {{ else if eq $x.ValueType "image"}} - + {{ else }} {{ $item.Value }} {{end}} -- 2.39.5 From e3748c853fd6bcc355d32b73d6fdcf88fea10522 Mon Sep 17 00:00:00 2001 From: jacs Date: Tue, 15 Apr 2025 07:23:34 -0500 Subject: [PATCH 35/40] template with select multiple, input custom attribute --- template/components/form_input.go | 6 ++++++ template/components/form_input.html | 5 +++++ template/components/form_select.go | 1 + template/components/form_select.html | 2 +- 4 files changed, 13 insertions(+), 1 deletion(-) diff --git a/template/components/form_input.go b/template/components/form_input.go index d1264ec..0ee8150 100644 --- a/template/components/form_input.go +++ b/template/components/form_input.go @@ -11,4 +11,10 @@ type FormInput struct { IsDisabled bool Autocomplete bool IsRequired bool + CustomAtt []CustomAtt +} + +type CustomAtt struct { + AttName string + AttValue string } diff --git a/template/components/form_input.html b/template/components/form_input.html index 6103b76..adf33e8 100644 --- a/template/components/form_input.html +++ b/template/components/form_input.html @@ -14,6 +14,11 @@ {{if ne .Value ""}} value="{{.Value}}" {{end}} + {{if .CustomAtt }} + {{range $options := .CustomAtt}} + {{$options.AttName}}="{{$options.AttValue}}" + {{end}} + {{end}} aria-describedby="{{.ID}}Help"> {{if ne .Hint ""}}{{.Hint}}{{end}} {{if ne .Error ""}}
    {{.Error}}
    {{end}} diff --git a/template/components/form_select.go b/template/components/form_select.go index db94fe3..ea10ea5 100644 --- a/template/components/form_select.go +++ b/template/components/form_select.go @@ -5,6 +5,7 @@ type FormSelect struct { SelectedOption FormSelectOption Label string AllOptions []FormSelectOption + IsMultiple bool } type FormSelectOption struct { diff --git a/template/components/form_select.html b/template/components/form_select.html index 6317e6b..eb222e5 100644 --- a/template/components/form_select.html +++ b/template/components/form_select.html @@ -1,7 +1,7 @@ {{define "form_select"}}
    - {{range $options := .AllOptions}} {{end}} -- 2.39.5 From f276f4d61d9ef9c74929fcaa9c490668c4b7e6dd Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Thu, 17 Apr 2025 01:49:43 -0500 Subject: [PATCH 36/40] add element paginator --- template/components/content_pagination.go | 9 +++++++++ template/components/content_pagination.html | 10 ++++++++++ 2 files changed, 19 insertions(+) create mode 100644 template/components/content_pagination.go create mode 100644 template/components/content_pagination.html diff --git a/template/components/content_pagination.go b/template/components/content_pagination.go new file mode 100644 index 0000000..87434a2 --- /dev/null +++ b/template/components/content_pagination.go @@ -0,0 +1,9 @@ +package components + +type ContentPagination struct { + PageStartRecord int + PageEndRecord int + TotalRecords int + PrevLink string + NextLink string +} diff --git a/template/components/content_pagination.html b/template/components/content_pagination.html new file mode 100644 index 0000000..a51e09d --- /dev/null +++ b/template/components/content_pagination.html @@ -0,0 +1,10 @@ +{{define "content_pagination"}} +
    +
      +
    • {{.PageStartRecord}} - {{.PageEndRecord}} of {{.TotalRecords}}
    • +
    •  
    • +
    • «
    • +
    • »
    • +
    +
    +{{end}} \ No newline at end of file -- 2.39.5 From 653fd5c64e1597662d66770ec36de9884dd4bba3 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Sun, 27 Apr 2025 23:41:25 -0500 Subject: [PATCH 37/40] add ID to PageNavItem --- template/components/page_nav.go | 1 + 1 file changed, 1 insertion(+) diff --git a/template/components/page_nav.go b/template/components/page_nav.go index 862d1c8..671e79a 100644 --- a/template/components/page_nav.go +++ b/template/components/page_nav.go @@ -10,6 +10,7 @@ type PageNav struct { type PageNavItem struct { Text string Link string + ID string IsDisabled bool IsActive bool ChildItems []PageNavItem -- 2.39.5 From 30746a06028debec9407e81ee4fe514eb8cc2081 Mon Sep 17 00:00:00 2001 From: Zeni Kim Date: Mon, 28 Apr 2025 00:11:04 -0500 Subject: [PATCH 38/40] check child items to active nav --- template/components/page_nav.html | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/template/components/page_nav.html b/template/components/page_nav.html index 08faaf4..5c34fad 100644 --- a/template/components/page_nav.html +++ b/template/components/page_nav.html @@ -3,9 +3,15 @@ {{range $item := .NavItems}} {{if gt (len $item.ChildItems) 0}} + {{ $hasActiveChild := false }} + {{range $child := $item.ChildItems}} + {{if $child.IsActive}} + {{ $hasActiveChild = true }} + {{end}} + {{end}}