Compare commits

...

38 commits
v1.7.3 ... main

Author SHA1 Message Date
b87e0113c9 Merge pull request 'develop' (#12) from develop into main
Reviewed-on: #12
2024-10-29 13:31:47 -04:00
1657c19cc4 add ID to dropdown item 2024-10-29 12:30:05 -05:00
95a37c9aca Merge pull request 'develop' (#11) from diana/core:develop into develop
Reviewed-on: #11
2024-10-29 13:29:04 -04:00
852d647f09 href add target 2024-10-29 10:00:24 -05:00
a390b5a02f Merge pull request 'develop' (#4) from goffee/core:develop into develop
Reviewed-on: diana/core#4
2024-10-29 10:57:55 -04:00
f07131086a Merge pull request 'add prod mode' (#10) from develop into main
Reviewed-on: #10
2024-10-29 07:53:38 -04:00
00adaed6a8 add prod mode 2024-10-29 06:50:14 -05:00
2a4a092cb2 Merge pull request 'develop' (#9) from develop into main
Reviewed-on: #9
2024-10-28 13:20:05 -04:00
cd04230f29 remove secure to enable remote cookie 2024-10-28 12:11:24 -05:00
7c92148ae4 add core services, add graph service, add component graph 2024-10-28 11:33:06 -05:00
59ea47dcd6 detail table 2024-10-27 12:54:34 -05:00
789a157571 Merge pull request 'develop' (#8) from develop into main
Reviewed-on: #8
2024-10-23 08:11:16 -04:00
cf8b3bdde7 Merge pull request 'component switch' (#7) from diana/core:develop into develop
Reviewed-on: #7
2024-10-23 08:08:05 -04:00
7218f26d68 component switch 2024-10-21 17:25:50 -05:00
8eb14bd2da Merge pull request 'develop' (#3) from goffee/core:develop into develop
Reviewed-on: diana/core#3
2024-10-21 18:16:44 -04:00
b9cd82867b Merge pull request 'develop' (#6) from develop into main
Reviewed-on: #6
2024-10-16 00:04:58 -04:00
00b8012edf fix conflict 2024-10-15 22:18:32 -05:00
be138b2fb4 add middle line 2024-10-15 22:15:20 -05:00
cc74165659 add cookie secret as env, fix components 2024-10-15 22:00:46 -05:00
bf84e14bb1 component list 2024-10-15 16:09:31 -05:00
458ad520ca Input required, table (class, href, badge) 2024-10-15 16:09:17 -05:00
f398ebb02d dropdown, href is content 2024-10-15 16:07:18 -05:00
a904773bab Badge 2024-10-15 16:06:49 -05:00
05bd3a01ee Merge pull request 'develop' (#2) from goffee/core:develop into develop
Reviewed-on: diana/core#2
2024-10-14 17:22:05 -04:00
45e7079005 Merge pull request 'develop components' (#4) from diana/core:develop into develop
Reviewed-on: #4
2024-10-14 16:27:09 -04:00
1c1740d97b base table 2024-10-14 12:13:51 -05:00
7073cd1c21 components: buttons, dropdown, href, nav 2024-10-12 13:01:52 -05:00
bfde0cc445 Merge pull request 'develop' (#1) from goffee/core:develop into develop
Reviewed-on: diana/core#1
2024-10-12 13:47:50 -04:00
8f17bf6a8c add form components 2024-10-08 07:58:42 -05:00
015e85bf7b start theme core templates 2024-10-07 18:10:04 -05:00
da7925ae08 Merge branch 'develop' of git.smarteching.com:goffee/core into develop 2024-09-30 09:13:10 -05:00
2bffdcdcf7 start cookie session 2024-09-30 09:12:38 -05:00
edc0c0c036 Merge pull request 'get body request, validator fix' (#3) from diana/core:develop into develop
Reviewed-on: #3
2024-09-28 18:50:43 -04:00
a82b6812e3 get body request, validator fix 2024-09-28 17:40:42 -05:00
21319dab48 Merge pull request 'theme base system' (#1) from develop into main
Reviewed-on: #1
2024-09-27 10:48:29 -04:00
465e88bf40 theme base system 2024-09-27 02:27:24 -05:00
1172e23c16 template system 2024-09-24 16:12:17 -05:00
711a68699a add public path 2024-09-23 19:04:14 -05:00
45 changed files with 1026 additions and 18 deletions

View file

@ -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!"

View file

@ -68,10 +68,49 @@ 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)
}
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 {

270
cookies.go Normal file
View file

@ -0,0 +1,270 @@
// Copyright (c) 2024 Zeni Kim <zenik@smarteching.com>
// Use of this source code is governed by MIT-style
// license that can be found in the LICENSE file.
package core
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/gob"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"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
// 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)
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
// 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
}
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,
SameSite: http.SameSiteLaxMode,
}
// Write an encrypted cookie containing the gob-encoded data as normal.
err = CookieWriteEncrypted(w, cookie, secretcookie)
if err != nil {
return err
}
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
}

48
core.go
View file

@ -6,6 +6,7 @@
package core
import (
"embed"
"fmt"
"log"
"net/http"
@ -35,14 +36,18 @@ var cacheC CacheConfig
var db *gorm.DB
var mailer *Mailer
var basePath string
var runMode string
var disableEvents bool = false
//go:embed all:template
var components_resources embed.FS
type configContainer struct {
Request RequestConfig
}
type App struct {
t int // for trancking hooks
t int // for tracking hooks
chain *chain
hooks *Hooks
Config *configContainer
@ -75,24 +80,44 @@ func (app *App) Bootstrap() {
NewEventsManager()
}
func (app *App) RegisterTemplates(templates_resources embed.FS) {
NewTemplates(components_resources, templates_resources)
}
func (app *App) Run(router *httprouter.Router) {
portNumber := os.Getenv("App_HTTP_PORT")
if portNumber == "" {
portNumber = "80"
}
router = app.RegisterRoutes(ResolveRouter().GetRoutes(), router)
// check if template engine is enable
TemplateEnableStr := os.Getenv("TEMPLATE_ENABLE")
if TemplateEnableStr == "" {
TemplateEnableStr = "false"
}
TemplateEnable, _ := strconv.ParseBool(TemplateEnableStr)
// if enabled,
if TemplateEnable {
router.ServeFiles("/public/*filepath", http.Dir("storage/public"))
}
useHttpsStr := os.Getenv("App_USE_HTTPS")
if useHttpsStr == "" {
useHttpsStr = "false"
}
useHttps, _ := strconv.ParseBool(useHttpsStr)
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
UseLetsEncryptStr := os.Getenv("App_USE_LETSENCRYPT")
if UseLetsEncryptStr == "" {
UseLetsEncryptStr = "false"
@ -135,6 +160,7 @@ func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httpr
router.PanicHandler = panicHandler
router.NotFound = notFoundHandler{}
router.MethodNotAllowed = methodNotAllowed{}
for _, route := range routes {
switch route.Method {
case GET:
@ -153,11 +179,24 @@ func (app *App) RegisterRoutes(routes []Route, router *httprouter.Router) *httpr
router.HEAD(route.Path, app.makeHTTPRouterHandlerFunc(route.Controller, route.Hooks))
}
}
// check if enable core services
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
}
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,
@ -181,11 +220,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)
}
@ -198,6 +239,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)
@ -532,6 +574,10 @@ func (app *App) SetBasePath(path string) {
basePath = path
}
func (app *App) SetRunMode(runmode string) {
runMode = runmode
}
func DisableEvents() {
disableEvents = true
}

7
go.mod
View file

@ -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 (

14
go.sum
View file

@ -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=

140
graph.go Normal file
View file

@ -0,0 +1,140 @@
// Copyright (c) 2024 Zeni Kim <zenik@smarteching.com>
// 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"))
}
}

View file

@ -6,6 +6,7 @@
package core
import (
"bytes"
"fmt"
"net/http"
)
@ -63,6 +64,20 @@ func (rs *Response) HTML(body string) *Response {
return rs
}
// TODO add doc
func (rs *Response) Template(name string, data interface{}) *Response {
var buffer bytes.Buffer
if rs.isTerminated == false {
err := tmpl.ExecuteTemplate(&buffer, name, data)
if err != nil {
panic(fmt.Sprintf("error executing template: %v", err))
}
rs.contentType = CONTENT_TYPE_HTML
buffer.WriteTo(rs.HttpResponseWriter)
}
return rs
}
// TODO add doc
func (rs *Response) SetStatusCode(code int) *Response {
if rs.isTerminated == false {

View file

@ -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
}

View file

@ -0,0 +1,7 @@
{{define "content_badge"}}
<span class="badge {{if eq .IsOutline true}}
border border-{{.TypeClass}} bg-{{.TypeClass}}-subtle text-{{.TypeClass}}-emphasis
{{else}}
text-bg-{{if .TypeClass}}{{.TypeClass}}{{else}}secondary{{end}}
{{end}} rounded-pill ">{{.Text}}</span>
{{end}}

View file

@ -0,0 +1,16 @@
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
ID string
IsDisabled bool
IsActive bool
}

View file

@ -0,0 +1,16 @@
{{define "content_dropdown_item"}}
<li><a {{ if .ID }}id="{{.ID}}"{{end}} class="dropdown-item {{if eq .IsActive true}}active{{end}} {{if eq .IsDisabled true}}disabled{{end}}" href="{{.Link}}">{{.Text}}</a></li>
{{end}}
{{define "content_dropdown"}}
<div class="dropdown">
<button class="btn btn-{{.TypeClass}} dropdown-toggle {{if eq .IsDisabled true}}disabled{{end}}" type="button" data-bs-toggle="dropdown" aria-expanded="false">
{{.Label}}
</button>
<ul class="dropdown-menu">
{{ range .Items}}
{{template "content_dropdown_item" .}}
{{end}}
</ul>
</div>
{{end}}

View file

@ -0,0 +1,8 @@
package components
type ContentGraph struct {
Graph string // pie, bar
Labels string
Values string
Alt string
}

View file

@ -0,0 +1,3 @@
{{define "content_graph"}}
<img src="/coregraph/graph/{{.Graph}}?l={{.Labels}}&v={{.Values}}" alt="{{.Alt}}">
{{end}}

View file

@ -0,0 +1,11 @@
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
IsDisabled bool
}

View file

@ -0,0 +1,7 @@
{{define "content_href"}}
<a class="{{if eq .IsButton true}} btn btn-{{.TypeClass}}{{end}} {{if eq .IsDisabled true}}disabled{{end}}"
{{if .Target}} target="{{.Target}}"{{end}}
href="{{.Link}}" {{if eq .IsButton true}}role="button"{{end}} {{if eq .IsDisabled true}}aria-disabled="true"{{end}}>
{{.Text}}
</a>
{{end}}

View file

@ -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

View file

@ -0,0 +1,14 @@
{{define "content_list"}}
<ul class="list-group">
{{ range .Items}}
<li class="list-group-item text-wrap {{if eq .IsDisabled true}}disabled{{end}} {{if .TypeClass}}list-group-item-{{.TypeClass}}{{end}}"
{{if eq .IsDisabled true}}aria-disabled="true"{{end}}
><div class="d-flex justify-content-between lh-sm"><p class="mb-1">{{.Text}}</p><span class="text-body-secondary ms-5">{{.EndElement}}</span></div>
<small>{{.Description}}</small>
</li>
{{end}}
</ul>
{{end}}

View file

@ -0,0 +1,20 @@
package components
type ContentTable struct {
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
ValueType string // -> default string, href, badge
Value string
}
type ContentTableTD struct {
ID string
Value interface{} // string or component struct according ValueType
}

View file

@ -0,0 +1,25 @@
{{define "content_table"}}
<table class="table table-hover {{.TableClass}}" {{ if .ID }}id="{{.ID}}"{{end}}>
<thead class="{{.HeadClass}}">
<tr>
{{range $index, $col := .AllTH}}<th {{ if .ID }}id="{{.ID}}"{{end}} scope="col">{{ $col.Value }}</th>{{end}}
</tr>
</thead>
<tbody>
{{- range .AllTD}}<tr scope="row">
{{range $index, $item := .}}<td {{ if $item.ID }}id="{{$item.ID}}"{{end}}>
{{ 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}}
</td>
{{end}}</tr>
{{- end}}
</tbody>
</table>
{{end}}

View file

@ -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
}

View file

@ -0,0 +1,29 @@
{{define "content_tabledetail"}}
<table class="table table-hover" {{ if .ID }}id="{{.ID}}"{{end}}>
{{$stylecell := "table-success"}}
{{if .HeadClass }}{{$stylecell = .HeadClass}}{{end}}
{{if .Title }}
<thead class="{{.HeadClass}}">
<tr>
<th colspan="2" class="{{$stylecell}}">{{ .Title }}</th>
</tr>
</thead>
{{end}}
<tbody>
{{range $item := .AllTD}}
<tr scope="row" {{ if $item.ID }}id="{{$item.ID}}"{{end}}>
<td class="{{$stylecell}}">{{ $item.Caption }}</td>
<td>
{{ 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}}
</td>
</tr>
{{end}}
</tbody>
</table>
{{end}}

View file

@ -0,0 +1,9 @@
package components
type FormButton struct {
Text string
Icon string
IsSubmit bool
TypeClass string // type primary, secondary, success, danger, warning, info, light, dark, link, outline-primary
IsDisabled bool
}

View file

@ -0,0 +1,20 @@
{{define "form_button"}}
<button class="btn btn-{{.TypeClass}}" {{if eq .IsSubmit true}}type="submit"{{else}}type="button"{{end}} {{if .IsDisabled}}disabled{{end}}>
{{.Text}}
</button>
<!-- tailwind heroicons -->
{{if eq .Icon "gear"}}
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="icon">
<path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z" />
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
</svg>
{{else if eq .Icon "arrow-right"}}
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="icon">
<path stroke-linecap="round" stroke-linejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3" />
</svg>
{{else if eq .Icon "plus"}}
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="icon">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
</svg>
{{end}}
{{end}}

View file

@ -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
}

View file

@ -0,0 +1,11 @@
{{define "form_checkbox"}}
<div class="input-container">
<label class="form-label">{{.Label}}</label>
{{range $options := .AllCheckbox}}
<div class="form-check">
<input class="form-check-input" type="checkbox" name="{{$options.Name}}" id="{{$options.ID}}" value="{{$options.Value}}"{{if eq $options.IsChecked true}} checked{{end}}>
<label class="form-check-label" for="{{$options.ID}}">{{$options.Label}}</label>
</div>
{{end}}
</div>
{{end}}

View file

@ -0,0 +1,13 @@
package components
type FormInput struct {
ID string
Label string
Type string
Placeholder string
Value string
Hint string
Error string
IsDisabled bool
IsRequired bool
}

View file

@ -0,0 +1,18 @@
{{define "form_input"}}
<div class="input-container">
<label class="form-label" for="{{.ID}}">{{.Label}}</label>
<input type="{{.Type}}" id="{{.ID}}" name="{{.ID}}" placeholder="{{.Placeholder}}" class="form-control{{if ne .Error ""}} error{{end}}"
{{if eq .IsDisabled true}}
disabled
{{end}}
{{if eq .IsRequired true}}
required
{{end}}
{{if ne .Value ""}}
value="{{.Value}}"
{{end}}
aria-describedby="{{.ID}}Help">
{{if ne .Hint ""}}<small id="{{.ID}}Help" class="form-text text-muted">{{.Hint}}</small>{{end}}
{{if ne .Error ""}}<div class="error">{{.Error}}</div>{{end}}
</div>
{{end}}

View file

@ -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
}

View file

@ -0,0 +1,11 @@
{{define "form_radio"}}
<div class="input-container">
<label class="form-label">{{.Label}}</label>
{{range $options := .AllRadios}}
<div class="form-check{{if eq $options.IsDisabled true}} disabled{{end}}">
<input class="form-check-input" type="radio" name="{{$options.Name}}" id="{{$options.ID}}" value="{{$options.Value}}"{{if eq $options.IsDisabled true}} disabled=""{{end}}{{if eq $options.IsChecked true}} checked=""{{end}}>
<label class="form-check-label" for="{{$options.ID}}">{{$options.Label}}</label>
</div>
{{end}}
</div>
{{end}}

View file

@ -0,0 +1,13 @@
package components
type FormSelect struct {
ID string
SelectedOption FormSelectOption
Label string
AllOptions []FormSelectOption
}
type FormSelectOption struct {
Value string
Caption string
}

View file

@ -0,0 +1,10 @@
{{define "form_select"}}
<div class="input-container">
<label for="{{.ID}}" class="form-label">{{.Label}}</label>
<select class="form-select" id="{{.ID}}" name="{{.ID}}">
{{range $options := .AllOptions}}
<option value="{{$options.Value}}" {{if eq $options.Value $.SelectedOption.Value }}selected="selected"{{end}}>{{$options.Caption}}</option>
{{end}}
</select>
</div>
{{end}}

View file

@ -0,0 +1,8 @@
package components
type FormSwitch struct {
ID string
Label string
IsChecked bool
IsDisabled bool
}

View file

@ -0,0 +1,7 @@
{{define "form_switch"}}
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" role="switch" name="{{.ID}}" id="{{.ID}}" {{if eq .IsChecked true}} checked{{end}} {{if eq .IsDisabled true}} disabled{{end}}>
<label class="form-check-label" for="{{.ID}}">{{.Label}}</label>
</div>
{{end}}

View file

@ -0,0 +1,7 @@
package components
type FormTextarea struct {
ID string
Label string
Value string
}

View file

@ -0,0 +1,6 @@
{{define "form_textarea"}}
<div class="input-container">
<label for="{{.ID}}" class="form-label">{{.Label}}</label>
<textarea class="form-control" id="{{.ID}}" name="{{.ID}}" rows="3">{{.Value}}</textarea>
</div>
{{end}}

View file

@ -0,0 +1,8 @@
package components
type PageCard struct {
CardTitle string
CardSubTitle string
CardBody string
CardLink string
}

View file

@ -0,0 +1,11 @@
{{define "page_card"}}
<div class="card">
<div class="card-body">
{{if .CardTitle}}<h5 class="card-title">{{.CardTitle}}</h5>{{end}}
{{if .CardSubTitle}}<h6 class="card-subtitle mb-2 text-muted">{{.CardSubTitle}}</h6>{{end}}
{{if .CardBody}}<p class="card-text">{{.CardBody}}</p>{{end}}
{{block "page_card_content" .}}{{end}}
{{if .CardLink}}<a href="{{.CardLink}}" class="card-link">Card link</a>{{end}}
</div>
</div>
{{end}}

View file

@ -0,0 +1,7 @@
{{define "page_footer"}}
<footer>
<script src="/public/app.js"></script>
</footer>
<script src="/public/bootstrap/js/popper.min.js"></script>
<script src="/public/bootstrap/js/bootstrap.min.js"></script>
{{end}}

View file

@ -0,0 +1,11 @@
{{define "page_head"}}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{.}} | Goffee</title>
<link rel="stylesheet" href="/public/style.css">
<link rel="icon" href="/public/img/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="/public/bootstrap/css/bootstrap.min.css">
</head>
{{end}}

View file

@ -0,0 +1,16 @@
package components
type PageNav struct {
NavClass string // nav-pills, nav-underline
NavItems []PageNavItem
IsVertical bool
IsTab bool
}
type PageNavItem struct {
Text string
Link string
IsDisabled bool
IsActive bool
ChildItems []PageNavItem
}

View file

@ -0,0 +1,23 @@
{{define "page_nav"}}
<ul class="nav justify-content-center {{.NavClass}} {{if eq .IsVertical true}}flex-column{{end}}{{if eq .IsTab true}}nav-tabs{{end}}" {{if eq .IsTab true}}role="tablist"{{end}}>
{{range $item := .NavItems}}
{{if gt (len $item.ChildItems) 0}}
<li class="nav-item dropdown">
<a href="{{$item.Link}}" {{if eq .IsDisabled true}}disabled{{end}} data-bs-toggle="dropdown"
class="nav-link dropdown-toggle {{if eq .IsActive true}}active{{end}} {{if eq .IsDisabled true}}disabled{{end}}">{{$item.Text}}</a>
<ul class="dropdown-menu">
{{ range $item.ChildItems}}
{{template "content_dropdown_item" .}}
{{end}}
</ul>
</li>
{{else}}
<li class="nav-item"><a href="{{$item.Link}}" {{if eq .IsDisabled true}}disabled{{end}} class="nav-link {{if eq .IsActive true}}active{{end}} {{if eq .IsDisabled true}}disabled{{end}}">
{{$item.Text}}
</a></li>
{{end}}
{{end}}
</ul>
{{end}}

View file

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
{{template "page_head" "Goffee"}}
<body>
<div class="container">
{{block "page_content" .}}
<main>
<h1>Use this file as base inside cup application</h1>
</main>
{{end}}
{{template "page_footer"}}
</div>
</body>
</html>

36
templates.go Normal file
View file

@ -0,0 +1,36 @@
// Copyright (c) 2024 Zeni Kim <zenik@smarteching.com>
// Use of this source code is governed by MIT-style
// license that can be found in the LICENSE file.
package core
import (
"embed"
"html/template"
"io/fs"
"strings"
)
var tmpl *template.Template = nil
func NewTemplates(components embed.FS, templates embed.FS) {
// templates
var paths []string
fs.WalkDir(components, ".", func(path string, d fs.DirEntry, err error) error {
if strings.Contains(d.Name(), ".html") {
paths = append(paths, path)
}
return nil
})
var pathst []string
fs.WalkDir(templates, ".", func(patht string, d fs.DirEntry, err error) error {
if strings.Contains(d.Name(), ".html") {
pathst = append(pathst, patht)
}
return nil
})
tmpla := template.Must(template.ParseFS(components, paths...))
tmpl = template.Must(tmpla.ParseFS(templates, pathst...))
}

View file

@ -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())
}
}