Skip to content

Commit cc87e67

Browse files
committed
Update example (serve_a_folder)
1 parent 635f7a0 commit cc87e67

File tree

6 files changed

+405
-74
lines changed

6 files changed

+405
-74
lines changed

examples/serve_a_folder/main.go

Lines changed: 112 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,83 +1,152 @@
11
package main
22

33
import (
4-
"time"
4+
"fmt"
55

66
ui "github.com/webui-dev/go-webui/v2"
77
)
88

9+
// Those constants are to avoid using global variables
10+
// you can also use `const w ui.Window = 1`.
11+
// A window ID can be between 1 and 512 (WEBUI_MAX_IDS)
912
const (
10-
w = ui.Window(1)
11-
w2 = ui.Window(2)
13+
MyWindow = ui.Window(1)
14+
MySecondWindow = ui.Window(2)
1215
)
1316

17+
func exitApp(e ui.Event) any {
18+
// Close all opened windows
19+
ui.Exit()
20+
return nil
21+
}
22+
1423
func events(e ui.Event) any {
24+
// This function gets called every time
25+
// there is an event
26+
1527
if e.EventType == ui.Connected {
16-
println("Connected.")
28+
fmt.Println("Connected.")
1729
} else if e.EventType == ui.Disconnected {
18-
println("Disconnected.")
30+
fmt.Println("Disconnected.")
1931
} else if e.EventType == ui.MouseClick {
20-
println("Click.")
32+
fmt.Println("Click.")
2133
} else if e.EventType == ui.Navigation {
22-
target, _ := ui.GetArg[string](e)
23-
println("Starting navigation to: ", target)
24-
// Since we bind all events, following `href` links is blocked by WebUI.
25-
// To control the navigation, we need to use `Navigate()`.
26-
e.Window.Navigate(target)
34+
url, _ := ui.GetArg[string](e)
35+
fmt.Printf("Starting navigation to: %s\n", url)
36+
37+
// Because we used `w.Bind("", events)`
38+
// WebUI will block all `href` link clicks and sent here instead.
39+
// We can then control the behaviour of links as needed.
40+
e.Window.Navigate(url)
2741
}
2842
return nil
2943
}
3044

3145
func switchToSecondPage(e ui.Event) any {
46+
// This function gets called every
47+
// time the user clicks on "SwitchToSecondPage"
48+
49+
// Switch to `/second.html` in the same opened window.
3250
e.Window.Show("second.html")
3351
return nil
3452
}
3553

3654
func showSecondWindow(e ui.Event) any {
37-
w2.Show("second.html")
38-
// Remove the Go Back button when showing the second page in another window.
39-
// Wait max. 10 seconds until the window is recognized as shown.
40-
for i := 0; i < 1000; i++ {
41-
if w2.IsShown() {
42-
break
43-
}
44-
// Slow down check interval to reduce load.
45-
time.Sleep(10 * time.Millisecond)
46-
}
47-
if !w2.IsShown() {
48-
return nil
49-
}
50-
// Let the DOM load.
51-
time.Sleep(50 * time.Millisecond)
52-
// Remove `Go Back` button.
53-
w2.Run("document.getElementById('go-back').remove();")
55+
// This function gets called every
56+
// time the user clicks on "OpenNewWindow"
5457

58+
// Show a new window, and navigate to `/second.html`
59+
// if it's already open, then switch in the same window
60+
MySecondWindow.Show("second.html")
5561
return nil
5662
}
5763

58-
func exit(e ui.Event) any {
59-
ui.Exit()
60-
return nil
64+
// Counter for dynamic content
65+
var count int
66+
67+
func myFilesHandler(filename string) ([]byte, int) {
68+
fmt.Printf("File: %s\n", filename)
69+
70+
if filename == "/test.txt" {
71+
// Const static file example
72+
response := "HTTP/1.1 200 OK\r\n" +
73+
"Content-Type: text/html\r\n" +
74+
"Content-Length: 99\r\n\r\n" +
75+
"<html>" +
76+
" This is a static embedded file content example." +
77+
" <script src=\"webui.js\"></script>" + // To keep connection with WebUI
78+
"</html>"
79+
return []byte(response), len(response)
80+
} else if filename == "/dynamic.html" {
81+
// Dynamic file example
82+
83+
// Generate body
84+
count++
85+
body := fmt.Sprintf(
86+
"<html>"+
87+
" This is a dynamic file content example. <br>"+
88+
" Count: %d <a href=\"dynamic.html\">[Refresh]</a><br>"+
89+
" <script src=\"webui.js\"></script>"+ // To keep connection with WebUI
90+
"</html>",
91+
count,
92+
)
93+
94+
// Generate header + body
95+
response := fmt.Sprintf(
96+
"HTTP/1.1 200 OK\r\n"+
97+
"Content-Type: text/html\r\n"+
98+
"Content-Length: %d\r\n\r\n"+
99+
"%s",
100+
len(body), body,
101+
)
102+
103+
return []byte(response), len(response)
104+
}
105+
106+
// Other files:
107+
// A nil return will make WebUI
108+
// look for the file locally.
109+
return nil, 0
61110
}
62111

63112
func main() {
64113
ui.SetDefaultRootFolder("ui")
114+
115+
// Create new windows
116+
MyWindow.NewWindow()
117+
MySecondWindow.NewWindow()
118+
119+
// Bind HTML element IDs with Go functions
120+
MyWindow.Bind("SwitchToSecondPage", switchToSecondPage)
121+
MyWindow.Bind("OpenNewWindow", showSecondWindow)
122+
MyWindow.Bind("Exit", exitApp)
123+
MySecondWindow.Bind("Exit", exitApp)
124+
125+
// Bind events
126+
MyWindow.Bind("", events)
65127

66-
w.NewWindow()
128+
// Set the `.ts` and `.js` runtime
129+
// MyWindow.SetRuntime(ui.Nodejs)
130+
// MyWindow.SetRuntime(ui.Bun)
131+
MyWindow.SetRuntime(ui.Deno)
67132

68-
// Bind HTML elements to functions
69-
w.Bind("switch-to-second-page", switchToSecondPage)
70-
w.Bind("open-new-window", showSecondWindow)
71-
w.Bind("exit", exit)
72-
// Bind all events.
73-
w.Bind("", events)
133+
// Set a custom files handler
134+
MyWindow.SetFileHandler(myFilesHandler)
74135

75-
// Show the main window.
76-
w.Show("index.html")
136+
// Set window size
137+
MyWindow.SetSize(800, 800)
77138

78-
// Prepare the second window.
79-
w2.NewWindow()
80-
w2.Bind("exit", exit)
139+
// Set window position
140+
MyWindow.SetPosition(200, 200)
81141

142+
// Show a new window
143+
// MyWindow.SetRootFolder("_MY_PATH_HERE_")
144+
// MyWindow.ShowBrowser("index.html", ui.Chrome)
145+
MyWindow.Show("index.html")
146+
147+
// Wait until all windows get closed
82148
ui.Wait()
149+
150+
// Free all memory resources (Optional)
151+
ui.Clean()
83152
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// This file gets called like follow:
2+
//
3+
// 1. UI `Index.html` request:
4+
// `http://localhost:xxx/bun_test.ts?foo=123&bar=456`
5+
//
6+
// 2. WebUI runs command:
7+
// `bun run "bun_test.ts" "foo=123&bar=456"`
8+
//
9+
// 3. Bun parses args and prints the response
10+
11+
// Get Query (HTTP GET)
12+
const args = process.argv.slice(2);
13+
const query = args[0];
14+
15+
// Variables
16+
let foo: string = '';
17+
let bar: string = '';
18+
19+
// Read Query
20+
const params = new URLSearchParams(query);
21+
for (const [key, value] of params.entries()) {
22+
if (key === 'foo') foo = value; // 123
23+
else if (key === 'bar') bar = value; // 456
24+
}
25+
26+
console.log('Response from Bun: ' + (parseInt(foo) + parseInt(bar))); // 579
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// This file gets called like follow:
2+
//
3+
// 1. UI `Index.html` request:
4+
// `http://localhost:xxx/deno_test.ts?foo=123&bar=456`
5+
//
6+
// 2. WebUI runs command:
7+
// `deno run --allow-all --unstable "deno_test.ts" "foo=123&bar=456"`
8+
//
9+
// 3. Deno parse args and print the response
10+
11+
// Import parse()
12+
import { parse } from 'https://deno.land/std/flags/mod.ts';
13+
14+
// Get Query (HTTP GET)
15+
const args = parse(Deno.args);
16+
const query = args._[0] as string;
17+
18+
// Variables
19+
let foo: string = '';
20+
let bar: string = '';
21+
22+
// Read Query
23+
const params = new URLSearchParams(query);
24+
for (const [key, value] of params.entries()) {
25+
if (key == 'foo') foo = value; // 123
26+
else if (key == 'bar') bar = value; // 456
27+
}
28+
29+
console.log('Response from Deno: ' + (parseInt(foo) + parseInt(bar))); // 579

0 commit comments

Comments
 (0)