Skip to content

Commit

Permalink
/api/fluxState endpoint; axios client to call it
Browse files Browse the repository at this point in the history
  • Loading branch information
laszlocph committed Oct 20, 2023
1 parent fed62a1 commit e670699
Show file tree
Hide file tree
Showing 10 changed files with 205 additions and 6 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
.env
kubeconfig.yaml
build
cmd/capacitor/web

# dependencies
web/node_modules
Expand Down
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@ build:

test:
go test -timeout 60s $(shell go list ./...)

build-ui:
(cd web; npm install; npm run build)
rm -rf cmd/capacitor/web/build
mkdir -p cmd/capacitor/web/build
@cp -r web/build/* cmd/capacitor/web/build
73 changes: 69 additions & 4 deletions cmd/capacitor/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@ import (
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"

kustomizationv1 "github.com/fluxcd/kustomize-controller/api/v1"
sourcev1 "github.com/fluxcd/source-controller/api/v1"
"github.com/gimlet-io/capacitor/pkg/controllers"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -56,6 +60,9 @@ func main() {
Resource: "gitrepositories",
}

stopCh := make(chan struct{})
defer close(stopCh)

ctrl := controllers.NewDynamicController(
"gitrepositories.source.toolkit.fluxcd.io",
dynamicClient,
Expand All @@ -75,12 +82,16 @@ func main() {
}
return nil
})

stopCh := make(chan struct{})
defer close(stopCh)

go ctrl.Run(1, stopCh)

r := setupRouter(dynamicClient)
go func() {
err = http.ListenAndServe(":9000", r)
if err != nil {
panic(err)
}
}()

signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)

Expand Down Expand Up @@ -153,3 +164,57 @@ func getFluxState(dc *dynamic.DynamicClient) (*fluxState, error) {

return fluxState, nil
}

func setupRouter(
dynamicClient *dynamic.DynamicClient,
) *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.WithValue("dynamicClient", dynamicClient))

r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
r.Get("/api/fluxState", fluxStateHandler)

filesDir := http.Dir("./web/build")
fileServer(r, "/", filesDir)

return r
}

// static files from a http.FileSystem
func fileServer(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
//TODO: serve all React routes https://github.com/go-chi/chi/issues/403
panic("FileServer does not permit any URL parameters.")
}

if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", http.StatusMovedPermanently).ServeHTTP)
path += "/"
}
path += "*"

r.Get(path, func(w http.ResponseWriter, r *http.Request) {
ctx := chi.RouteContext(r.Context())
pathPrefix := strings.TrimSuffix(ctx.RoutePattern(), "/*")
fs := http.StripPrefix(pathPrefix, http.FileServer(root))
fs.ServeHTTP(w, r)
})
}

func fluxStateHandler(w http.ResponseWriter, r *http.Request) {
dynamicClient, _ := r.Context().Value("dynamicClient").(*dynamic.DynamicClient)

fluxState, err := getFluxState(dynamicClient)
if err != nil {
panic(err.Error())
}
fluxStateBytes, err := json.Marshal(fluxState)
if err != nil {
panic(err.Error())
}

w.WriteHeader(http.StatusOK)
w.Write(fluxStateBytes)
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fluxcd/kustomize-controller/api v1.1.1
github.com/fluxcd/source-controller/api v1.1.2
github.com/go-chi/chi v1.5.5
github.com/go-logr/logr v1.2.4 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ github.com/fluxcd/pkg/apis/meta v1.1.2 h1:Unjo7hxadtB2dvGpeFqZZUdsjpRA08YYSBb7dF
github.com/fluxcd/pkg/apis/meta v1.1.2/go.mod h1:BHQyRHCskGMEDf6kDGbgQ+cyiNpUHbLsCOsaMYM2maI=
github.com/fluxcd/source-controller/api v1.1.2 h1:FfKDKVWnopo+Q2pOAxgHEjrtr4MP41L8aapR4mqBhBk=
github.com/fluxcd/source-controller/api v1.1.2/go.mod h1:ZLkaUd1KQIjtLPCvO63Ni5zpnSTVBAkeRgFBzMItbDQ=
github.com/go-chi/chi v1.5.5 h1:vOB/HbEMt9QqBqErz07QehcOKHaWFtuj87tTDVz2qXE=
github.com/go-chi/chi v1.5.5/go.mod h1:C9JqLr3tIYjDOZpzn+BCuxY8z8vmca43EeMgyZt7irw=
github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ=
github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
Expand Down
59 changes: 58 additions & 1 deletion web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.5.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
Expand Down Expand Up @@ -34,5 +35,6 @@
"last 1 firefox version",
"last 1 safari version"
]
}
},
"proxy": "http://127.0.0.1:9000"
}
11 changes: 11 additions & 0 deletions web/src/App.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import logo from './logo.svg';
import './App.css';
import APIBackend from "./apiBackend";
import CapacitorClient from "./client";

function App() {
const capacitorClient = new CapacitorClient(
(response) => {
console.log(`${response.status}: ${response.statusText} on ${response.path}`);
}
);

return (
<>
<APIBackend capacitorClient={capacitorClient}/>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
Expand All @@ -19,6 +29,7 @@ function App() {
</a>
</header>
</div>
</>
);
}

Expand Down
13 changes: 13 additions & 0 deletions web/src/apiBackend.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Component } from 'react';

export default class APIBackend extends Component {

componentDidMount() {
this.props.capacitorClient.getFluxState()
.then(data => console.log(data), () => {/* Generic error handler deals with it */ });
}

render() {
return null;
}
}
41 changes: 41 additions & 0 deletions web/src/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import axios from 'axios';

export default class CapacitorClient {
constructor(onError) {
this.onError = onError
}

URL = () => this.url;

getFluxState = () => this.get('/api/fluxState');

get = async (path) => {
try {
const { data } = await axios.get(path, {
credentials: 'include'
});
return data;
} catch (error) {
this.onError(error.response);
throw error.response;
}
}

post = async (path, body) => {
try {
const { data } = await axios
.post(path, body, {
credentials: 'include',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
});
return data;
} catch (error) {
this.onError(error.response);
throw error.response;
}
}

}

0 comments on commit e670699

Please sign in to comment.