Skip to content

Commit 0bd4690

Browse files
committed
Merge branch 'development' of github.com:gofr-dev/gofr into development
2 parents b95c475 + fd446cc commit 0bd4690

File tree

5 files changed

+241
-1
lines changed

5 files changed

+241
-1
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Configurations
2+
3+
GoFr reads configuration via environment variables. It provides an easy way to manage this. Application code is decoupled from how configuration is managed as per the [12-factor](https://12factor.net/config).
4+
5+
Configs in GoFr can be used to initialise datasources, tracing. In doing so it abstract the logic and gives an easy interface to setup different things.
6+
7+
To set configs create a `configs` folder in the project's root and add `.env` file.
8+
9+
By default, GoFr starts HTTP server at port 8000, in order to change that we can add the config `HTTP_PORT`
10+
Similarly to Set the app-name you can add `APP_NAME`. For example:
11+
12+
```dotenv
13+
# configs/.env
14+
15+
APP_NAME=test-service
16+
HTTP_PORT=9000
17+
```
18+
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
2+
# Connecting MySQL
3+
4+
Just like any other datasource gofr also supports connection to MySQL database based on configuration variables. It automatically manages the connection pool, connection retry etc.
5+
6+
## Setup
7+
8+
You can run the mysql server and create a database locally using the following docker command:
9+
10+
```bash
11+
docker run --name gofr-mysql -e MYSQL_ROOT_PASSWORD=root123 -e MYSQL_DATABASE=test_db -p 3306:3306 -d mysql:8.0.30
12+
```
13+
14+
Access `test_db` database and create table customer with columns `id` and `name`
15+
16+
```bash
17+
docker exec -it gofr-mysql mysql -uroot -proot123 test_db -e "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL);"
18+
```
19+
20+
Now the database with table is ready, we can connect our server to MySQL
21+
22+
## Configuration & Usage
23+
24+
After adding MySQL configs `.env` will be updated to the following.
25+
26+
```bash
27+
# configs/.env
28+
APP_NAME=test-service
29+
HTTP_PORT=9000
30+
31+
REDIS_HOST=localhost
32+
REDIS_PORT=6379
33+
34+
DB_HOST=localhost
35+
DB_USER=root
36+
DB_PASSWORD=root123
37+
DB_NAME=test_db
38+
DB_PORT=3306
39+
```
40+
41+
Now in the following example let's store customer data using **POST** `/customer` and then use **GET** `/customer` to retrieve the same.
42+
We will be storing the customer data with `id` and `name`.
43+
44+
After adding code to add and retrieve data from MySQL datastore `main.go` will be updated to the following.
45+
46+
```go
47+
package main
48+
49+
import "gofr.dev/pkg/gofr"
50+
51+
type Customer struct {
52+
ID int `json:"id"`
53+
Name string `json:"name"`
54+
}
55+
56+
func main() {
57+
// initialise gofr object
58+
app := gofr.New()
59+
60+
app.GET("/greet", func(ctx *gofr.Context) (interface{}, error) {
61+
// Get the value using the redis instance
62+
value, err := ctx.Redis.Get(ctx.Context, "greeting").Result()
63+
64+
return value, err
65+
})
66+
67+
app.POST("/customer/{name}", func(ctx *gofr.Context) (interface{}, error) {
68+
name := ctx.PathParam("name")
69+
70+
// Inserting a customer row in database using SQL
71+
_, err := ctx.DB.ExecContext(ctx, "INSERT INTO customers (name) VALUES (?)", name)
72+
73+
return nil, err
74+
})
75+
76+
app.GET("/customer", func(ctx *gofr.Context) (interface{}, error) {
77+
var customers []Customer
78+
79+
// Getting the customer from the database using SQL
80+
rows, err := ctx.DB.QueryContext(ctx, "SELECT * FROM customers")
81+
if err != nil {
82+
return nil, err
83+
}
84+
85+
for rows.Next() {
86+
var customer Customer
87+
if err := rows.Scan(&customer.ID, &customer.Name); err != nil {
88+
return nil, err
89+
}
90+
91+
customers = append(customers, customer)
92+
}
93+
94+
// return the customer
95+
return customers, nil
96+
})
97+
98+
// Starts the server, it will listen on the default port 8000.
99+
// it can be over-ridden through configs
100+
app.Run()
101+
}
102+
```
103+
104+
To update the database with the customer data access use through this curl command through terminal
105+
106+
```bash
107+
# here abc and xyz after /customer are the path parameters
108+
curl --location --request POST 'http://localhost:9000/customer/abc'
109+
110+
curl --location --request POST 'http://localhost:9000/customer/xyz'
111+
```
112+
113+
You will see the following output if database is successfully updated
114+
115+
```json
116+
{}
117+
```
118+
119+
Now when we access the [http://localhost:9000/customer](http://localhost:9000/customer) we should see the following output
120+
121+
```json
122+
{
123+
"data": [
124+
{
125+
"id": 1,
126+
"name": "abc"
127+
},
128+
{
129+
"id": 2,
130+
"name": "xyz"
131+
}
132+
]
133+
}
134+
```
File renamed without changes.
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
## Prerequisite
2+
3+
- Install or update [Go](https://go.dev/dl/).
4+
5+
To check the version use the following command `go version`.
6+
7+
- Prior familiarity with Golang syntax is essential. [Golang Tour](https://tour.golang.org/) is highly recommended as it has an excellent guided tour.
8+
9+
## Write your first GoFr API
10+
11+
Let's start by initializing the go module by using the following command.
12+
13+
```bash
14+
go mod init github.com/example
15+
```
16+
17+
To know more about go modules refer [here](https://go.dev/ref/mod)
18+
19+
Add [gofr](https://github.com/gofr-dev/gofr) package to the project using the following command
20+
21+
```bash
22+
go get gofr.dev
23+
```
24+
25+
Now add the following code to _main.go_ file
26+
27+
```go
28+
package main
29+
30+
import "gofr.dev/pkg/gofr"
31+
32+
func main() {
33+
// initialise gofr object
34+
app := gofr.New()
35+
36+
// register route greet
37+
app.GET("/greet", func(ctx *gofr.Context) (interface{}, error) {
38+
39+
return "Hello World!", nil
40+
})
41+
42+
// Runs the server, it will listen on the default port 8000.
43+
// it can be over-ridden through configs
44+
a.Run()
45+
}
46+
```
47+
48+
Before running the server run the following command to go needs to download and sync the required modules.
49+
50+
`go mod tidy`
51+
52+
To run the server, use the command
53+
54+
`go run main.go`
55+
56+
This would start the server at 8000 port, you can access [http://localhost:8000/greet](http://localhost:8000/greet) from your browser, you would be able to see the output as following with _Status Code 200_ as per REST Standard
57+
58+
```json
59+
{ "data": "Hello World!" }
60+
```
61+
62+
## Understanding the example
63+
64+
The `hello-world` server involves three essential steps:
65+
66+
1. **Creating GoFr Server:**
67+
68+
When `gofr.New()` is called, it initializes the framework and handles various setup tasks like configuring database connection pools, initialising logger, setting CORS headers etc based on the configs.
69+
70+
_This single line is a standard part of all gofr-based servers._
71+
72+
2. **Attaching a Handler to a Path:**
73+
74+
In this step, we instruct the server to associate an HTTP request with a specific handler function. This is achieved through `app.GET("/greet", HandlerFunction)`, where _GET /hello_ maps to HandlerFunction. Likewise, `app.POST("/todo", ToDoCreationHandler)` links a _POST_ request to the /todo endpoint with _ToDoCreationHandler_.
75+
76+
**Good To Know**
77+
78+
In Go, functions are first-class citizens, allowing easy handler definition and reference.
79+
Handler functions should follow the `func(ctx *gofr.Context) (interface{}, error)` signature.
80+
They take a context as input, returning two values: the response data and an error (set to `nil` on success).
81+
82+
In GoFr `ctx *gofr.Context` serves as a wrapper for requests, responses, and dependencies, providing various functionalities.
83+
84+
For more details about context, refer [here](/docs/v1/references/context).
85+
86+
3. **Starting the server**
87+
88+
When `app.Run()` is called, it configures ,initiates and runs the HTTP server, middlewares based on provided configs. It manages essential features such as routes for health checks, swagger UI etc. It starts the server on the default port 8000.

examples/http-server/configs/.env

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,4 @@ DB_NAME=test
1111
DB_PORT=2001
1212

1313
TRACER_HOST=localhost
14-
TRACER_PORT=2005
14+
TRACER_PORT=2005

0 commit comments

Comments
 (0)