Skip to content

Commit

Permalink
example and doc update
Browse files Browse the repository at this point in the history
  • Loading branch information
rbroggi committed Jul 21, 2024
1 parent bb2169d commit 23ad76d
Show file tree
Hide file tree
Showing 6 changed files with 282 additions and 110 deletions.
8 changes: 7 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,10 @@ dependencies_up: dependencies_down
.PHONY: tests
## tests: runs tests against a locally running mongo container
tests:
go test -v ./...
go test -v ./...

.PHONY: example
## example: runs an http-server locally
example:
go build -o bin/server streamingconfig/example/server
./bin/server
35 changes: 33 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fields.

## Usage

checkout the [example](./example/main.go).
checkout the [example](./example/server/main.go).

1. Define a configuration with `json` field tags (and optionally with `default` field tags):
2. Make sure that your configuration type implements the `streamingconfig.Config` interface:
Expand All @@ -36,4 +36,35 @@ checkout the [example](./example/main.go).
```shell
make dependencies_up
make tests
```
```

### Run example server

```shell
make dependencies_up
make example
```

Optionally, you can also start a second server to check that the changes happening in one server will be reflected in the other:

```shell
HTTP_PORT=8081 make example
```

#### Getting latest configuration request
```shell
curl -X GET --location "http://localhost:8080/configs/latest"
```
#### Changing latest configuration request
```shell
curl -X PUT --location "http://localhost:8080/configs/latest" \
-H "user-id: mark" \
-d '{
"name": "betty",
"age": 35
}'
```
#### Listing multiple versions
```shell
curl -X GET --location "http://localhost:8080/configs?fromVersion=0&toVersion=21"
```
107 changes: 0 additions & 107 deletions example/main.go

This file was deleted.

15 changes: 15 additions & 0 deletions example/server/configs.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
### GET latest config
GET http://localhost:8080/configs/latest


### Modify latest config
PUT http://localhost:8080/configs/latest
user-id: mark

{
"name": "stark",
"age": 35
}

### List config versions
GET http://localhost:8080/configs?fromVersion=0&toVersion=21
109 changes: 109 additions & 0 deletions example/server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package main

import (
"context"
"errors"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"

config "streamingconfig"

"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

type conf struct {
Name string `json:"name" default:"john"`
Age int `json:"age"`
}

func (c *conf) Update(new config.Config) error {
newCfg, ok := new.(*conf)
if !ok {
return errors.New("wrong configuration")
}
c.Name = newCfg.Name
c.Age = newCfg.Age
return nil
}

func main() {
port := os.Getenv("HTTP_PORT")
if port == "" {
port = "8080"
}
runnableCtx, cancelRunnables := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancelRunnables()
repo, done := initRepo(runnableCtx)
s := &server{repo: repo, lgr: slog.Default()}
mux := http.NewServeMux()
mux.HandleFunc("GET /configs/latest", s.latestConfigHandler)
mux.HandleFunc("PUT /configs/latest", s.putConfigHandler)
mux.HandleFunc("GET /configs", s.listConfigsHandler)
// Create a new server
srv := &http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: mux,
}
// Start the server in a goroutine
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
fmt.Printf("Server listening on port %s\n", port)
// until shutdown signal is sent
<-runnableCtx.Done()
// Graceful shutdown
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer func() {
cancel()
}()

if err := srv.Shutdown(ctx); err != nil {
log.Println("Error during shutdown:", err)
}
log.Println("Server stopped")
<-done
}

func initRepo(ctx context.Context) (*config.WatchedRepo[*conf], <-chan struct{}) {
lgr := slog.Default()
db := getDb()
repo, err := config.NewWatchedRepo[*conf](
config.Args{
Logger: lgr,
DB: db,
})
if err != nil {
log.Fatal(err)
}
done, err := repo.Start(ctx)
if err != nil {
log.Fatal(err)
}
return repo, done
}

func getDb() *mongo.Database {
ctx, cnl := context.WithTimeout(context.Background(), 5*time.Second)
defer cnl()
// use test name as db name to parallel tests.
opts := options.Client()
opts.ApplyURI("mongodb://localhost:27017/?connect=direct")
client, err := mongo.Connect(ctx, opts)
if err != nil {
panic(fmt.Errorf("run `make dependencies_up` before, error: %w", err))
}
err = client.Ping(ctx, nil)
if err != nil {
panic(fmt.Errorf("error %v\nrun `make dependencies_up` before running main\n", err))
}
return client.Database("test")
}
Loading

0 comments on commit 23ad76d

Please sign in to comment.