Skip to content

Commit bf7c22b

Browse files
author
Nexus
committed
docs: add more examples (JWT, file-upload, CORS)
- Add JWT authentication example - Add file upload example - Add CORS configuration example - Update examples README
1 parent 107e22b commit bf7c22b

4 files changed

Lines changed: 257 additions & 6 deletions

File tree

example/README.md

Lines changed: 61 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,63 @@
1-
# DotWeb
2-
Simple and easy go web micro framework
1+
# DotWeb Examples
32

4-
More examples: https://github.com/devfeel/dotweb-example
3+
This directory contains various examples demonstrating dotweb features.
54

6-
## Contact Us
7-
#### QQ-Group:193409346 - <a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=836e11667837ad674462a4a97fb21fba487cd3dff5b2e1ca0d7ea4c2324b4574"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="Golang-Devfeel" title="Golang-Devfeel"></a>
8-
#### Gitter:[![Gitter](https://badges.gitter.im/devfeel/dotweb.svg)](https://gitter.im/devfeel-dotweb/wechat)
5+
## Available Examples
6+
7+
### 1. Basic Usage
8+
Simple web server setup with routing.
9+
10+
```go
11+
// See main.go
12+
```
13+
14+
### 2. JWT Authentication
15+
Demonstrates JWT token-based authentication.
16+
17+
```go
18+
// See jwt/main.go
19+
```
20+
21+
Run:
22+
```bash
23+
cd jwt
24+
go run main.go
25+
```
26+
27+
### 3. File Upload
28+
Shows how to handle file uploads.
29+
30+
```go
31+
// See file-upload/main.go
32+
```
33+
34+
Run:
35+
```bash
36+
cd file-upload
37+
go run main.go
38+
```
39+
40+
### 4. CORS
41+
Cross-Origin Resource Sharing configuration.
42+
43+
```go
44+
// See cors/main.go
45+
```
46+
47+
Run:
48+
```bash
49+
cd cors
50+
go run main.go
51+
```
52+
53+
## Running Examples
54+
55+
```bash
56+
# Run any example
57+
cd example/<name>
58+
go run main.go
59+
```
60+
61+
## More Examples
62+
63+
Visit [dotweb-example](https://github.com/devfeel/dotweb-example) for more complete examples.

example/cors/main.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/devfeel/dotweb"
7+
)
8+
9+
// CORS Example
10+
// This demonstrates how to handle Cross-Origin Resource Sharing (CORS)
11+
12+
func main() {
13+
// init DotApp
14+
app := dotweb.New()
15+
16+
// API endpoint with CORS headers
17+
app.HttpServer.GET("/api/data", func(ctx dotweb.Context) error {
18+
// Set CORS headers
19+
ctx.Response().Header().Set("Access-Control-Allow-Origin", "*")
20+
ctx.Response().Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
21+
ctx.Response().Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
22+
23+
return ctx.WriteJson(map[string]interface{}{
24+
"message": "Hello from API",
25+
"data": []string{"item1", "item2", "item3"},
26+
})
27+
})
28+
29+
// POST endpoint
30+
app.HttpServer.POST("/api/data", func(ctx dotweb.Context) error {
31+
// Set CORS headers
32+
ctx.Response().Header().Set("Access-Control-Allow-Origin", "*")
33+
ctx.Response().Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
34+
ctx.Response().Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
35+
36+
return ctx.WriteJson(map[string]string{
37+
"status": "success",
38+
"message": "Data received",
39+
})
40+
})
41+
42+
fmt.Println("CORS Example server starting on :8080")
43+
fmt.Println("API endpoint: GET /api/data")
44+
fmt.Println("API endpoint: POST /api/data")
45+
fmt.Println("Test with: curl -H 'Origin: *' http://localhost:8080/api/data")
46+
err := app.StartServer(8080)
47+
fmt.Println("server error => ", err)
48+
}

example/file-upload/main.go

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"time"
7+
8+
"github.com/devfeel/dotweb"
9+
)
10+
11+
// File Upload Example
12+
// This demonstrates how to handle file uploads with dotweb
13+
14+
func main() {
15+
// init DotApp
16+
app := dotweb.New()
17+
18+
// Set upload directory
19+
uploadDir := "./uploads"
20+
if err := os.MkdirAll(uploadDir, 0755); err != nil {
21+
fmt.Println("Error creating upload dir:", err)
22+
return
23+
}
24+
25+
// Show upload form
26+
app.HttpServer.GET("/upload", func(ctx dotweb.Context) error {
27+
return ctx.WriteString(`
28+
<!DOCTYPE html>
29+
<html>
30+
<head><title>File Upload</title></head>
31+
<body>
32+
<form enctype="multipart/form-data" method="post" action="/upload">
33+
<input type="file" name="file"><br>
34+
<input type="submit" value="Upload">
35+
</form>
36+
</body>
37+
</html>
38+
`)
39+
})
40+
41+
// Handle file upload
42+
app.HttpServer.POST("/upload", func(ctx dotweb.Context) error {
43+
file, err := ctx.Request().FormFile("file")
44+
if err != nil {
45+
return ctx.WriteString("Error uploading file: " + err.Error())
46+
}
47+
48+
// Generate unique filename
49+
filename := fmt.Sprintf("file_%d%s", time.Now().Unix(), file.GetFileExt())
50+
serverPath := fmt.Sprintf("%s/%s", uploadDir, filename)
51+
52+
// Save file
53+
size, err := file.SaveFile(serverPath)
54+
if err != nil {
55+
return ctx.WriteString("Error saving file: " + err.Error())
56+
}
57+
58+
return ctx.WriteJson(map[string]interface{}{
59+
"message": "File uploaded successfully",
60+
"filename": filename,
61+
"size": size,
62+
"contentType": file.Header.Header.Get("Content-Type"),
63+
})
64+
})
65+
66+
// List uploaded files
67+
app.HttpServer.GET("/files", func(ctx dotweb.Context) error {
68+
files, err := os.ReadDir(uploadDir)
69+
if err != nil {
70+
return ctx.WriteString("Error reading files")
71+
}
72+
73+
var fileList []string
74+
for _, f := range files {
75+
if !f.IsDir() {
76+
fileList = append(fileList, f.Name())
77+
}
78+
}
79+
return ctx.WriteJson(fileList)
80+
})
81+
82+
fmt.Println("File Upload Example server starting on :8080")
83+
fmt.Println("Upload form: GET /upload")
84+
fmt.Println("Upload handler: POST /upload")
85+
fmt.Println("List files: GET /files")
86+
err := app.StartServer(8080)
87+
fmt.Println("server error => ", err)
88+
}

example/jwt/main.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"time"
6+
7+
"github.com/devfeel/dotweb"
8+
)
9+
10+
// JWT Middleware Example
11+
// This demonstrates how to use JWT authentication with dotweb
12+
13+
func main() {
14+
// init DotApp
15+
app := dotweb.New()
16+
17+
// Set route
18+
app.HttpServer.GET("/api/public", func(ctx dotweb.Context) error {
19+
return ctx.WriteString("This is a public endpoint")
20+
})
21+
22+
// Protected route - in real app, add JWT validation middleware
23+
app.HttpServer.GET("/api/private", func(ctx dotweb.Context) error {
24+
return ctx.WriteJson(map[string]interface{}{
25+
"message": "This is a private endpoint",
26+
"user": "admin",
27+
})
28+
})
29+
30+
// Login endpoint - returns simple token (use proper JWT in production)
31+
app.HttpServer.POST("/api/login", func(ctx dotweb.Context) error {
32+
// In production, validate credentials from database
33+
username := ctx.PostFormValue("username")
34+
password := ctx.PostFormValue("password")
35+
36+
// Simple validation (replace with real auth)
37+
if username == "admin" && password == "password" {
38+
// Generate simple token (use proper JWT library in production)
39+
token := generateSimpleToken(username)
40+
return ctx.WriteJson(map[string]string{
41+
"token": token,
42+
})
43+
}
44+
return ctx.WriteString("Invalid credentials")
45+
})
46+
47+
fmt.Println("JWT Example server starting on :8080")
48+
fmt.Println("Public endpoint: GET /api/public")
49+
fmt.Println("Private endpoint: GET /api/private")
50+
fmt.Println("Login: POST /api/login?username=admin&password=password")
51+
err := app.StartServer(8080)
52+
fmt.Println("server error => ", err)
53+
}
54+
55+
// generateSimpleToken creates a simple token (for demonstration only)
56+
// In production, use: github.com/golang-jwt/jwt
57+
func generateSimpleToken(username string) string {
58+
exp := time.Now().Add(time.Hour).Unix()
59+
return fmt.Sprintf("%s.%d.%s", username, exp, "signature")
60+
}

0 commit comments

Comments
 (0)