Skip to content

Commit

Permalink
Albedo as go libary
Browse files Browse the repository at this point in the history
  • Loading branch information
M4tteoP committed Sep 22, 2024
1 parent b13032f commit 1f3c10f
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 7 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,36 @@ Flags:
-p, --port int port to listen on (default 8080)
```

## Usage as a library
`github.com/coreruleset/albedo/server` package provides a handler that can be used for testing purposes.
Usage example:
```go
package albedo_test

import (
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/coreruleset/albedo/server"
"github.com/stretchr/testify/require"
)

func TestAlbedo(t *testing.T) {
testServer := httptest.NewServer(server.Handler())
defer testServer.Close()

client := http.Client{
Timeout: time.Duration(1 * time.Second),
}

_, err := client.Get(testServer.URL)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
}
```

## Endpoints

```yaml
Expand Down
24 changes: 24 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package main

import (
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/coreruleset/albedo/server"
"github.com/stretchr/testify/require"
)

func TestAlbedoLibrary(t *testing.T) {
testServer := httptest.NewServer(server.Handler())
defer testServer.Close()

client := http.Client{
Timeout: time.Duration(1 * time.Second),
}

resp, err := client.Get(testServer.URL)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
}
21 changes: 14 additions & 7 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,26 @@ const capabilitiesDescription = `

func Start(binding string, port int) *http.Server {
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", binding, port),
Addr: fmt.Sprintf("%s:%d", binding, port),
Handler: Handler(),
}

http.HandleFunc("/", handleDefault)
http.HandleFunc("/capabilities", handleCapabilities)
http.HandleFunc("/capabilities/", handleCapabilities)
http.HandleFunc("POST /reflect", handleReflect)
http.HandleFunc("POST /reflect/", handleReflect)

log.Fatal(server.ListenAndServe())
return server
}

func Handler() http.Handler {
mux := http.NewServeMux()

mux.HandleFunc("/", handleDefault)
mux.HandleFunc("/capabilities", handleCapabilities)
mux.HandleFunc("/capabilities/", handleCapabilities)
mux.HandleFunc("POST /reflect", handleReflect)
mux.HandleFunc("POST /reflect/", handleReflect)

return mux
}

// Respond with empty 200 for all requests by default
func handleDefault(w http.ResponseWriter, r *http.Request) {
log.Printf("Received default request to %s", r.URL)
Expand Down

0 comments on commit 1f3c10f

Please sign in to comment.