Skip to content

Commit 815c8ba

Browse files
committed
[Core+Svelte]: better context store and html "engine" + svelte typescript support
1 parent 56e4ac8 commit 815c8ba

File tree

11 files changed

+299
-209
lines changed

11 files changed

+299
-209
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,4 @@ func main() {
5050
## todo:
5151
- [ ] SSR
5252
- [ ] SSE
53-
- [x] CSS Engines like Tailwindcss
53+
- [x] CSS Engine (Tailwindcss)

cmd/main.go

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,40 @@
11
package main
22

33
import (
4-
gosvelt "github.com/4lxprime/GoSvelt"
4+
gs "github.com/4lxprime/GoSvelt"
55
"github.com/fasthttp/websocket"
66
)
77

88
func main() {
9-
gs := gosvelt.New()
9+
r := gs.New(&gs.Config{
10+
TypeScript: false,
11+
})
1012

11-
gs.Middleware("/", func(next gosvelt.HandlerFunc) gosvelt.HandlerFunc {
12-
return func(c *gosvelt.Context) error {
13-
return next(c)
13+
r.SvelteMiddleware("/", func(next gs.SvelteHandlerFunc) gs.SvelteHandlerFunc {
14+
return func(c *gs.Context, svelte gs.Map) error {
15+
return next(c, svelte)
1416
}
1517
})
1618

17-
gs.Get("/gg/:name", func(c *gosvelt.Context) error {
18-
return c.Json(200, gosvelt.Map{"gg": c.Param("name")})
19+
r.Get("/gg/:name", func(c *gs.Context) error {
20+
return c.Json(200, gs.Map{"gg": c.Param("name")})
1921
})
2022

21-
gs.Get("/test", func(c *gosvelt.Context) error {
23+
r.Get("/test", func(c *gs.Context) error {
2224
return c.Text(200, "Hello, World!")
2325
})
2426

25-
gs.Get("/ws", func(c *gosvelt.Context) error {
27+
r.Get("/ws", func(c *gs.Context) error {
2628
return c.Ws(func(conn *websocket.Conn) {
27-
conn.WriteJSON(gosvelt.Map{"ez": "pz"})
29+
conn.WriteJSON(gs.Map{"ez": "pz"})
2830
})
2931
})
3032

31-
gs.Static("/index", "./cmd/static/index.html")
33+
r.Static("/svelte_logo", "./cmd/static/svelte_logo.svg")
3234

33-
gs.AdvancedSvelte("/advanced", "./cmd/static/", "app/App.svelte", func(c *gosvelt.Context, svelte gosvelt.Map) error {
35+
r.AdvancedSvelte("/", "./cmd/static/", "app/App.svelte", func(c *gs.Context, svelte gs.Map) error {
3436
return c.Html(200, "./cmd/static/index.html", svelte)
3537
}, true)
3638

37-
gs.Start(":8080")
39+
r.Start(":8080")
3840
}

cmd/static/App.svelte

Lines changed: 0 additions & 26 deletions
This file was deleted.

cmd/static/app/App.svelte

Lines changed: 49 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,59 @@
11
<script>
2-
import Gosvelt from "../gosvelt/gosvelt.svelte";
2+
import { onMount } from 'svelte';
33
4-
let name = "world";
4+
let canvas;
5+
6+
onMount(() => {
7+
const ctx = canvas.getContext('2d');
8+
let frame;
9+
10+
(function loop() {
11+
frame = requestAnimationFrame(loop);
12+
13+
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
14+
15+
for (let p = 0; p < imageData.data.length; p += 4) {
16+
const i = p / 4;
17+
const x = i % canvas.width;
18+
const y = (i / canvas.height) >>> 0;
19+
20+
const t = window.performance.now();
21+
22+
const r = 64 + (128 * x) / canvas.width + 64 * Math.sin(t / 1000);
23+
const g = 64 + (128 * y) / canvas.height + 64 * Math.cos(t / 1400);
24+
const b = 128;
25+
26+
imageData.data[p + 0] = r;
27+
imageData.data[p + 1] = g;
28+
imageData.data[p + 2] = b;
29+
imageData.data[p + 3] = 255;
30+
}
31+
32+
ctx.putImageData(imageData, 0, 0);
33+
})();
34+
35+
return () => {
36+
cancelAnimationFrame(frame);
37+
};
38+
});
539
</script>
640

7-
<main class="bg-zinc-50 justify-center items-center">
8-
<h1 class="p-2">Hello {name}</h1>
9-
<Gosvelt/>
41+
<main class="bg-zinc-800 h-screen items-center justify-center text-center flex">
42+
<header class="absolute top-0 left-0 w-full h-8 bg-zinc-700 flex-grow">
43+
<div class="">
44+
<h1 class="text-xl text-white">GoSvelt</h1>
45+
</div>
46+
</header>
47+
<canvas class="w-60" bind:this={canvas} width={32} height={32} />
1048
</main>
1149

1250
<style>
1351
@tailwind base;
1452
@tailwind components;
1553
@tailwind utilities;
16-
17-
main {
18-
align-items: center;
19-
justify-content: center;
20-
}
21-
22-
h1 {
23-
text-transform: uppercase;
24-
color: aqua;
25-
}
26-
</style>
54+
55+
canvas {
56+
-webkit-mask: url(/svelte_logo) 50% 50% no-repeat;
57+
mask: url(/svelte_logo) 50% 50% no-repeat;
58+
}
59+
</style>

cmd/static/gosvelt/gosvelt.svelte

Lines changed: 0 additions & 7 deletions
This file was deleted.

cmd/static/index.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22
<html lang="en">
33
<head>
44
<meta charset='utf-8'>
5+
<meta name="robots" content="noindex,nofollow">
56
<meta name='viewport' content='width=device-width,initial-scale=1'>
7+
<meta name="description" content="">
68

79
<title>GoSvelt App</title>
10+
811
<link rel='stylesheet' href='&{css}'>
912
<script defer src='&{js}'></script>
1013
</head>

cmd/static/svelte_logo.svg

Lines changed: 10 additions & 0 deletions
Loading

context.go

Lines changed: 79 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@ import (
77
"io/ioutil"
88
"os"
99
"path/filepath"
10-
"regexp"
11-
"strconv"
10+
"strings"
1211
"sync"
1312
"time"
1413

@@ -66,29 +65,74 @@ func (c *Context) Args() *fasthttp.Args {
6665

6766
// CONTEXT STORE -->
6867

69-
func (c *Context) Set(key, value string) {
68+
func (c *Context) CSet(key, value string) {
7069
c.lock.Lock()
7170
defer c.lock.Unlock()
7271

7372
if c.store == nil {
7473
c.store = make(Map)
7574
}
7675

77-
c.store[key] = value
76+
if pool, ok := c.gosvelt.storePool.Get().(Map); ok {
77+
pool[key] = value
78+
c.store = pool
79+
80+
} else {
81+
c.store[key] = value
82+
}
7883
}
7984

80-
func (c *Context) Get(key string) string {
85+
func (c *Context) CGet(key string) string {
8186
c.lock.RLock()
8287
defer c.lock.RUnlock()
8388

84-
return c.store[key].(string)
89+
if c.store == nil {
90+
return ""
91+
}
92+
93+
if pool, ok := c.gosvelt.storePool.Get().(Map); ok {
94+
value, ok := pool[key]
95+
if ok {
96+
return value.(string)
97+
}
98+
99+
value = c.store[key]
100+
pool[key] = value
101+
c.store = pool
102+
103+
return value.(string)
104+
}
105+
106+
if value, ok := c.store[key]; ok {
107+
return value.(string)
108+
}
109+
110+
return ""
111+
}
112+
113+
func (c *Context) CDel(key string) {
114+
c.lock.Lock()
115+
defer c.lock.Unlock()
116+
117+
if c.store == nil {
118+
return
119+
}
120+
121+
if pool, ok := c.gosvelt.storePool.Get().(Map); ok {
122+
delete(pool, key)
123+
c.store = pool
124+
125+
} else {
126+
delete(c.store, key)
127+
}
85128
}
86129

87-
func (c *Context) CacheReset() {
130+
func (c *Context) CReset() {
88131
c.lock.Lock()
89132
defer c.lock.Unlock()
90133

91134
c.store = make(Map)
135+
c.gosvelt.storePool.Put(c.store)
92136
}
93137

94138
// CONTEXT RESPONSES -->
@@ -115,54 +159,45 @@ func (c *Context) Html(code int, t string, args ...any) error {
115159

116160
switch args[0].(type) {
117161
case string:
118-
// find pattern &{x} and replace it with an given arg
119-
// where x is an string
120-
re := regexp.MustCompile(`&{(\d+)}`)
121-
output = re.ReplaceAllStringFunc(t, func(match string) string {
122-
digitStr := re.FindStringSubmatch(match)[1]
123-
digit, _ := strconv.Atoi(digitStr)
124-
125-
if digit >= 1 && digit <= len(args) {
126-
// convert []any into []string
127-
strArgs := make([]string, len(args))
128-
for i, v := range args {
129-
strArgs[i] = v.(string)
130-
}
131-
return strArgs[digit-1]
132-
}
133-
134-
return match
135-
})
162+
// create a map of placeholders to values
163+
placeholders := make(map[string]string)
164+
for i, arg := range args[1:] {
165+
placeholders[fmt.Sprintf("%d", i+1)] = fmt.Sprint(arg)
166+
}
167+
168+
// replace placeholders in the template with values
169+
for placeholder, value := range placeholders {
170+
t = strings.ReplaceAll(t, fmt.Sprintf("&{%s}", placeholder), value)
171+
}
172+
173+
output = t
136174

137175
case Map:
138-
// find pattern &{x} and replace it with an given arg
139-
// where x is an string without ""
140-
re := regexp.MustCompile(`&{(\w+)}`)
141-
output = re.ReplaceAllStringFunc(t, func(match string) string {
142-
key := re.FindStringSubmatch(match)[1]
176+
// create a map of placeholders to values
177+
placeholders := make(map[string]string)
178+
for key, value := range args[0].(Map) {
179+
placeholders[fmt.Sprintf("&{%s}", key)] = fmt.Sprint(value)
180+
}
143181

144-
if value, ok := args[0].(Map)[key]; ok {
145-
if strValue, ok := value.(string); ok {
146-
return strValue
147-
}
148-
}
182+
// replace placeholders in the template with values
183+
for placeholder, value := range placeholders {
184+
t = strings.ReplaceAll(t, placeholder, value)
185+
}
149186

150-
return match
151-
})
187+
output = t
152188

153189
default:
154-
return fmt.Errorf("args must be ...string or gosvelt.Map")
190+
return fmt.Errorf("args must be...string or gosvelt.Map")
155191
}
156192

157-
c.SetCType("text/html; charset=UTF-8")
193+
c.SetCType(MTextHtmlUTF8)
158194

159195
c.SetStatusCode(code)
160196
c.Write([]byte(output))
161197

162198
return nil
163199
}
164200

165-
// todo: fix "Error occurred: not found" but it work
166201
func (c *Context) File(code int, file string, compress ...bool) error {
167202
fs := &fasthttp.FS{
168203
Root: "",
@@ -312,7 +347,7 @@ func (c *Context) Secure() bool {
312347

313348
// get the url params with key
314349
func (c *Context) Param(key string) string {
315-
return fmt.Sprintf("%s", c.fasthttpCtx.UserValue(key)) // todo: remplace fasthttp context by something else
350+
return fmt.Sprintf("%s", c.fasthttpCtx.UserValue(key))
316351
}
317352

318353
// add an cookie
@@ -330,7 +365,7 @@ func (c *Context) SetCookie(k, v string, expire time.Time) {
330365

331366
// write to client
332367
func (c *Context) Write(body []byte) {
333-
c.fasthttpCtx.Write(body) // todo: remplace fasthttp context by something else
368+
c.Res().AppendBody(body) // todo: remplace fasthttp context by something else
334369
}
335370

336371
// set response header
@@ -340,10 +375,10 @@ func (c *Context) SetHeader(key, value string) {
340375

341376
// set response status code in int
342377
func (c *Context) SetStatusCode(code int) {
343-
c.Res().SetStatusCode(code)
378+
c.Res().Header.SetStatusCode(code)
344379
}
345380

346381
// set response content type
347382
func (c *Context) SetCType(ctype string) {
348-
c.SetHeader("Content-Type", ctype)
383+
c.Res().Header.Set("Content-Type", ctype)
349384
}

0 commit comments

Comments
 (0)