Skip to content

Commit

Permalink
fixing the formatting of some files and adding examples to the readme
Browse files Browse the repository at this point in the history
  • Loading branch information
BrunoCiccarino committed Oct 23, 2024
1 parent cbed795 commit bf9ddbe
Show file tree
Hide file tree
Showing 5 changed files with 149 additions and 109 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env
48 changes: 37 additions & 11 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
## Changelog

### express-go v0.1 Release Notes
🚀 express-go v0.1 - The First Release!
### GopherLight v0.1 Release Notes
🚀 GopherLight v0.1 - The First Release!
We are excited to announce the first version of express-go, a micro-framework inspired by Express.js, now for the Go universe! This initial release brings the simplicity and flexibility you already love from Express, but with the robust performance and reliability of Go.

🎯 Main Features
* Simple Routing: Set up routes quickly and easily. Just define the URL and a handler, and that's it!

```go
app.Route("/hello", func(r *req.Request, w *req.Response) {
app.Route("GET", "/hello", func(r *req.Request, w *req.Response) {
w.Send("Hello, World!")
})
```
Expand All @@ -35,14 +35,40 @@ This is only version 0.1, so there's still a lot to go! We are working on:
📝 Contributions
This is an early version, and we are open to suggestions, improvements and contributions from the community. Feel free to explore the code, open issues, or submit PRs to make express-go even better!

## [0.2] - 2024-10-21
### GopherLight v0.2 Release Notes
🚀 GopherLight v0.2 - Enhanced Routing and Middleware Support!

### Additions
- **Support for multiple HTTP methods**: The framework now allows the routing of requests to HTTP methods such as GET, POST, PUT, DELETE and others, providing greater flexibility in defining routes.
We are excited to announce the second version of GopherLight, bringing more flexibility and features to our lightweight Go framework. With this update, you’ll experience a more powerful routing system and the addition of convenient middleware to streamline your development process.

### Improvements
- **HTTP method validation**: Implementation of validation to ensure that routes respond only to appropriate methods, increasing security and clarity when handling requests.
### 🎯 Additions

### Changes
- **Route function refactoring**: The function has been adjusted to accept and manage different HTTP methods efficiently.
- **Documentation update**: The documentation has been revised and updated to reflect the new capabilities of the framework, including examples of use of the different HTTP methods.
* Support for Multiple HTTP Methods: GopherLight now allows routing for various HTTP methods such as GET, POST, PUT, DELETE, and more. You can define routes for each specific method, increasing flexibility in handling requests.

```go
app.Route("POST", "/submit", func(r *req.Request, w *req.Response) {
w.Send("Data received!")
})
```

* Logging Middleware: Automatically log the start and completion time of each request, making it easier to debug and monitor the behavior of your app.

* Timeout Middleware: Prevent long-running requests from blocking your application with the newly introduced timeout middleware. You can set time limits for your request handling.

```go
app.Use(middleware.LoggingMiddleware)
app.Use(middleware.TimeoutMiddleware(2 * time.Second))
```

### 🛠️ Improvements

HTTP Method Validation: We've implemented stricter validation for HTTP methods. Now, your routes will only respond to the defined methods, ensuring security and better management of requests.
### 🔄 Changes

Route Function Refactoring: The route function has been restructured to handle multiple HTTP methods efficiently, improving performance and code clarity.
Documentation Update: The documentation has been updated to reflect all the new features, including detailed examples of how to utilize multiple HTTP methods and middleware in your application.
### 🚀 What’s Next?

Enhanced error handling and better integration with third-party services.
Middleware for authentication and CSRF protection.

* 📝 Contributions GopherLight continues to grow with your support! We welcome contributions, suggestions, and improvements from the community. Feel free to explore, submit issues, or open PRs to make the framework even better.
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ So, if you’re looking for a friendly and efficient way to build web apps in Go
- [x] router
- [x] http requests
- [x] manipulation of the methods (get, post, pu, delete ...)
- [ ] middleware (authentication, timeout, anti csrf, etc...)
- [ ] middleware (authentication, ~~timeout~~, anti csrf, ~~logging~~, etc...)
- [ ] next func
- [ ] more detailed error logs
- [ ] More complete documentation
Expand All @@ -36,11 +36,21 @@ So, if you’re looking for a friendly and efficient way to build web apps in Go
```bash
go get github.com/BrunoCiccarino/GopherLight/router
go get github.com/BrunoCiccarino/GopherLight/req
go get github.com/BrunoCiccarino/GopherLight/middleware
```

### basic usage example

```go
package main

import (
"fmt"
"github.com/BrunoCiccarino/GopherLight/router"
"github.com/BrunoCiccarino/GopherLight/req"
)


func main() {
app := router.NewApp()

Expand All @@ -54,6 +64,13 @@ func main() {
}
```

### basic use middlewares

```go
app.Use(middleware.LoggingMiddleware)
app.Use(middleware.TimeoutMiddleware(2 * time.Second))
```

# Contribute

That said, there's a bunch of ways you can contribute to this project, like by:
Expand Down
188 changes: 93 additions & 95 deletions examples/crud/main.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@


package main

import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"

"github.com/BrunoCiccarino/GopherLight/req"
"github.com/BrunoCiccarino/GopherLight/router"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"

"github.com/BrunoCiccarino/GopherLight/req"
"github.com/BrunoCiccarino/GopherLight/router"
)

// Middleware example: Logging middleware
func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Request: %s %s\n", r.Method, r.URL.Path)
next(w, r)
}
return func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Request: %s %s\n", r.Method, r.URL.Path)
next(w, r)
}
}

type User struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}

var users = make(map[int]User)
Expand All @@ -44,17 +42,17 @@ var nextID = 1
//
// Sends a JSON response with the created user data or an error if the input is invalid.
func CreateUser(req *req.Request, res *req.Response) {
var user User
err := json.Unmarshal([]byte(req.BodyAsString()), &user)
if err != nil {
res.Status(http.StatusBadRequest).JSONError("Invalid input")
log.Println("Error decoding JSON:", err)
return
}
user.ID = nextID
nextID++
users[user.ID] = user
res.Status(http.StatusCreated).JSON(user)
var user User
err := json.Unmarshal([]byte(req.BodyAsString()), &user)
if err != nil {
res.Status(http.StatusBadRequest).JSONError("Invalid input")
log.Println("Error decoding JSON:", err)
return
}
user.ID = nextID
nextID++
users[user.ID] = user
res.Status(http.StatusCreated).JSON(user)
}

// GetUser returns a user by their ID.
Expand All @@ -64,20 +62,20 @@ func CreateUser(req *req.Request, res *req.Response) {
// req: The received request (containing the user ID).
// res: The response to be sent (containing the user or an error message).
func GetUser(req *req.Request, res *req.Response) {
idParam := req.QueryParam("id")
id, err := strconv.Atoi(idParam)
if err != nil || id <= 0 {
res.Status(http.StatusBadRequest).JSONError("Invalid user ID")
return
}

user, exists := users[id]
if !exists {
res.Status(http.StatusNotFound).JSONError("User not found")
return
}

res.JSON(user)
idParam := req.QueryParam("id")
id, err := strconv.Atoi(idParam)
if err != nil || id <= 0 {
res.Status(http.StatusBadRequest).JSONError("Invalid user ID")
return
}

user, exists := users[id]
if !exists {
res.Status(http.StatusNotFound).JSONError("User not found")
return
}

res.JSON(user)
}

// UpdateUser updates a user's data.
Expand All @@ -87,32 +85,32 @@ func GetUser(req *req.Request, res *req.Response) {
// req: The received request (containing the new data).
// res: The response to be sent (containing the updated status and user).
func UpdateUser(req *req.Request, res *req.Response) {
idParam := req.QueryParam("id")
id, err := strconv.Atoi(idParam)
if err != nil || id <= 0 {
res.Status(http.StatusBadRequest).JSONError("Invalid user ID")
return
}

var updatedUser User
err = json.Unmarshal([]byte(req.BodyAsString()), &updatedUser)
if err != nil {
res.Status(http.StatusBadRequest).JSONError("Invalid input")
log.Println("Error decoding JSON:", err)
return
}

user, exists := users[id]
if !exists {
res.Status(http.StatusNotFound).JSONError("User not found")
return
}

user.Name = updatedUser.Name
user.Age = updatedUser.Age
users[id] = user

res.JSON(user)
idParam := req.QueryParam("id")
id, err := strconv.Atoi(idParam)
if err != nil || id <= 0 {
res.Status(http.StatusBadRequest).JSONError("Invalid user ID")
return
}

var updatedUser User
err = json.Unmarshal([]byte(req.BodyAsString()), &updatedUser)
if err != nil {
res.Status(http.StatusBadRequest).JSONError("Invalid input")
log.Println("Error decoding JSON:", err)
return
}

user, exists := users[id]
if !exists {
res.Status(http.StatusNotFound).JSONError("User not found")
return
}

user.Name = updatedUser.Name
user.Age = updatedUser.Age
users[id] = user

res.JSON(user)
}

// DeleteUser removes a user by ID.
Expand All @@ -122,41 +120,41 @@ func UpdateUser(req *req.Request, res *req.Response) {
// req: The received request (containing the user ID).
// res: The response to be sent (success or error status).
func DeleteUser(req *req.Request, res *req.Response) {
idParam := req.QueryParam("id")
id, err := strconv.Atoi(idParam)
if err != nil || id <= 0 {
res.Status(http.StatusBadRequest).JSONError("Invalid user ID")
return
}

_, exists := users[id]
if !exists {
res.Status(http.StatusNotFound).JSONError("User not found")
return
}

delete(users, id)
res.JSON(map[string]string{"message": fmt.Sprintf("User %d deleted", id)})
idParam := req.QueryParam("id")
id, err := strconv.Atoi(idParam)
if err != nil || id <= 0 {
res.Status(http.StatusBadRequest).JSONError("Invalid user ID")
return
}

_, exists := users[id]
if !exists {
res.Status(http.StatusNotFound).JSONError("User not found")
return
}

delete(users, id)
res.JSON(map[string]string{"message": fmt.Sprintf("User %d deleted", id)})
}

// Define the "/hello" route handler
func HelloHandler(req *req.Request, res *req.Response) {
res.Send("Hello, World!")
res.Send("Hello, World!")
}

func main() {
app := router.NewApp()
app := router.NewApp()

// Use the logging middleware
app.Use(loggingMiddleware)
// Use the logging middleware
app.Use(loggingMiddleware)

// Register routes
app.Route("GET", "/hello", HelloHandler)
app.Route("POST", "/users/create", CreateUser)
app.Route("GET", "/users/get", GetUser)
app.Route("PUT", "/users/update", UpdateUser)
app.Route("DELETE", "/users/delete", DeleteUser)
// Register routes
app.Route("GET", "/hello", HelloHandler)
app.Route("POST", "/users/create", CreateUser)
app.Route("GET", "/users/get", GetUser)
app.Route("PUT", "/users/update", UpdateUser)
app.Route("DELETE", "/users/delete", DeleteUser)

fmt.Println("Server listening on port 3333")
app.Listen(":3333")
fmt.Println("Server listening on port 3333")
app.Listen(":3333")
}
2 changes: 0 additions & 2 deletions req/response.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// File: req/response.go

package req

import (
Expand Down

0 comments on commit bf9ddbe

Please sign in to comment.