Skip to content

Commit

Permalink
minimize the introductory frame
Browse files Browse the repository at this point in the history
  • Loading branch information
pitabwire committed Feb 7, 2025
1 parent 4121c76 commit 7861def
Showing 1 changed file with 9 additions and 155 deletions.
164 changes: 9 additions & 155 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,169 +47,23 @@ go get -u github.com/pitabwire/frame

### Quick Start Example

Let's create a simple user management API that demonstrates Frame's key features:
- HTTP Server setup
- Database integration
- Authentication
- Request handling
The simplest possible Frame server in 5 lines:

```go
package main

import (
"context"
"encoding/json"
"github.com/gorilla/mux"
"github.com/pitabwire/frame"
"log"
"net/http"
"time"
)

// User represents our user model
type User struct {
ID uint `json:"id" gorm:"primarykey"`
Name string `json:"name"`
Email string `json:"email" gorm:"uniqueIndex"`
CreatedAt time.Time `json:"created_at"`
}

// UserHandler handles user-related HTTP requests
type UserHandler struct {
service *frame.Service
}

// CreateUser handles user creation
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
var user User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

// Get database from frame
db := frame.GetDB(r.Context())
if err := db.Create(&user).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}

// GetUser handles fetching a user
func (h *UserHandler) GetUser(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]

var user User
db := frame.GetDB(r.Context())
if err := db.First(&user, id).Error; err != nil {
http.Error(w, "User not found", http.StatusNotFound)
return
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}

import ("github.com/pitabwire/frame"; "net/http"; "context")
func main() {
ctx := context.Background()

// Setup database
dbURL := "postgres://user:password@localhost:5432/myapp?sslmode=disable"
dbOption := frame.Datastore(ctx, dbURL, false)

// Create router and handler
router := mux.NewRouter()
handler := &UserHandler{}

// Setup routes
api := router.PathPrefix("/api/v1").Subrouter()
api.HandleFunc("/users", handler.CreateUser).Methods("POST")
api.HandleFunc("/users/{id}", handler.GetUser).Methods("GET")

// Add authentication middleware
authConfig := frame.AuthConfig{
JWTSecret: []byte("your-secret-key"),
TokenExpiration: 24 * time.Hour,
}
authMiddleware := frame.NewAuthMiddleware(authConfig)
api.Use(authMiddleware.Handler)

// Create HTTP server
server := frame.HttpHandler(router)

// Create and run service
service := frame.NewService("user-service",
server, // HTTP server
dbOption, // Database
)

// Auto-migrate database
db := frame.GetDB(ctx)
if err := db.AutoMigrate(&User{}); err != nil {
log.Fatal("Failed to migrate database:", err)
}

// Start the service
if err := service.Run(ctx, ":8080"); err != nil {
log.Fatal("Failed to start service:", err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello!")) })
frame.NewService("hello-service", frame.HttpHandler(http.DefaultServeMux)).Run(context.Background(), ":8080")
}
```

This example demonstrates:

1. **Service Setup**
- Creating an HTTP server with routing
- Configuring database connection
- Setting up authentication

2. **Database Integration**
- Model definition with GORM tags
- Auto-migration
- Basic CRUD operations

3. **Authentication**
- JWT-based authentication
- Protected routes
- Middleware integration

4. **Request Handling**
- Route definition
- Request parsing
- Response formatting

To use this example:

1. Install Frame:
```bash
go get -u github.com/pitabwire/frame
```

2. Set up PostgreSQL database

3. Run the application:
```bash
go run main.go
```

4. Test the API:
```bash
# Create a user
curl -X POST -H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"[email protected]"}' \
http://localhost:8080/api/v1/users

# Get a user
curl -H "Authorization: Bearer <token>" \
http://localhost:8080/api/v1/users/1
```
Try it:
```bash
curl http://localhost:8080/
```

For more detailed documentation on each component, check the sections below.
For more comprehensive examples and detailed documentation of Frame's features, check the sections below.

### Contribution

Expand Down

0 comments on commit 7861def

Please sign in to comment.