From 783683446157ad2ae103851200042197d2c04f09 Mon Sep 17 00:00:00 2001 From: brittonhayes Date: Thu, 27 Jul 2023 17:21:26 -0700 Subject: [PATCH 1/6] feat: large renaming --- .env | 8 ++--- .github/workflows/ci.yaml | 2 +- .github/workflows/release.yml | 2 +- Dockerfile | 8 ++--- Procfile | 2 +- README.md | 22 ++++++------- Taskfile.yml | 2 +- warhammer.go => aos.go | 10 +++--- api/openapi.yaml | 6 ++-- cmd/{warhammerd => aos}/main.go | 40 ++++++++++++------------ config/prometheus-config.yaml | 4 +-- docker-compose.yml | 26 +++++++-------- embed.go | 2 +- go.mod | 2 +- railway.toml | 2 +- service/allegiance.go | 8 ++--- service/alliance.go | 8 ++--- service/army.go | 8 ++--- service/city.go | 6 ++-- service/doc.go | 8 ++--- service/healthz.go | 4 +-- service/service.go | 14 ++++----- service/strategy.go | 8 ++--- service/unit.go | 8 ++--- service/warscroll.go | 6 ++-- sqlite/allegiance.go | 8 ++--- sqlite/alliance.go | 6 ++-- sqlite/army.go | 8 ++--- sqlite/city.go | 8 ++--- sqlite/migrations/20230712031006_init.go | 2 +- sqlite/repository.go | 30 +++++++++--------- sqlite/strategy.go | 6 ++-- sqlite/unit.go | 10 +++--- sqlite/warscroll.go | 8 ++--- 34 files changed, 151 insertions(+), 151 deletions(-) rename warhammer.go => aos.go (86%) rename cmd/{warhammerd => aos}/main.go (86%) diff --git a/.env b/.env index c80812f..ee6fab9 100644 --- a/.env +++ b/.env @@ -2,14 +2,14 @@ # Images IMAGE_VERSION=1.0.0 -IMAGE_NAME=ghcr.io/brittonhayes/warhammer +IMAGE_NAME=ghcr.io/brittonhayes/aos # Platform ENV_PLATFORM=local # Service -WARHAMMER_SERVICE_NAME=warhammerd -WARHAMMER_SERVICE_PORT=8080 +SERVICE_NAME=aos +SERVICE_PORT=8080 # OpenTelemetry Collector OTEL_COLLECTOR_HOST=otel_collector @@ -19,7 +19,7 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://${OTEL_COLLECTOR_HOST}:${OTEL_COLLECTOR_PORT_ PUBLIC_OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:8080/oltp-http/v1/traces # OpenTelemetry Resource Definitions -OTEL_RESOURCE_ATTRIBUTES="service.namespace=warhammerd" +OTEL_RESOURCE_ATTRIBUTES="service.namespace=aos" # Metrics Temporality OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=cumulative diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index a581aee..516ba8b 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -19,7 +19,7 @@ jobs: go-version: ${{ matrix.go-version }} - name: Build - run: go build -o bin/warhammerd ./cmd/warhammerd + run: go build -o bin/aos ./cmd/aos - name: Test run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7f54612..edb9350 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,7 +7,7 @@ on: env: REGISTRY: ghcr.io - IMAGE_NAME: ${{ github.repository }} + IMAGE_NAME: brittonhayes/aos jobs: build-and-push-image: diff --git a/Dockerfile b/Dockerfile index bee89aa..dda4806 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,17 +9,17 @@ COPY go.mod ./ RUN go mod download COPY . /src/ -RUN CGO_ENABLED=0 go build -o /bin/warhammerd cmd/warhammerd/main.go +RUN CGO_ENABLED=0 go build -o /bin/aos cmd/aos/main.go # STAGE 2 FROM gcr.io/distroless/static-debian11:nonroot LABEL maintainer="brittonhayes" -COPY --from=builder --chown=nonroot:nonroot /bin/warhammerd /bin/warhammerd +COPY --from=builder --chown=nonroot:nonroot /bin/aos /bin/aos EXPOSE 8080 -ENTRYPOINT [ "/bin/warhammerd" ] +ENTRYPOINT [ "/bin/aos" ] -CMD ["/bin/warhammerd"] \ No newline at end of file +CMD ["/bin/aos"] \ No newline at end of file diff --git a/Procfile b/Procfile index 9748291..019cb10 100644 --- a/Procfile +++ b/Procfile @@ -1 +1 @@ -process: /bin/warhammerd \ No newline at end of file +process: /bin/aos \ No newline at end of file diff --git a/README.md b/README.md index 93c9c93..b505e78 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -# Warhammer +# AoS -[![Go Reference](https://pkg.go.dev/badge/github.com/brittonhayes/warhammer.svg)](https://pkg.go.dev/github.com/brittonhayes/warhammer) -[![Go Report Card](https://goreportcard.com/badge/github.com/brittonhayes/warhammer)](https://goreportcard.com/report/github.com/brittonhayes/warhammer) +[![Go Reference](https://pkg.go.dev/badge/github.com/brittonhayes/aos.svg)](https://pkg.go.dev/github.com/brittonhayes/aos) +[![Go Report Card](https://goreportcard.com/badge/github.com/brittonhayes/aos)](https://goreportcard.com/report/github.com/brittonhayes/aos) -> A Warhammer: Age of Sigmar REST API built with Go and Sqlite. +> An unnoficial Warhammer: Age of Sigmar REST API built with Go and Sqlite. ## ✨ Try the API (hosted) @@ -28,11 +28,11 @@ task up API documentation is available in YAML format within the repository. The OpenAPI spec is used to generate the transport logic thanks to [goapi-gen](https://github.com/discord-gophers/goapi-gen). -- [View the OpenAPI Spec](https://github.com/brittonhayes/warhammer/blob/main/api/openapi.yaml) +- [View the OpenAPI Spec](https://github.com/brittonhayes/aos/blob/main/api/openapi.yaml) ## 🗄️ Adding or Editing Data -All application data used to seed the database is editable in the [fixtures/](https://github.com/brittonhayes/warhammer/blob/main/fixtures/) directory. The API is built to be self-seeding and read-only, so if there is a need to add more data, simply add it to the fixtures files, rebuild and redeploy the API. +All application data used to seed the database is editable in the [fixtures/](https://github.com/brittonhayes/aos/blob/main/fixtures/) directory. The API is built to be self-seeding and read-only, so if there is a need to add more data, simply add it to the fixtures files, rebuild and redeploy the API. ### Example - Adding a new alliance @@ -50,7 +50,7 @@ To add a new entry to the database, just add a new object to the appropriate yam + description: The forces of Chaos seek to corrupt and dominate the Mortal Realms. Made up of daemons, monsters, and twisted beings, they spread destruction wherever theygo. ``` -- [View the data](https://github.com/brittonhayes/warhammer/blob/main/fixtures/fixtures.yaml) +- [View the data](https://github.com/brittonhayes/aos/blob/main/fixtures/fixtures.yaml) ## API Endpoints @@ -76,15 +76,15 @@ Application observability is instrumented with OpenTelemetry. Telemetry is avail When running with docker-compose, the following services are available: -- API is available at [http://warhammer.localhost:8090](http://warhammer.localhost:8090) -- Documentation is available at [http://warhammer.localhost:8090/docs](http://warhammer.localhost:8090/docs) +- API is available at [http://aos.localhost:8090](http://aos.localhost:8090) +- Documentation is available at [http://aos.localhost:8090/docs](http://aos.localhost:8090/docs) - Traefik Dashboard is available at [http://localhost:8080](http://localhost:8080) - Prometheus is available at [http://prometheus.localhost:8090](http://prometheus.localhost:8090) - Grafana is available at [http://grafana.localhost:8090](http://grafana.localhost:8090) ## 🙋 FAQ -- **Q: Where is X {unit,alliance,etc}?** - A: Waiting for you to add it! See the [fixtures/](https://github.com/brittonhayes/warhammer/blob/main/fixtures/) directory for more information. +- **Q: Where is X {unit,alliance,etc}?** - A: Waiting for you to add it! See the [fixtures/](https://github.com/brittonhayes/aos/blob/main/fixtures/) directory for more information. ## ⚖️ Copyright and Data Ownership @@ -99,4 +99,4 @@ through a REST interface rather than the usual PDF. If you consume the data served through this API, be aware that you are also obligated to respect [Games Workshop's](https://www.games-workshop.com) [intellectual property guidelines](https://www.games-workshop.com/en-US/Intellectual-Property-Guidelines). -For more information, view our [Contributing Guidelines](https://github.com/brittonhayes/warhammer/blob/main/CONTRIBUTING.md). \ No newline at end of file +For more information, view our [Contributing Guidelines](https://github.com/brittonhayes/aos/blob/main/CONTRIBUTING.md). \ No newline at end of file diff --git a/Taskfile.yml b/Taskfile.yml index dc2e1ee..cb7c83d 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -5,7 +5,7 @@ version: '3' tasks: default: cmds: - - go run ./cmd/warhammerd + - go run ./cmd/aos up: desc: "Start the application with docker-compose" diff --git a/warhammer.go b/aos.go similarity index 86% rename from warhammer.go rename to aos.go index df51c9c..14d1d62 100644 --- a/warhammer.go +++ b/aos.go @@ -1,17 +1,17 @@ -// Package warhammer provides the WarhammerRepository interface for the Warhammer REST API and services +// Package aos provides the Repository interface for the AoS REST API and services // -//go:generate goapi-gen -generate types,server,spec -package api --out api/warhammer.gen.go ./api/openapi.yaml +//go:generate goapi-gen -generate types,server,spec -package api --out api/api.gen.go ./api/openapi.yaml //go:generate npx @redocly/cli build-docs api/openapi.yaml -o web/index.html -package warhammer +package aos import ( "context" "io/fs" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" ) -type WarhammerRepository interface { +type Repository interface { GetArmyByID(ctx context.Context, id string) (*api.Army, error) GetArmies(ctx context.Context) ([]api.Army, error) diff --git a/api/openapi.yaml b/api/openapi.yaml index daf1fd6..35f0c2d 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1,14 +1,14 @@ openapi: "3.1.0" info: - title: Warhammer Age of Sigmar API (Unofficial) + title: AoS API (Unofficial) version: 1.0.0 - description: API specification for a Warhammer Age of Sigmar API (Unofficial) + description: API specification for an AoS REST API (Unofficial) license: name: MIT url: https://opensource.org/licenses/MIT security: [] servers: -- url: http://warhammer.localhost +- url: http://aos-api.localhost description: Local server - url: https://aos-api.com description: Production server diff --git a/cmd/warhammerd/main.go b/cmd/aos/main.go similarity index 86% rename from cmd/warhammerd/main.go rename to cmd/aos/main.go index 7ea01af..a5b122d 100644 --- a/cmd/warhammerd/main.go +++ b/cmd/aos/main.go @@ -8,13 +8,13 @@ import ( "sort" "time" - "github.com/brittonhayes/warhammer" - "github.com/brittonhayes/warhammer/api" - "github.com/brittonhayes/warhammer/fixtures" - "github.com/brittonhayes/warhammer/internal/logging" - "github.com/brittonhayes/warhammer/internal/tracing" - "github.com/brittonhayes/warhammer/service" - "github.com/brittonhayes/warhammer/sqlite" + "github.com/brittonhayes/aos" + "github.com/brittonhayes/aos/api" + "github.com/brittonhayes/aos/fixtures" + "github.com/brittonhayes/aos/internal/logging" + "github.com/brittonhayes/aos/internal/tracing" + "github.com/brittonhayes/aos/service" + "github.com/brittonhayes/aos/sqlite" apimw "github.com/discord-gophers/goapi-gen/middleware" "github.com/go-chi/chi/v5" @@ -29,16 +29,16 @@ import ( func main() { var ( - repo warhammer.WarhammerRepository + repo aos.Repository ) app := &cli.App{ - Name: "warhammerd", - Usage: "the warhammer api server", + Name: "aos", + Usage: "AoS api server", Suggest: true, Before: func(c *cli.Context) error { if c.Bool("migrate") { - repo = sqlite.NewWarhammerRepository(c.String("db")) + repo = sqlite.NewaosRepository(c.String("db")) err := repo.Init(c.Context) if err != nil { @@ -59,7 +59,7 @@ func main() { fixtures.WARSCROLLS, } - err = repo.Seed(c.Context, warhammer.FIXTURES, data...) + err = repo.Seed(c.Context, aos.FIXTURES, data...) if err != nil { return err } @@ -67,10 +67,10 @@ func main() { return nil }, Action: func(c *cli.Context) error { - repo = sqlite.NewWarhammerRepository(c.String("db")) + repo = sqlite.NewaosRepository(c.String("db")) // Create an instance of our handler which satisfies the generated interface - s := service.NewWarhammerService(repo) + s := service.NewaosService(repo) swagger, err := api.GetSwagger() if err != nil { @@ -158,14 +158,14 @@ func main() { Name: "port", Aliases: []string{"p"}, Value: 8080, - EnvVars: []string{"WARHAMMER_SERVICE_PORT", "PORT"}, + EnvVars: []string{"PORT"}, Usage: "port to listen on", }, &cli.StringFlag{ Name: "service", Aliases: []string{"s"}, - Value: "warhammerd", - EnvVars: []string{"WARHAMMER_SERVICE_NAME", "SERVICE_NAME"}, + Value: "aos", + EnvVars: []string{"SERVICE_NAME"}, Usage: "customize the service name", }, &cli.StringFlag{ @@ -176,7 +176,7 @@ func main() { }, &cli.StringFlag{ Name: "db", - Value: "file:warhammer.db", + Value: "file:aos.db", EnvVars: []string{"DATABASE_URL"}, Usage: "database url", }, @@ -203,7 +203,7 @@ func main() { return repo.Migrate(c.Context) }, Before: func(c *cli.Context) error { - repo = sqlite.NewWarhammerRepository(c.String("db")) + repo = sqlite.NewaosRepository(c.String("db")) return nil }, Subcommands: []*cli.Command{ @@ -258,7 +258,7 @@ func main() { fixtures.WARSCROLLS, } - return repo.Seed(c.Context, warhammer.FIXTURES, data...) + return repo.Seed(c.Context, aos.FIXTURES, data...) }, }, }, diff --git a/config/prometheus-config.yaml b/config/prometheus-config.yaml index 9f10d1a..474d687 100644 --- a/config/prometheus-config.yaml +++ b/config/prometheus-config.yaml @@ -24,6 +24,6 @@ scrape_configs: static_configs: - targets: ['prometheus:9090'] -- job_name: 'warhammer' +- job_name: 'aos' static_configs: - - targets: ['warhammer:8080'] + - targets: ['aos:8080'] diff --git a/docker-compose.yml b/docker-compose.yml index 34168da..4fcf93b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -6,7 +6,7 @@ volumes: networks: default: - name: warhammer + name: aos driver: bridge services: @@ -25,25 +25,25 @@ services: volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - warhammer: - container_name: warhammer - image: ghcr.io:brittonhayes/warhammer:latest + aos: + container_name: aos + image: ghcr.io:brittonhayes/aos:latest build: dockerfile: ./Dockerfile context: . labels: - "traefik.enable=true" - "traefik.docker.network=web" - - "traefik.http.routers.warhammer.rule=Host(`warhammer.localhost`) && PathPrefix(`/api`) && Method(`GET`, `OPTIONS`)" - - "traefik.http.routers.warhammer.entrypoints=web" - - "traefik.http.middlewares.warhammer-ratelimit.ratelimit.average=250" - - "traefik.http.middlewares.warhammer-ratelimit.ratelimit.burst=100" - - "traefik.http.middlewares.warhammer-strip-api.stripprefix.prefixes=/api" - - "traefik.http.routers.warhammer.middlewares=warhammer-strip-api" - - "traefik.http.services.warhammer.loadbalancer.server.port=8080" + - "traefik.http.routers.aos-api.rule=Host(`aos-api.localhost`) && PathPrefix(`/api`) && Method(`GET`, `OPTIONS`)" + - "traefik.http.routers.aos-api.entrypoints=web" + - "traefik.http.middlewares.aos-api-ratelimit.ratelimit.average=250" + - "traefik.http.middlewares.aos-api-ratelimit.ratelimit.burst=100" + - "traefik.http.middlewares.aos-api-strip-api.stripprefix.prefixes=/api" + - "traefik.http.routers.aos-api.middlewares=aos-api-strip-api" + - "traefik.http.services.aos-api.loadbalancer.server.port=8080" environment: - - WARHAMMER_SERVICE_NAME - - WARHAMMER_SERVICE_PORT + - SERVICE_NAME + - SERVICE_PORT - OTEL_EXPORTER_OTLP_ENDPOINT - OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE - OTEL_RESOURCE_ATTRIBUTES diff --git a/embed.go b/embed.go index 807e848..cfba223 100644 --- a/embed.go +++ b/embed.go @@ -1,4 +1,4 @@ -package warhammer +package aos import ( "embed" diff --git a/go.mod b/go.mod index 91558c8..c430566 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/brittonhayes/warhammer +module github.com/brittonhayes/aos go 1.20 diff --git a/railway.toml b/railway.toml index 3597f5c..d09db9f 100644 --- a/railway.toml +++ b/railway.toml @@ -1,4 +1,4 @@ [deploy] -startCommand = "/bin/warhammerd --migrate --tracing=false" +startCommand = "/bin/aos --migrate --tracing=false" restartPolicyType = "on_failure" restartPolicyMaxRetries = 5 \ No newline at end of file diff --git a/service/allegiance.go b/service/allegiance.go index 66bdcce..19f092c 100644 --- a/service/allegiance.go +++ b/service/allegiance.go @@ -3,8 +3,8 @@ package service import ( "net/http" - "github.com/brittonhayes/warhammer/api" - "github.com/brittonhayes/warhammer/internal/logging" + "github.com/brittonhayes/aos/api" + "github.com/brittonhayes/aos/internal/logging" "github.com/sirupsen/logrus" ) @@ -13,7 +13,7 @@ const ( ErrAllegiancesNotFound = "No allegiances found" ) -func (s *WarhammerService) GetAllegianceByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *aosService) GetAllegianceByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetAllegianceByID", @@ -28,7 +28,7 @@ func (s *WarhammerService) GetAllegianceByID(w http.ResponseWriter, r *http.Requ return api.GetAllegianceByIDJSON200Response(*allegiance) } -func (s *WarhammerService) GetAllegiances(w http.ResponseWriter, r *http.Request, params api.GetAllegiancesParams) *api.Response { +func (s *aosService) GetAllegiances(w http.ResponseWriter, r *http.Request, params api.GetAllegiancesParams) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetAllegiances", diff --git a/service/alliance.go b/service/alliance.go index 75a5f79..9e67f2f 100644 --- a/service/alliance.go +++ b/service/alliance.go @@ -3,8 +3,8 @@ package service import ( "net/http" - "github.com/brittonhayes/warhammer/api" - "github.com/brittonhayes/warhammer/internal/logging" + "github.com/brittonhayes/aos/api" + "github.com/brittonhayes/aos/internal/logging" "github.com/sirupsen/logrus" ) @@ -13,7 +13,7 @@ const ( ErrAlliancesNotFound = "No alliances found" ) -func (s *WarhammerService) GetGrandAllianceByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *aosService) GetGrandAllianceByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetGrandAllianceByID", @@ -28,7 +28,7 @@ func (s *WarhammerService) GetGrandAllianceByID(w http.ResponseWriter, r *http.R return api.GetGrandAllianceByIDJSON200Response(*alliance) } -func (s *WarhammerService) GetGrandAlliances(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *aosService) GetGrandAlliances(w http.ResponseWriter, r *http.Request) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetGrandAlliances", diff --git a/service/army.go b/service/army.go index 26355d2..de79338 100644 --- a/service/army.go +++ b/service/army.go @@ -3,8 +3,8 @@ package service import ( "net/http" - "github.com/brittonhayes/warhammer/api" - "github.com/brittonhayes/warhammer/internal/logging" + "github.com/brittonhayes/aos/api" + "github.com/brittonhayes/aos/internal/logging" "github.com/sirupsen/logrus" ) @@ -13,7 +13,7 @@ const ( ErrArmiesNotFound = "No armies found" ) -func (s *WarhammerService) GetArmyByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *aosService) GetArmyByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetArmyByID", @@ -28,7 +28,7 @@ func (s *WarhammerService) GetArmyByID(w http.ResponseWriter, r *http.Request, i return api.GetArmyByIDJSON200Response(*army) } -func (s *WarhammerService) GetArmies(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *aosService) GetArmies(w http.ResponseWriter, r *http.Request) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetArmies", diff --git a/service/city.go b/service/city.go index 8f254bd..65aed67 100644 --- a/service/city.go +++ b/service/city.go @@ -3,14 +3,14 @@ package service import ( "net/http" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" ) const ( ErrCitiesNotFound = "cities not found" ) -func (s *WarhammerService) GetCities(w http.ResponseWriter, r *http.Request, params api.GetCitiesParams) *api.Response { +func (s *aosService) GetCities(w http.ResponseWriter, r *http.Request, params api.GetCitiesParams) *api.Response { cities, err := s.repo.GetCities(r.Context(), params) if err != nil { return api.GetCitiesJSON404Response(api.Error{ @@ -22,7 +22,7 @@ func (s *WarhammerService) GetCities(w http.ResponseWriter, r *http.Request, par return api.GetCitiesJSON200Response(cities) } -func (s *WarhammerService) GetCityByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *aosService) GetCityByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { city, err := s.repo.GetCityByID(r.Context(), id) if err != nil { return api.GetCityByIDJSON404Response(api.Error{ diff --git a/service/doc.go b/service/doc.go index 93671c7..5334e44 100644 --- a/service/doc.go +++ b/service/doc.go @@ -3,16 +3,16 @@ package service import ( "net/http" - "github.com/brittonhayes/warhammer" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos" + "github.com/brittonhayes/aos/api" ) -func (s *WarhammerService) GetDocs(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *aosService) GetDocs(w http.ResponseWriter, r *http.Request) *api.Response { resp := api.Response{} resp.ContentType("text/html") resp.Status(http.StatusOK) - w.Write(warhammer.OPEN_API_DOCS) + w.Write(aos.OPEN_API_DOCS) return &resp } diff --git a/service/healthz.go b/service/healthz.go index 36ebd49..a12513f 100644 --- a/service/healthz.go +++ b/service/healthz.go @@ -3,10 +3,10 @@ package service import ( "net/http" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" ) -func (s *WarhammerService) GetHealthz(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *aosService) GetHealthz(w http.ResponseWriter, r *http.Request) *api.Response { resp := api.Health{Status: "ok"} return api.GetHealthzJSON200Response(resp) } diff --git a/service/service.go b/service/service.go index cf68439..c322ea0 100644 --- a/service/service.go +++ b/service/service.go @@ -1,18 +1,18 @@ package service import ( - "github.com/brittonhayes/warhammer" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos" + "github.com/brittonhayes/aos/api" ) -type WarhammerService struct { - repo warhammer.WarhammerRepository +type aosService struct { + repo aos.HammerRepository } -var _ api.ServerInterface = (*WarhammerService)(nil) +var _ api.ServerInterface = (*aosService)(nil) -func NewWarhammerService(repository warhammer.WarhammerRepository) api.ServerInterface { - return &WarhammerService{ +func NewaosService(repository aos.HammerRepository) api.ServerInterface { + return &aosService{ repo: repository, } } diff --git a/service/strategy.go b/service/strategy.go index 5050972..a6735ab 100644 --- a/service/strategy.go +++ b/service/strategy.go @@ -3,8 +3,8 @@ package service import ( "net/http" - "github.com/brittonhayes/warhammer/api" - "github.com/brittonhayes/warhammer/internal/logging" + "github.com/brittonhayes/aos/api" + "github.com/brittonhayes/aos/internal/logging" "github.com/sirupsen/logrus" ) @@ -13,7 +13,7 @@ const ( ErrGrandStrategiesNotFound = "No strategys found" ) -func (s *WarhammerService) GetGrandStrategyByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *aosService) GetGrandStrategyByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetStrategyByID", @@ -28,7 +28,7 @@ func (s *WarhammerService) GetGrandStrategyByID(w http.ResponseWriter, r *http.R return api.GetGrandStrategyByIDJSON200Response(api.GrandStrategy(*strategy)) } -func (s *WarhammerService) GetGrandStrategies(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *aosService) GetGrandStrategies(w http.ResponseWriter, r *http.Request) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetStrategies", diff --git a/service/unit.go b/service/unit.go index 51e47f1..0e7e8c1 100644 --- a/service/unit.go +++ b/service/unit.go @@ -3,7 +3,7 @@ package service import ( "net/http" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" ) const ( @@ -11,7 +11,7 @@ const ( ErrUnitsNotFound = "No units found" ) -func (s *WarhammerService) GetUnitByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *aosService) GetUnitByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { unit, err := s.repo.GetUnitByID(r.Context(), id) if err != nil { return api.GetUnitByIDJSON404Response(api.Error{Code: http.StatusNotFound, Message: ErrUnitNotFound}) @@ -20,7 +20,7 @@ func (s *WarhammerService) GetUnitByID(w http.ResponseWriter, r *http.Request, i return api.GetUnitByIDJSON200Response(*unit) } -func (s *WarhammerService) GetUnits(w http.ResponseWriter, r *http.Request, params api.GetUnitsParams) *api.Response { +func (s *aosService) GetUnits(w http.ResponseWriter, r *http.Request, params api.GetUnitsParams) *api.Response { units, err := s.repo.GetUnits(r.Context(), params) if err != nil { return api.GetUnitsJSON404Response(api.Error{Code: http.StatusNotFound, Message: ErrUnitsNotFound}) @@ -29,7 +29,7 @@ func (s *WarhammerService) GetUnits(w http.ResponseWriter, r *http.Request, para return api.GetUnitsJSON200Response(units) } -func (s *WarhammerService) GetAbilitiesForUnitByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *aosService) GetAbilitiesForUnitByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { abilities, err := s.repo.GetAbilitiesForUnitByID(r.Context(), id) if err != nil { return api.GetAbilitiesForUnitByIDJSON404Response(api.Error{Code: http.StatusNotFound, Message: ErrUnitNotFound}) diff --git a/service/warscroll.go b/service/warscroll.go index 945ac35..f70e168 100644 --- a/service/warscroll.go +++ b/service/warscroll.go @@ -3,7 +3,7 @@ package service import ( "net/http" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" "go.opentelemetry.io/otel/attribute" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" "go.opentelemetry.io/otel/trace" @@ -14,7 +14,7 @@ const ( ErrWarscrollsNotFound = "No warscrolls found" ) -func (s *WarhammerService) GetWarscrollByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *aosService) GetWarscrollByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { span := trace.SpanFromContext(r.Context()) defer span.End() @@ -40,7 +40,7 @@ func (s *WarhammerService) GetWarscrollByID(w http.ResponseWriter, r *http.Reque return api.GetWarscrollByIDJSON200Response(*warscroll) } -func (s *WarhammerService) GetWarscrolls(w http.ResponseWriter, r *http.Request, params api.GetWarscrollsParams) *api.Response { +func (s *aosService) GetWarscrolls(w http.ResponseWriter, r *http.Request, params api.GetWarscrollsParams) *api.Response { span := trace.SpanFromContext(r.Context()) defer span.End() diff --git a/sqlite/allegiance.go b/sqlite/allegiance.go index dcd4c66..a5ddf95 100644 --- a/sqlite/allegiance.go +++ b/sqlite/allegiance.go @@ -3,11 +3,11 @@ package sqlite import ( "context" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" "github.com/uptrace/bun" ) -func (r *warhammerRepository) GetAllegianceByID(ctx context.Context, id string) (*api.Allegiance, error) { +func (r *aosRepository) GetAllegianceByID(ctx context.Context, id string) (*api.Allegiance, error) { var allegiance api.Allegiance err := r.db.NewSelect().Model(&allegiance).Where("id = ?", id).Scan(ctx) if err != nil { @@ -17,7 +17,7 @@ func (r *warhammerRepository) GetAllegianceByID(ctx context.Context, id string) return &allegiance, nil } -func (r *warhammerRepository) allegiancesFilterQuery(query *bun.SelectQuery, params api.GetAllegiancesParams) (*bun.SelectQuery, error) { +func (r *aosRepository) allegiancesFilterQuery(query *bun.SelectQuery, params api.GetAllegiancesParams) (*bun.SelectQuery, error) { if params.GrandAlliance != nil { query = query.Where("grand_alliance = ?", params.GrandAlliance) } @@ -29,7 +29,7 @@ func (r *warhammerRepository) allegiancesFilterQuery(query *bun.SelectQuery, par return query, nil } -func (r *warhammerRepository) GetAllegiances(ctx context.Context, params api.GetAllegiancesParams) ([]api.Allegiance, error) { +func (r *aosRepository) GetAllegiances(ctx context.Context, params api.GetAllegiancesParams) ([]api.Allegiance, error) { var allegiances []api.Allegiance query, err := r.allegiancesFilterQuery(r.db.NewSelect().Model(&allegiances), params) diff --git a/sqlite/alliance.go b/sqlite/alliance.go index 9282f1d..9e9c7dc 100644 --- a/sqlite/alliance.go +++ b/sqlite/alliance.go @@ -3,10 +3,10 @@ package sqlite import ( "context" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" ) -func (r *warhammerRepository) GetGrandAllianceByID(ctx context.Context, id string) (*api.GrandAlliance, error) { +func (r *aosRepository) GetGrandAllianceByID(ctx context.Context, id string) (*api.GrandAlliance, error) { var grandAlliance api.GrandAlliance err := r.db.NewSelect().Model(&grandAlliance).Where("id = ?", id).Scan(ctx) if err != nil { @@ -16,7 +16,7 @@ func (r *warhammerRepository) GetGrandAllianceByID(ctx context.Context, id strin return &grandAlliance, nil } -func (r *warhammerRepository) GetGrandAlliances(ctx context.Context) ([]api.GrandAlliance, error) { +func (r *aosRepository) GetGrandAlliances(ctx context.Context) ([]api.GrandAlliance, error) { var grandAlliances []api.GrandAlliance err := r.db.NewSelect().Model(&grandAlliances).Scan(ctx) if err != nil { diff --git a/sqlite/army.go b/sqlite/army.go index 239b8bd..ad0782f 100644 --- a/sqlite/army.go +++ b/sqlite/army.go @@ -3,10 +3,10 @@ package sqlite import ( "context" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" ) -func (r *warhammerRepository) GetArmyByID(ctx context.Context, id string) (*api.Army, error) { +func (r *aosRepository) GetArmyByID(ctx context.Context, id string) (*api.Army, error) { var army api.Army err := r.db.NewSelect().Model(&army).Where("id = ?", id).Scan(ctx) if err != nil { @@ -16,7 +16,7 @@ func (r *warhammerRepository) GetArmyByID(ctx context.Context, id string) (*api. return &army, nil } -func (r *warhammerRepository) GetArmies(ctx context.Context) ([]api.Army, error) { +func (r *aosRepository) GetArmies(ctx context.Context) ([]api.Army, error) { var armies []api.Army err := r.db.NewSelect().Model(&armies).Scan(ctx) if err != nil { @@ -26,7 +26,7 @@ func (r *warhammerRepository) GetArmies(ctx context.Context) ([]api.Army, error) return armies, nil } -func (r *warhammerRepository) UpdateArmyByID(ctx context.Context, id string, army *api.Army) (*api.Army, error) { +func (r *aosRepository) UpdateArmyByID(ctx context.Context, id string, army *api.Army) (*api.Army, error) { _, err := r.db.NewUpdate().Model(army).Where("id = ?", id).Exec(ctx) if err != nil { return nil, err diff --git a/sqlite/city.go b/sqlite/city.go index af51f4f..24f433a 100644 --- a/sqlite/city.go +++ b/sqlite/city.go @@ -3,11 +3,11 @@ package sqlite import ( "context" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" "github.com/uptrace/bun" ) -func (r *warhammerRepository) citiesFilterQuery(query *bun.SelectQuery, params api.GetCitiesParams) (*bun.SelectQuery, error) { +func (r *aosRepository) citiesFilterQuery(query *bun.SelectQuery, params api.GetCitiesParams) (*bun.SelectQuery, error) { if params.Name != nil { query = query.Where("? LIKE ?", bun.Ident("name"), *params.Name+"%") @@ -16,7 +16,7 @@ func (r *warhammerRepository) citiesFilterQuery(query *bun.SelectQuery, params a return query, nil } -func (r *warhammerRepository) GetCities(ctx context.Context, params api.GetCitiesParams) ([]api.City, error) { +func (r *aosRepository) GetCities(ctx context.Context, params api.GetCitiesParams) ([]api.City, error) { var cities []api.City query, err := r.citiesFilterQuery(r.db.NewSelect().Model(&cities), params) @@ -32,7 +32,7 @@ func (r *warhammerRepository) GetCities(ctx context.Context, params api.GetCitie return cities, nil } -func (r *warhammerRepository) GetCityByID(ctx context.Context, id string) (*api.City, error) { +func (r *aosRepository) GetCityByID(ctx context.Context, id string) (*api.City, error) { var city api.City err := r.db.NewSelect().Model(&city).Where("id = ?", id).Scan(ctx) diff --git a/sqlite/migrations/20230712031006_init.go b/sqlite/migrations/20230712031006_init.go index 737f5a8..6516c43 100644 --- a/sqlite/migrations/20230712031006_init.go +++ b/sqlite/migrations/20230712031006_init.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" "github.com/uptrace/bun" ) diff --git a/sqlite/repository.go b/sqlite/repository.go index ae629a1..e3794f7 100644 --- a/sqlite/repository.go +++ b/sqlite/repository.go @@ -6,10 +6,10 @@ import ( "io/fs" "strings" - "github.com/brittonhayes/warhammer" - "github.com/brittonhayes/warhammer/api" - "github.com/brittonhayes/warhammer/internal/logging" - "github.com/brittonhayes/warhammer/sqlite/migrations" + "github.com/brittonhayes/aos" + "github.com/brittonhayes/aos/api" + "github.com/brittonhayes/aos/internal/logging" + "github.com/brittonhayes/aos/sqlite/migrations" "github.com/uptrace/bun" "github.com/uptrace/bun/dbfixture" "github.com/uptrace/bun/dialect/sqlitedialect" @@ -18,18 +18,18 @@ import ( "github.com/uptrace/bun/migrate" ) -type warhammerRepository struct { +type aosRepository struct { m *migrate.Migrator db *bun.DB } const ( - DB_NAME = "warhammer" + DB_NAME = "aos" DEFAULT_LIMIT = 100 DEFAULT_OFFSET = 0 ) -func NewWarhammerRepository(connection string) warhammer.WarhammerRepository { +func NewaosRepository(connection string) aos.Repository { sqldb, err := sql.Open(sqliteshim.ShimName, connection) if err != nil { panic(err) @@ -43,18 +43,18 @@ func NewWarhammerRepository(connection string) warhammer.WarhammerRepository { migrator := migrate.NewMigrator(db, migrations.Migrations) - return &warhammerRepository{ + return &aosRepository{ m: migrator, db: db, } } -func (r *warhammerRepository) Init(ctx context.Context) error { +func (r *aosRepository) Init(ctx context.Context) error { logging.NewLogrus(ctx).Info("initializing database") return r.m.Init(ctx) } -func (r *warhammerRepository) Generate(ctx context.Context, name string) error { +func (r *aosRepository) Generate(ctx context.Context, name string) error { name = strings.ReplaceAll(name, " ", "_") m, err := r.m.CreateGoMigration(ctx, name) @@ -67,7 +67,7 @@ func (r *warhammerRepository) Generate(ctx context.Context, name string) error { return nil } -func (r *warhammerRepository) Migrate(ctx context.Context) error { +func (r *aosRepository) Migrate(ctx context.Context) error { logger := logging.NewLogrus(ctx) @@ -91,7 +91,7 @@ func (r *warhammerRepository) Migrate(ctx context.Context) error { return nil } -func (r *warhammerRepository) Seed(ctx context.Context, fsys fs.FS, names ...string) error { +func (r *aosRepository) Seed(ctx context.Context, fsys fs.FS, names ...string) error { logger := logging.NewLogrus(ctx) models := []interface{}{ @@ -116,17 +116,17 @@ func (r *warhammerRepository) Seed(ctx context.Context, fsys fs.FS, names ...str return f.Load(ctx, fsys, names...) } -func (r *warhammerRepository) Lock(ctx context.Context) error { +func (r *aosRepository) Lock(ctx context.Context) error { logging.NewLogrus(ctx).Info("locking database") return r.m.Lock(ctx) } -func (r *warhammerRepository) Unlock(ctx context.Context) error { +func (r *aosRepository) Unlock(ctx context.Context) error { logging.NewLogrus(ctx).Info("unlocking database") return r.m.Unlock(ctx) } -func (r *warhammerRepository) Rollback(ctx context.Context) error { +func (r *aosRepository) Rollback(ctx context.Context) error { logger := logging.NewLogrus(ctx) err := r.m.Lock(ctx) diff --git a/sqlite/strategy.go b/sqlite/strategy.go index 5bec2d1..247371f 100644 --- a/sqlite/strategy.go +++ b/sqlite/strategy.go @@ -3,10 +3,10 @@ package sqlite import ( "context" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" ) -func (r *warhammerRepository) GetGrandStrategyByID(ctx context.Context, id string) (*api.GrandStrategy, error) { +func (r *aosRepository) GetGrandStrategyByID(ctx context.Context, id string) (*api.GrandStrategy, error) { var strategy api.GrandStrategy err := r.db.NewSelect().Model(&strategy).Where("id = ?", id).Scan(ctx) if err != nil { @@ -16,7 +16,7 @@ func (r *warhammerRepository) GetGrandStrategyByID(ctx context.Context, id strin return &strategy, nil } -func (r *warhammerRepository) GetGrandStrategies(ctx context.Context) ([]api.GrandStrategy, error) { +func (r *aosRepository) GetGrandStrategies(ctx context.Context) ([]api.GrandStrategy, error) { var strategies []api.GrandStrategy err := r.db.NewSelect().Model(&strategies).Scan(ctx) if err != nil { diff --git a/sqlite/unit.go b/sqlite/unit.go index e1d3de1..9817029 100644 --- a/sqlite/unit.go +++ b/sqlite/unit.go @@ -3,11 +3,11 @@ package sqlite import ( "context" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" "github.com/uptrace/bun" ) -func (r *warhammerRepository) GetUnitByID(ctx context.Context, id string) (*api.Unit, error) { +func (r *aosRepository) GetUnitByID(ctx context.Context, id string) (*api.Unit, error) { var unit api.Unit err := r.db.NewSelect().Model(&unit).Where("id = ?", id).Scan(ctx) if err != nil { @@ -17,7 +17,7 @@ func (r *warhammerRepository) GetUnitByID(ctx context.Context, id string) (*api. return &unit, nil } -func (r *warhammerRepository) unitsFilterQuery(query *bun.SelectQuery, params api.GetUnitsParams) (*bun.SelectQuery, error) { +func (r *aosRepository) unitsFilterQuery(query *bun.SelectQuery, params api.GetUnitsParams) (*bun.SelectQuery, error) { if params.Name != nil { query = query.Where("? LIKE ?", bun.Ident("name"), *params.Name+"%") } @@ -37,7 +37,7 @@ func (r *warhammerRepository) unitsFilterQuery(query *bun.SelectQuery, params ap return query, nil } -func (r *warhammerRepository) GetUnits(ctx context.Context, params api.GetUnitsParams) ([]api.Unit, error) { +func (r *aosRepository) GetUnits(ctx context.Context, params api.GetUnitsParams) ([]api.Unit, error) { var units []api.Unit query, err := r.unitsFilterQuery(r.db.NewSelect().Model(&units), params) @@ -53,7 +53,7 @@ func (r *warhammerRepository) GetUnits(ctx context.Context, params api.GetUnitsP return units, nil } -func (r *warhammerRepository) GetAbilitiesForUnitByID(ctx context.Context, id string) ([]api.Ability, error) { +func (r *aosRepository) GetAbilitiesForUnitByID(ctx context.Context, id string) ([]api.Ability, error) { var unit api.Unit err := r.db.NewSelect().Model(&unit).Where("id = ?", id).Scan(ctx) if err != nil { diff --git a/sqlite/warscroll.go b/sqlite/warscroll.go index af0eed4..8f3e451 100644 --- a/sqlite/warscroll.go +++ b/sqlite/warscroll.go @@ -3,11 +3,11 @@ package sqlite import ( "context" - "github.com/brittonhayes/warhammer/api" + "github.com/brittonhayes/aos/api" "github.com/uptrace/bun" ) -func (r *warhammerRepository) warscrollFilterQuery(query *bun.SelectQuery, params api.GetWarscrollsParams) (*bun.SelectQuery, error) { +func (r *aosRepository) warscrollFilterQuery(query *bun.SelectQuery, params api.GetWarscrollsParams) (*bun.SelectQuery, error) { if params.Name != nil { query = query.Where("? LIKE ?", bun.Ident("name"), *params.Name+"%") } @@ -31,7 +31,7 @@ func (r *warhammerRepository) warscrollFilterQuery(query *bun.SelectQuery, param return query, nil } -func (r *warhammerRepository) GetWarscrolls(ctx context.Context, params api.GetWarscrollsParams) ([]api.Warscroll, error) { +func (r *aosRepository) GetWarscrolls(ctx context.Context, params api.GetWarscrollsParams) ([]api.Warscroll, error) { var warscrolls []api.Warscroll query, err := r.warscrollFilterQuery(r.db.NewSelect().Model(&warscrolls), params) @@ -47,7 +47,7 @@ func (r *warhammerRepository) GetWarscrolls(ctx context.Context, params api.GetW return warscrolls, nil } -func (r *warhammerRepository) GetWarscrollByID(ctx context.Context, id string) (*api.Warscroll, error) { +func (r *aosRepository) GetWarscrollByID(ctx context.Context, id string) (*api.Warscroll, error) { var warscroll api.Warscroll err := r.db.NewSelect().Model(&warscroll).Where("id = ?", id).Scan(ctx) From cab01e42bb76a2bf8a76b5e4478c194e92b6d8ad Mon Sep 17 00:00:00 2001 From: brittonhayes Date: Thu, 27 Jul 2023 17:34:36 -0700 Subject: [PATCH 2/6] fix: renaming services and README.md --- README.md | 2 +- cmd/aos/main.go | 4 ++-- service/allegiance.go | 4 ++-- service/alliance.go | 4 ++-- service/army.go | 4 ++-- service/city.go | 4 ++-- service/doc.go | 2 +- service/healthz.go | 2 +- service/service.go | 10 +++++----- service/strategy.go | 4 ++-- service/unit.go | 6 +++--- service/warscroll.go | 4 ++-- 12 files changed, 25 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index b505e78..c9a4618 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![Go Reference](https://pkg.go.dev/badge/github.com/brittonhayes/aos.svg)](https://pkg.go.dev/github.com/brittonhayes/aos) [![Go Report Card](https://goreportcard.com/badge/github.com/brittonhayes/aos)](https://goreportcard.com/report/github.com/brittonhayes/aos) -> An unnoficial Warhammer: Age of Sigmar REST API built with Go and Sqlite. +> An unnoficial AoS REST API built with Go and Sqlite. ## ✨ Try the API (hosted) diff --git a/cmd/aos/main.go b/cmd/aos/main.go index a5b122d..b056852 100644 --- a/cmd/aos/main.go +++ b/cmd/aos/main.go @@ -70,7 +70,7 @@ func main() { repo = sqlite.NewaosRepository(c.String("db")) // Create an instance of our handler which satisfies the generated interface - s := service.NewaosService(repo) + s := service.New(repo) swagger, err := api.GetSwagger() if err != nil { @@ -183,7 +183,7 @@ func main() { &cli.BoolFlag{ Name: "tracing", Aliases: []string{"t"}, - Value: true, + Value: false, EnvVars: []string{"TRACING"}, Usage: "enable tracing", }, diff --git a/service/allegiance.go b/service/allegiance.go index 19f092c..b730cf4 100644 --- a/service/allegiance.go +++ b/service/allegiance.go @@ -13,7 +13,7 @@ const ( ErrAllegiancesNotFound = "No allegiances found" ) -func (s *aosService) GetAllegianceByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *Service) GetAllegianceByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetAllegianceByID", @@ -28,7 +28,7 @@ func (s *aosService) GetAllegianceByID(w http.ResponseWriter, r *http.Request, i return api.GetAllegianceByIDJSON200Response(*allegiance) } -func (s *aosService) GetAllegiances(w http.ResponseWriter, r *http.Request, params api.GetAllegiancesParams) *api.Response { +func (s *Service) GetAllegiances(w http.ResponseWriter, r *http.Request, params api.GetAllegiancesParams) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetAllegiances", diff --git a/service/alliance.go b/service/alliance.go index 9e67f2f..5beaab9 100644 --- a/service/alliance.go +++ b/service/alliance.go @@ -13,7 +13,7 @@ const ( ErrAlliancesNotFound = "No alliances found" ) -func (s *aosService) GetGrandAllianceByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *Service) GetGrandAllianceByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetGrandAllianceByID", @@ -28,7 +28,7 @@ func (s *aosService) GetGrandAllianceByID(w http.ResponseWriter, r *http.Request return api.GetGrandAllianceByIDJSON200Response(*alliance) } -func (s *aosService) GetGrandAlliances(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *Service) GetGrandAlliances(w http.ResponseWriter, r *http.Request) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetGrandAlliances", diff --git a/service/army.go b/service/army.go index de79338..d952160 100644 --- a/service/army.go +++ b/service/army.go @@ -13,7 +13,7 @@ const ( ErrArmiesNotFound = "No armies found" ) -func (s *aosService) GetArmyByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *Service) GetArmyByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetArmyByID", @@ -28,7 +28,7 @@ func (s *aosService) GetArmyByID(w http.ResponseWriter, r *http.Request, id stri return api.GetArmyByIDJSON200Response(*army) } -func (s *aosService) GetArmies(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *Service) GetArmies(w http.ResponseWriter, r *http.Request) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetArmies", diff --git a/service/city.go b/service/city.go index 65aed67..3b4e9e7 100644 --- a/service/city.go +++ b/service/city.go @@ -10,7 +10,7 @@ const ( ErrCitiesNotFound = "cities not found" ) -func (s *aosService) GetCities(w http.ResponseWriter, r *http.Request, params api.GetCitiesParams) *api.Response { +func (s *Service) GetCities(w http.ResponseWriter, r *http.Request, params api.GetCitiesParams) *api.Response { cities, err := s.repo.GetCities(r.Context(), params) if err != nil { return api.GetCitiesJSON404Response(api.Error{ @@ -22,7 +22,7 @@ func (s *aosService) GetCities(w http.ResponseWriter, r *http.Request, params ap return api.GetCitiesJSON200Response(cities) } -func (s *aosService) GetCityByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *Service) GetCityByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { city, err := s.repo.GetCityByID(r.Context(), id) if err != nil { return api.GetCityByIDJSON404Response(api.Error{ diff --git a/service/doc.go b/service/doc.go index 5334e44..0ecaa5d 100644 --- a/service/doc.go +++ b/service/doc.go @@ -7,7 +7,7 @@ import ( "github.com/brittonhayes/aos/api" ) -func (s *aosService) GetDocs(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *Service) GetDocs(w http.ResponseWriter, r *http.Request) *api.Response { resp := api.Response{} resp.ContentType("text/html") resp.Status(http.StatusOK) diff --git a/service/healthz.go b/service/healthz.go index a12513f..659eab9 100644 --- a/service/healthz.go +++ b/service/healthz.go @@ -6,7 +6,7 @@ import ( "github.com/brittonhayes/aos/api" ) -func (s *aosService) GetHealthz(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *Service) GetHealthz(w http.ResponseWriter, r *http.Request) *api.Response { resp := api.Health{Status: "ok"} return api.GetHealthzJSON200Response(resp) } diff --git a/service/service.go b/service/service.go index c322ea0..1736500 100644 --- a/service/service.go +++ b/service/service.go @@ -5,14 +5,14 @@ import ( "github.com/brittonhayes/aos/api" ) -type aosService struct { - repo aos.HammerRepository +type Service struct { + repo aos.Repository } -var _ api.ServerInterface = (*aosService)(nil) +var _ api.ServerInterface = (*Service)(nil) -func NewaosService(repository aos.HammerRepository) api.ServerInterface { - return &aosService{ +func New(repository aos.Repository) api.ServerInterface { + return &Service{ repo: repository, } } diff --git a/service/strategy.go b/service/strategy.go index a6735ab..90f7b58 100644 --- a/service/strategy.go +++ b/service/strategy.go @@ -13,7 +13,7 @@ const ( ErrGrandStrategiesNotFound = "No strategys found" ) -func (s *aosService) GetGrandStrategyByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *Service) GetGrandStrategyByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetStrategyByID", @@ -28,7 +28,7 @@ func (s *aosService) GetGrandStrategyByID(w http.ResponseWriter, r *http.Request return api.GetGrandStrategyByIDJSON200Response(api.GrandStrategy(*strategy)) } -func (s *aosService) GetGrandStrategies(w http.ResponseWriter, r *http.Request) *api.Response { +func (s *Service) GetGrandStrategies(w http.ResponseWriter, r *http.Request) *api.Response { logging.NewLogrus(r.Context()).WithFields(logrus.Fields{ "event": "GetStrategies", diff --git a/service/unit.go b/service/unit.go index 0e7e8c1..4ec2cf8 100644 --- a/service/unit.go +++ b/service/unit.go @@ -11,7 +11,7 @@ const ( ErrUnitsNotFound = "No units found" ) -func (s *aosService) GetUnitByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *Service) GetUnitByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { unit, err := s.repo.GetUnitByID(r.Context(), id) if err != nil { return api.GetUnitByIDJSON404Response(api.Error{Code: http.StatusNotFound, Message: ErrUnitNotFound}) @@ -20,7 +20,7 @@ func (s *aosService) GetUnitByID(w http.ResponseWriter, r *http.Request, id stri return api.GetUnitByIDJSON200Response(*unit) } -func (s *aosService) GetUnits(w http.ResponseWriter, r *http.Request, params api.GetUnitsParams) *api.Response { +func (s *Service) GetUnits(w http.ResponseWriter, r *http.Request, params api.GetUnitsParams) *api.Response { units, err := s.repo.GetUnits(r.Context(), params) if err != nil { return api.GetUnitsJSON404Response(api.Error{Code: http.StatusNotFound, Message: ErrUnitsNotFound}) @@ -29,7 +29,7 @@ func (s *aosService) GetUnits(w http.ResponseWriter, r *http.Request, params api return api.GetUnitsJSON200Response(units) } -func (s *aosService) GetAbilitiesForUnitByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *Service) GetAbilitiesForUnitByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { abilities, err := s.repo.GetAbilitiesForUnitByID(r.Context(), id) if err != nil { return api.GetAbilitiesForUnitByIDJSON404Response(api.Error{Code: http.StatusNotFound, Message: ErrUnitNotFound}) diff --git a/service/warscroll.go b/service/warscroll.go index f70e168..edc28ef 100644 --- a/service/warscroll.go +++ b/service/warscroll.go @@ -14,7 +14,7 @@ const ( ErrWarscrollsNotFound = "No warscrolls found" ) -func (s *aosService) GetWarscrollByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { +func (s *Service) GetWarscrollByID(w http.ResponseWriter, r *http.Request, id string) *api.Response { span := trace.SpanFromContext(r.Context()) defer span.End() @@ -40,7 +40,7 @@ func (s *aosService) GetWarscrollByID(w http.ResponseWriter, r *http.Request, id return api.GetWarscrollByIDJSON200Response(*warscroll) } -func (s *aosService) GetWarscrolls(w http.ResponseWriter, r *http.Request, params api.GetWarscrollsParams) *api.Response { +func (s *Service) GetWarscrolls(w http.ResponseWriter, r *http.Request, params api.GetWarscrollsParams) *api.Response { span := trace.SpanFromContext(r.Context()) defer span.End() From 1053e44508d87ef645780e29e58052812c77b64d Mon Sep 17 00:00:00 2001 From: brittonhayes Date: Fri, 28 Jul 2023 00:38:39 +0000 Subject: [PATCH 3/6] Commit from GitHub Actions (CI) --- api/api.gen.go | 1368 ++++++++++++++++++++++++++++++++++++++++++++++++ web/index.html | 40 +- 2 files changed, 1388 insertions(+), 20 deletions(-) create mode 100644 api/api.gen.go diff --git a/api/api.gen.go b/api/api.gen.go new file mode 100644 index 0000000..a537ce0 --- /dev/null +++ b/api/api.gen.go @@ -0,0 +1,1368 @@ +// Package api provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/discord-gophers/goapi-gen version v0.3.0 DO NOT EDIT. +package api + +import ( + "bytes" + "compress/gzip" + "encoding/base64" + "encoding/json" + "encoding/xml" + "fmt" + "net/http" + "net/url" + "path" + "strings" + + "github.com/discord-gophers/goapi-gen/runtime" + "github.com/getkin/kin-openapi/openapi3" + "github.com/go-chi/chi/v5" + "github.com/go-chi/render" +) + +// Ability defines model for Ability. +type Ability struct { + Description *string `json:"description,omitempty"` + Name *string `json:"name,omitempty"` +} + +// Allegiance defines model for Allegiance. +type Allegiance struct { + ID *string `bun:"id,pk" json:"_id,omitempty"` + Description *string `json:"description,omitempty"` + GrandAlliance *string `json:"grand_alliance,omitempty"` + MortalRealm *string `json:"mortal_realm,omitempty"` + Name string `json:"name"` +} + +// Army defines model for Army. +type Army struct { + ID *string `bun:"id,pk" json:"_id,omitempty"` + Name string `json:"name"` + Units []Unit `json:"units,omitempty"` +} + +// Attribute defines model for Attribute. +type Attribute struct { + Name *string `json:"name,omitempty"` + Value *int64 `json:"value,omitempty"` +} + +// City defines model for City. +type City struct { + ID *string `bun:"id,pk" json:"_id,omitempty"` + Description *string `json:"description,omitempty"` + Name *string `json:"name,omitempty"` +} + +// DamageTable defines model for DamageTable. +type DamageTable struct { + ID *string `bun:"id,pk" json:"_id,omitempty"` + MinWoundsSuffered *int64 `json:"min_wounds_suffered,omitempty"` + Move *Move `json:"move,omitempty"` + WoundTrackPosition *int64 `json:"wound_track_position,omitempty"` +} + +// Error defines model for Error. +type Error struct { + Code int32 `json:"code"` + Message string `json:"message"` +} + +// GrandAlliance defines model for GrandAlliance. +type GrandAlliance struct { + ID *string `bun:",pk" json:"_id,omitempty"` + Description *string `json:"description,omitempty"` + Name string `json:"name"` +} + +// GrandStrategy defines model for GrandStrategy. +type GrandStrategy struct { + ID *string `bun:",pk" json:"_id,omitempty"` + Description *string `json:"description,omitempty"` + Name string `json:"name"` +} + +// Health defines model for Health. +type Health struct { + Status string `json:"status"` +} + +// Move defines model for Move. +type Move struct { + Name *string `json:"name,omitempty"` + Value *int64 `json:"value,omitempty"` +} + +// Size defines model for Size. +type Size struct { + Unit *string `json:"unit,omitempty"` + Value *int64 `json:"value,omitempty"` +} + +// Unit defines model for Unit. +type Unit struct { + ID *string `bun:"id,pk" json:"_id,omitempty"` + Abilities []Ability `json:"abilities,omitempty"` + Bravery *int64 `json:"bravery,omitempty"` + Champion *string `json:"champion,omitempty"` + CommandAbilities []Attribute `json:"command_abilities,omitempty"` + DamageTable []DamageTable `json:"damage_table,omitempty"` + Description *string `json:"description,omitempty"` + GrandAlliance *string `json:"grand_alliance,omitempty"` + Keywords []string `json:"keywords,omitempty"` + Magic []Attribute `json:"magic,omitempty"` + MeleeWeapons []Weapon `json:"melee_weapons,omitempty"` + MissileWeapons []Weapon `json:"missile_weapons,omitempty"` + Models *int64 `json:"models,omitempty"` + Move *Move `json:"move,omitempty"` + Name string `json:"name"` + Points *int64 `json:"points,omitempty"` + Save *int64 `json:"save,omitempty"` + Size *Size `json:"size,omitempty"` + Wounds *int64 `json:"wounds,omitempty"` +} + +// Warscroll defines model for Warscroll. +type Warscroll struct { + ID *string `bun:",pk" json:"_id,omitempty"` + Allegiance *Allegiance `json:"allegiance,omitempty"` + AllegianceID *string `json:"allegiance_id,omitempty"` + BattlefieldRole *string `json:"battlefield_role,omitempty"` + GrandAlliance *GrandAlliance `json:"grand_alliance,omitempty"` + GrandAllianceID *string `json:"grand_alliance_id,omitempty"` + Name *string `json:"name,omitempty"` + Notes *string `json:"notes,omitempty"` + Points *int64 `json:"points,omitempty"` + Size *int64 `json:"size,omitempty"` +} + +// Weapon defines model for Weapon. +type Weapon struct { + ID *string `bun:",pk" json:"_id,omitempty"` + Attacks *int64 `json:"attacks,omitempty"` + Damage *int64 `json:"damage,omitempty"` + Name *string `json:"name,omitempty"` + Range *int64 `json:"range,omitempty"` + Rend *int64 `json:"rend,omitempty"` + ToHit *int64 `json:"to_hit,omitempty"` + ToWound *int64 `json:"to_wound,omitempty"` +} + +// GetAllegiancesParams defines parameters for GetAllegiances. +type GetAllegiancesParams struct { + // name of allegiance to filter by + Name *string `json:"name,omitempty"` + + // id of grand alliance to filter by + GrandAlliance *string `json:"grand_alliance,omitempty"` +} + +// GetCitiesParams defines parameters for GetCities. +type GetCitiesParams struct { + // name of city to filter by + Name *string `json:"name,omitempty"` +} + +// GetUnitsParams defines parameters for GetUnits. +type GetUnitsParams struct { + // name of unit to filter by + Name *string `json:"name,omitempty"` + + // grand alliance of unit to filter by + GrandAlliance *string `json:"grand_alliance,omitempty"` + + // grand strategy of unit to filter by + GrandStrategy *string `json:"grand_strategy,omitempty"` + + // points of unit to filter by + Points *int `json:"points,omitempty"` +} + +// GetWarscrollsParams defines parameters for GetWarscrolls. +type GetWarscrollsParams struct { + // name of warscroll to filter by + Name *string `json:"name,omitempty"` + + // points of warscroll to filter by + Points *int `json:"points,omitempty"` + + // battlefield_role of warscroll to filter by + BattlefieldRole *string `json:"battlefield_role,omitempty"` + + // size of warscroll to filter by + Size *string `json:"size,omitempty"` + + // notes of warscroll to filter by + Notes *string `json:"notes,omitempty"` +} + +// Response is a common response struct for all the API calls. +// A Response object may be instantiated via functions for specific operation responses. +// It may also be instantiated directly, for the purpose of responding with a single status code. +type Response struct { + body interface{} + Code int + contentType string +} + +// Render implements the render.Renderer interface. It sets the Content-Type header +// and status code based on the response definition. +func (resp *Response) Render(w http.ResponseWriter, r *http.Request) error { + w.Header().Set("Content-Type", resp.contentType) + render.Status(r, resp.Code) + return nil +} + +// Status is a builder method to override the default status code for a response. +func (resp *Response) Status(code int) *Response { + resp.Code = code + return resp +} + +// ContentType is a builder method to override the default content type for a response. +func (resp *Response) ContentType(contentType string) *Response { + resp.contentType = contentType + return resp +} + +// MarshalJSON implements the json.Marshaler interface. +// This is used to only marshal the body of the response. +func (resp *Response) MarshalJSON() ([]byte, error) { + return json.Marshal(resp.body) +} + +// MarshalXML implements the xml.Marshaler interface. +// This is used to only marshal the body of the response. +func (resp *Response) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + return e.Encode(resp.body) +} + +// GetAllegiancesJSON200Response is a constructor method for a GetAllegiances response. +// A *Response is returned with the configured status code and content type from the spec. +func GetAllegiancesJSON200Response(body []Allegiance) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetAllegiancesJSON404Response is a constructor method for a GetAllegiances response. +// A *Response is returned with the configured status code and content type from the spec. +func GetAllegiancesJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetAllegianceByIDJSON200Response is a constructor method for a GetAllegianceByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetAllegianceByIDJSON200Response(body Allegiance) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetAllegianceByIDJSON404Response is a constructor method for a GetAllegianceByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetAllegianceByIDJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetArmiesJSON200Response is a constructor method for a GetArmies response. +// A *Response is returned with the configured status code and content type from the spec. +func GetArmiesJSON200Response(body []Army) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetArmiesJSON404Response is a constructor method for a GetArmies response. +// A *Response is returned with the configured status code and content type from the spec. +func GetArmiesJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetArmyByIDJSON200Response is a constructor method for a GetArmyByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetArmyByIDJSON200Response(body Army) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetArmyByIDJSON404Response is a constructor method for a GetArmyByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetArmyByIDJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetCitiesJSON200Response is a constructor method for a GetCities response. +// A *Response is returned with the configured status code and content type from the spec. +func GetCitiesJSON200Response(body []City) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetCitiesJSON404Response is a constructor method for a GetCities response. +// A *Response is returned with the configured status code and content type from the spec. +func GetCitiesJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetCityByIDJSON200Response is a constructor method for a GetCityByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetCityByIDJSON200Response(body City) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetCityByIDJSON404Response is a constructor method for a GetCityByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetCityByIDJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetDocsJSON404Response is a constructor method for a GetDocs response. +// A *Response is returned with the configured status code and content type from the spec. +func GetDocsJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetGrandAlliancesJSON200Response is a constructor method for a GetGrandAlliances response. +// A *Response is returned with the configured status code and content type from the spec. +func GetGrandAlliancesJSON200Response(body []GrandAlliance) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetGrandAlliancesJSON404Response is a constructor method for a GetGrandAlliances response. +// A *Response is returned with the configured status code and content type from the spec. +func GetGrandAlliancesJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetGrandAllianceByIDJSON200Response is a constructor method for a GetGrandAllianceByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetGrandAllianceByIDJSON200Response(body GrandAlliance) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetGrandAllianceByIDJSON404Response is a constructor method for a GetGrandAllianceByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetGrandAllianceByIDJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetGrandStrategiesJSON200Response is a constructor method for a GetGrandStrategies response. +// A *Response is returned with the configured status code and content type from the spec. +func GetGrandStrategiesJSON200Response(body []GrandStrategy) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetGrandStrategiesJSON404Response is a constructor method for a GetGrandStrategies response. +// A *Response is returned with the configured status code and content type from the spec. +func GetGrandStrategiesJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetGrandStrategyByIDJSON200Response is a constructor method for a GetGrandStrategyByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetGrandStrategyByIDJSON200Response(body GrandStrategy) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetGrandStrategyByIDJSON404Response is a constructor method for a GetGrandStrategyByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetGrandStrategyByIDJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetHealthzJSON200Response is a constructor method for a GetHealthz response. +// A *Response is returned with the configured status code and content type from the spec. +func GetHealthzJSON200Response(body Health) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetHealthzJSON404Response is a constructor method for a GetHealthz response. +// A *Response is returned with the configured status code and content type from the spec. +func GetHealthzJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetUnitsJSON200Response is a constructor method for a GetUnits response. +// A *Response is returned with the configured status code and content type from the spec. +func GetUnitsJSON200Response(body []Unit) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetUnitsJSON404Response is a constructor method for a GetUnits response. +// A *Response is returned with the configured status code and content type from the spec. +func GetUnitsJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetUnitByIDJSON200Response is a constructor method for a GetUnitByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetUnitByIDJSON200Response(body Unit) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetUnitByIDJSON404Response is a constructor method for a GetUnitByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetUnitByIDJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetAbilitiesForUnitByIDJSON200Response is a constructor method for a GetAbilitiesForUnitByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetAbilitiesForUnitByIDJSON200Response(body []Ability) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetAbilitiesForUnitByIDJSON404Response is a constructor method for a GetAbilitiesForUnitByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetAbilitiesForUnitByIDJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetWarscrollsJSON200Response is a constructor method for a GetWarscrolls response. +// A *Response is returned with the configured status code and content type from the spec. +func GetWarscrollsJSON200Response(body []Warscroll) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetWarscrollsJSON404Response is a constructor method for a GetWarscrolls response. +// A *Response is returned with the configured status code and content type from the spec. +func GetWarscrollsJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// GetWarscrollByIDJSON200Response is a constructor method for a GetWarscrollByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetWarscrollByIDJSON200Response(body Warscroll) *Response { + return &Response{ + body: body, + Code: 200, + contentType: "application/json", + } +} + +// GetWarscrollByIDJSON404Response is a constructor method for a GetWarscrollByID response. +// A *Response is returned with the configured status code and content type from the spec. +func GetWarscrollByIDJSON404Response(body Error) *Response { + return &Response{ + body: body, + Code: 404, + contentType: "application/json", + } +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + // Get all allegiances + // (GET /allegiances) + GetAllegiances(w http.ResponseWriter, r *http.Request, params GetAllegiancesParams) *Response + // Get allegiance by id + // (GET /allegiances/{id}) + GetAllegianceByID(w http.ResponseWriter, r *http.Request, id string) *Response + // Get all armies + // (GET /armies) + GetArmies(w http.ResponseWriter, r *http.Request) *Response + // Get army by id + // (GET /armies/{id}) + GetArmyByID(w http.ResponseWriter, r *http.Request, id string) *Response + // Get all cities + // (GET /cities) + GetCities(w http.ResponseWriter, r *http.Request, params GetCitiesParams) *Response + // Get city by id + // (GET /cities/{id}) + GetCityByID(w http.ResponseWriter, r *http.Request, id string) *Response + // Get API documentation + // (GET /docs) + GetDocs(w http.ResponseWriter, r *http.Request) *Response + // Get all grand alliances + // (GET /grand-alliances) + GetGrandAlliances(w http.ResponseWriter, r *http.Request) *Response + // Get grand alliance by id + // (GET /grand-alliances/{id}) + GetGrandAllianceByID(w http.ResponseWriter, r *http.Request, id string) *Response + // Get all grand strategies + // (GET /grand-strategies) + GetGrandStrategies(w http.ResponseWriter, r *http.Request) *Response + // Get grand strategy by id + // (GET /grand-strategies/{id}) + GetGrandStrategyByID(w http.ResponseWriter, r *http.Request, id string) *Response + // Get health status + // (GET /healthz) + GetHealthz(w http.ResponseWriter, r *http.Request) *Response + // Get all units + // (GET /units) + GetUnits(w http.ResponseWriter, r *http.Request, params GetUnitsParams) *Response + // Get unit by id + // (GET /units/{id}) + GetUnitByID(w http.ResponseWriter, r *http.Request, id string) *Response + // Get abilities for unit by id + // (GET /units/{id}/abilities) + GetAbilitiesForUnitByID(w http.ResponseWriter, r *http.Request, id string) *Response + // Get all warscrolls + // (GET /warscrolls) + GetWarscrolls(w http.ResponseWriter, r *http.Request, params GetWarscrollsParams) *Response + // Get warscroll by id + // (GET /warscrolls/{id}) + GetWarscrollByID(w http.ResponseWriter, r *http.Request, id string) *Response +} + +// ServerInterfaceWrapper converts contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +// GetAllegiances operation middleware +func (siw *ServerInterfaceWrapper) GetAllegiances(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // Parameter object where we will unmarshal all parameters from the context + var params GetAllegiancesParams + + // ------------- Optional query parameter "name" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "name", r.URL.Query(), ¶ms.Name); err != nil { + err = fmt.Errorf("invalid format for parameter name: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "name"}) + return + } + + // ------------- Optional query parameter "grand_alliance" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "grand_alliance", r.URL.Query(), ¶ms.GrandAlliance); err != nil { + err = fmt.Errorf("invalid format for parameter grand_alliance: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "grand_alliance"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetAllegiances(w, r, params) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetAllegianceByID operation middleware +func (siw *ServerInterfaceWrapper) GetAllegianceByID(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // ------------- Path parameter "id" ------------- + var id string + + if err := runtime.BindStyledParameter("simple", false, "id", chi.URLParam(r, "id"), &id); err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "id"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetAllegianceByID(w, r, id) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetArmies operation middleware +func (siw *ServerInterfaceWrapper) GetArmies(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetArmies(w, r) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetArmyByID operation middleware +func (siw *ServerInterfaceWrapper) GetArmyByID(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // ------------- Path parameter "id" ------------- + var id string + + if err := runtime.BindStyledParameter("simple", false, "id", chi.URLParam(r, "id"), &id); err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "id"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetArmyByID(w, r, id) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetCities operation middleware +func (siw *ServerInterfaceWrapper) GetCities(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // Parameter object where we will unmarshal all parameters from the context + var params GetCitiesParams + + // ------------- Optional query parameter "name" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "name", r.URL.Query(), ¶ms.Name); err != nil { + err = fmt.Errorf("invalid format for parameter name: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "name"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetCities(w, r, params) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetCityByID operation middleware +func (siw *ServerInterfaceWrapper) GetCityByID(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // ------------- Path parameter "id" ------------- + var id string + + if err := runtime.BindStyledParameter("simple", false, "id", chi.URLParam(r, "id"), &id); err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "id"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetCityByID(w, r, id) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetDocs operation middleware +func (siw *ServerInterfaceWrapper) GetDocs(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetDocs(w, r) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetGrandAlliances operation middleware +func (siw *ServerInterfaceWrapper) GetGrandAlliances(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetGrandAlliances(w, r) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetGrandAllianceByID operation middleware +func (siw *ServerInterfaceWrapper) GetGrandAllianceByID(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // ------------- Path parameter "id" ------------- + var id string + + if err := runtime.BindStyledParameter("simple", false, "id", chi.URLParam(r, "id"), &id); err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "id"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetGrandAllianceByID(w, r, id) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetGrandStrategies operation middleware +func (siw *ServerInterfaceWrapper) GetGrandStrategies(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetGrandStrategies(w, r) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetGrandStrategyByID operation middleware +func (siw *ServerInterfaceWrapper) GetGrandStrategyByID(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // ------------- Path parameter "id" ------------- + var id string + + if err := runtime.BindStyledParameter("simple", false, "id", chi.URLParam(r, "id"), &id); err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "id"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetGrandStrategyByID(w, r, id) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetHealthz operation middleware +func (siw *ServerInterfaceWrapper) GetHealthz(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetHealthz(w, r) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetUnits operation middleware +func (siw *ServerInterfaceWrapper) GetUnits(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // Parameter object where we will unmarshal all parameters from the context + var params GetUnitsParams + + // ------------- Optional query parameter "name" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "name", r.URL.Query(), ¶ms.Name); err != nil { + err = fmt.Errorf("invalid format for parameter name: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "name"}) + return + } + + // ------------- Optional query parameter "grand_alliance" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "grand_alliance", r.URL.Query(), ¶ms.GrandAlliance); err != nil { + err = fmt.Errorf("invalid format for parameter grand_alliance: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "grand_alliance"}) + return + } + + // ------------- Optional query parameter "grand_strategy" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "grand_strategy", r.URL.Query(), ¶ms.GrandStrategy); err != nil { + err = fmt.Errorf("invalid format for parameter grand_strategy: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "grand_strategy"}) + return + } + + // ------------- Optional query parameter "points" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "points", r.URL.Query(), ¶ms.Points); err != nil { + err = fmt.Errorf("invalid format for parameter points: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "points"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetUnits(w, r, params) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetUnitByID operation middleware +func (siw *ServerInterfaceWrapper) GetUnitByID(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // ------------- Path parameter "id" ------------- + var id string + + if err := runtime.BindStyledParameter("simple", false, "id", chi.URLParam(r, "id"), &id); err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "id"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetUnitByID(w, r, id) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetAbilitiesForUnitByID operation middleware +func (siw *ServerInterfaceWrapper) GetAbilitiesForUnitByID(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // ------------- Path parameter "id" ------------- + var id string + + if err := runtime.BindStyledParameter("simple", false, "id", chi.URLParam(r, "id"), &id); err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "id"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetAbilitiesForUnitByID(w, r, id) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetWarscrolls operation middleware +func (siw *ServerInterfaceWrapper) GetWarscrolls(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // Parameter object where we will unmarshal all parameters from the context + var params GetWarscrollsParams + + // ------------- Optional query parameter "name" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "name", r.URL.Query(), ¶ms.Name); err != nil { + err = fmt.Errorf("invalid format for parameter name: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "name"}) + return + } + + // ------------- Optional query parameter "points" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "points", r.URL.Query(), ¶ms.Points); err != nil { + err = fmt.Errorf("invalid format for parameter points: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "points"}) + return + } + + // ------------- Optional query parameter "battlefield_role" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "battlefield_role", r.URL.Query(), ¶ms.BattlefieldRole); err != nil { + err = fmt.Errorf("invalid format for parameter battlefield_role: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "battlefield_role"}) + return + } + + // ------------- Optional query parameter "size" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "size", r.URL.Query(), ¶ms.Size); err != nil { + err = fmt.Errorf("invalid format for parameter size: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "size"}) + return + } + + // ------------- Optional query parameter "notes" ------------- + + if err := runtime.BindQueryParameter("form", true, false, "notes", r.URL.Query(), ¶ms.Notes); err != nil { + err = fmt.Errorf("invalid format for parameter notes: %w", err) + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "notes"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetWarscrolls(w, r, params) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +// GetWarscrollByID operation middleware +func (siw *ServerInterfaceWrapper) GetWarscrollByID(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // ------------- Path parameter "id" ------------- + var id string + + if err := runtime.BindStyledParameter("simple", false, "id", chi.URLParam(r, "id"), &id); err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{err, "id"}) + return + } + + var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := siw.Handler.GetWarscrollByID(w, r, id) + if resp != nil { + if resp.body != nil { + render.Render(w, r, resp) + } else { + w.WriteHeader(resp.Code) + } + } + }) + + handler(w, r.WithContext(ctx)) +} + +type UnescapedCookieParamError struct { + err error + paramName string +} + +// Error implements error. +func (err UnescapedCookieParamError) Error() string { + return fmt.Sprintf("error unescaping cookie parameter %s: %v", err.paramName, err.err) +} + +func (err UnescapedCookieParamError) Unwrap() error { return err.err } + +type UnmarshalingParamError struct { + err error + paramName string +} + +// Error implements error. +func (err UnmarshalingParamError) Error() string { + return fmt.Sprintf("error unmarshaling parameter %s as JSON: %v", err.paramName, err.err) +} + +func (err UnmarshalingParamError) Unwrap() error { return err.err } + +type RequiredParamError struct { + err error + paramName string +} + +// Error implements error. +func (err RequiredParamError) Error() string { + if err.err == nil { + return fmt.Sprintf("query parameter %s is required, but not found", err.paramName) + } else { + return fmt.Sprintf("query parameter %s is required, but errored: %s", err.paramName, err.err) + } +} + +func (err RequiredParamError) Unwrap() error { return err.err } + +type RequiredHeaderError struct { + paramName string +} + +// Error implements error. +func (err RequiredHeaderError) Error() string { + return fmt.Sprintf("header parameter %s is required, but not found", err.paramName) +} + +type InvalidParamFormatError struct { + err error + paramName string +} + +// Error implements error. +func (err InvalidParamFormatError) Error() string { + return fmt.Sprintf("invalid format for parameter %s: %v", err.paramName, err.err) +} + +func (err InvalidParamFormatError) Unwrap() error { return err.err } + +type TooManyValuesForParamError struct { + NumValues int + paramName string +} + +// Error implements error. +func (err TooManyValuesForParamError) Error() string { + return fmt.Sprintf("expected one value for %s, got %d", err.paramName, err.NumValues) +} + +// ParameterName is an interface that is implemented by error types that are +// relevant to a specific parameter. +type ParameterError interface { + error + // ParamName is the name of the parameter that the error is referring to. + ParamName() string +} + +func (err UnescapedCookieParamError) ParamName() string { return err.paramName } +func (err UnmarshalingParamError) ParamName() string { return err.paramName } +func (err RequiredParamError) ParamName() string { return err.paramName } +func (err RequiredHeaderError) ParamName() string { return err.paramName } +func (err InvalidParamFormatError) ParamName() string { return err.paramName } +func (err TooManyValuesForParamError) ParamName() string { return err.paramName } + +type ServerOptions struct { + BaseURL string + BaseRouter chi.Router + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +type ServerOption func(*ServerOptions) + +// Handler creates http.Handler with routing matching OpenAPI spec. +func Handler(si ServerInterface, opts ...ServerOption) http.Handler { + options := &ServerOptions{ + BaseURL: "/", + BaseRouter: chi.NewRouter(), + ErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + }, + } + + for _, f := range opts { + f(options) + } + + r := options.BaseRouter + wrapper := ServerInterfaceWrapper{ + Handler: si, + ErrorHandlerFunc: options.ErrorHandlerFunc, + } + + r.Route(options.BaseURL, func(r chi.Router) { + r.Get("/allegiances", wrapper.GetAllegiances) + r.Get("/allegiances/{id}", wrapper.GetAllegianceByID) + r.Get("/armies", wrapper.GetArmies) + r.Get("/armies/{id}", wrapper.GetArmyByID) + r.Get("/cities", wrapper.GetCities) + r.Get("/cities/{id}", wrapper.GetCityByID) + r.Get("/docs", wrapper.GetDocs) + r.Get("/grand-alliances", wrapper.GetGrandAlliances) + r.Get("/grand-alliances/{id}", wrapper.GetGrandAllianceByID) + r.Get("/grand-strategies", wrapper.GetGrandStrategies) + r.Get("/grand-strategies/{id}", wrapper.GetGrandStrategyByID) + r.Get("/healthz", wrapper.GetHealthz) + r.Get("/units", wrapper.GetUnits) + r.Get("/units/{id}", wrapper.GetUnitByID) + r.Get("/units/{id}/abilities", wrapper.GetAbilitiesForUnitByID) + r.Get("/warscrolls", wrapper.GetWarscrolls) + r.Get("/warscrolls/{id}", wrapper.GetWarscrollByID) + }) + return r +} + +func WithRouter(r chi.Router) ServerOption { + return func(s *ServerOptions) { + s.BaseRouter = r + } +} + +func WithServerBaseURL(url string) ServerOption { + return func(s *ServerOptions) { + s.BaseURL = url + } +} + +func WithErrorHandler(handler func(w http.ResponseWriter, r *http.Request, err error)) ServerOption { + return func(s *ServerOptions) { + s.ErrorHandlerFunc = handler + } +} + +// Base64 encoded, gzipped, json marshaled Swagger object +var swaggerSpec = []string{ + + "H4sIAAAAAAAC/9RaW2/bOBP9KwK/72EXcCK3DfbBb95eg93uFpsGfSgKg5bGNhteVJJKohb57wtSknWj", + "LKqxs/ZTU2s4Q845Z4aU+ANFgiWCA9cKzX4gFW2AYfvnfEko0Zn5M5EiAakJ2AcxqEiSRBPBzX91lgCa", + "IaUl4Wv0MEEcM3A8eJiUv4jlV4i0MZ1TCmuCeQTdMAsSd71M0P3ZWpzBvZb4TOO1tVymHM0QiSfJjQ0z", + "NMG1xDxeYEq3kTsmTEiN6UICpmzkIiV8S4mEGM0+51ZfXAuXLNvnknumM0EpJzmyRAOzf/xfwgrN0P/C", + "CvmwgD285sROr3CDpcTZiEVpLcky1Q4we+d3i2lqn6yEZFibRXH92wXauidcwxqkmz8vnQQ9HHNGUPsV", + "ZngNH/GS7pXbjPDFnUh5rBYqXa3AYuKRPUPpWxjC/72xeZggG2GhJY5uFolQpEzIT4H0WkohzWi4xyzJ", + "0xGJGNDsYnoxQQyUwmsz5C+hgzcmshnVTFhu35zAi+fudZb+hsRpfVb2Lka/NZViXisUj4Px8TTz0qGd", + "9ZWWWMM6O5lZvwNM9aY7XaWxTtWw48LO5fp9Qf0nqUlX5LsjmKnDBwh2XbjdV3nBtukXbrxaRrlN6HSN", + "CVpKfAsy86xP0QazpI9bkWDMNu3x89s2JccMY1ukF7qs0l4e65Xd5fPxu48byO6EjJuL7Fi1AzO8JtF+", + "8sKAAizuACeC+6f6k7V3+iNKEbpXjyIGqg7Q+nqrQiJIsUn2iKjwLfiaFvVi1+RsTSn7svKtFl5l9xOW", + "KpKC0v01CtzY1e8kYWXZGOeMbCoK1prCigCNF1JQ8BTYrik0W3xneN9MemnChQa1BwIVrPiprlDIZn+A", + "ao2jG9+p50XV07g3jxJzbycSuO8uWIvFJm+ZfsZWcT8JhPmJ8JXoHJrR/MNloBKIyIpE2PwWrIQMMA/m", + "4ir45/XVx8BY/HLNxWpFIoLpr2iCKImAK6i2Luj95Uc0QamkaIY2WidqFoYiAa5EKiM4F3IdFoNUaGzN", + "FIk2skEmkCPGLUiVT/HZ+fR8akYYhzghaIZenD87n6IJSrDeWDKElWLt/9egu2t9CzrAlAZ1W+tV2pVf", + "xrnNvPE4wRIz0CAVmn1uezSrD8Sq5jHQIlgRqkEGywyZrKMZ+paazUdJsfyfSfGGw7mdbMchsYli60FQ", + "1gOfSK0CtCvmF0NeZXpinsHn02l+3OEauE0mThJakCT8qnJVV/78Wn2jyrbO9u0dC/r7D2N1Mb0YNZFd", + "8fMDoCNU7cBnSl7KGDbbRSdljEWdb+EPEj8Mka6kxzILSLybdb9nl6+GiJcTokk7CTqVvGSCkUZFBBuz", + "6sJapnBIMvhy4JgxbyKWgy4Z8akvuZkL5PLJE0hNsuzURJZnp5ZqD2lJlu0QlWTZCDkZXyckJIvw8SJa", + "IWMRjban5Z3iKcwcYL4sn3i15IjobC/N+Eka40vni4ujVmsBVA3bYbVaUHrVapLgr9YS4BNRa47w0SJa", + "Q8YiGotot1bNlj0WUcqAaztLF6KvjJfBpGq41+FGM9pc4/acsyQcW8m28TrWZHZzY3Nqd+Nn5W58uBQ2", + "9/vOmth4Z/A0G4vOa4oTqlntjLpgGa5irXNYbz1rZMq/sHWPeSdS4lrMOFomOPGrUUHlH6yIt0RrA/po", + "cFU3eSKRbj+8naJIazl1QuMr02JENiDTMldjZbp1f2Iyrbhx5DJt4We5sLEfaL/vRD+3CYpvsQ7Y3xVO", + "Dpjp4kPy8aa4mSSb2+01nZ11L7dyZPW6eOB1RjNeDvPCtFXiR8Qa8cq0J+qWsaOjliPHRc2/5oyJVnz/", + "cUSpviE8ybG355bXMXennPmVVIb7kEWlt/uYFPg3nRLhE2k1Ob5Hi2cNmRagYeN6R38pLK3sV7PdQM9L", + "2zdCPgb0ZtCjoMDjruccr9z70LVkuSuvKwx3y5qpgxif6k+9+ubW32GaZ9VQRgXy6SqdWO17FKOjdi5i", + "jFqqIt/Hh7Q3IkaFsVcxxiNnL3D858Kt7uWcVqeuqa4l2OGeXeHUW8+3afEv5A30T6SF19A/WrTbaNnh", + "CuStG4w/RYRpkD9v3FqZhSEW6gwn5Jwam41QZnvaHv9BijiN7GUZhxNV8xIJhh6+PPwbAAD//+u73f7c", + "MgAA", +} + +// GetSwagger returns the content of the embedded swagger specification file +// or error if failed to decode +func decodeSpec() ([]byte, error) { + zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) + if err != nil { + return nil, fmt.Errorf("error base64 decoding spec: %s", err) + } + zr, err := gzip.NewReader(bytes.NewReader(zipped)) + if err != nil { + return nil, fmt.Errorf("error decompressing spec: %s", err) + } + var buf bytes.Buffer + _, err = buf.ReadFrom(zr) + if err != nil { + return nil, fmt.Errorf("error decompressing spec: %s", err) + } + + return buf.Bytes(), nil +} + +var rawSpec = decodeSpecCached() + +// a naive cached of a decoded swagger spec +func decodeSpecCached() func() ([]byte, error) { + data, err := decodeSpec() + return func() ([]byte, error) { + return data, err + } +} + +// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. +func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { + var res = make(map[string]func() ([]byte, error)) + if len(pathToFile) > 0 { + res[pathToFile] = rawSpec + } + + return res +} + +// GetSwagger returns the Swagger specification corresponding to the generated code +// in this file. The external references of Swagger specification are resolved. +// The logic of resolving external references is tightly connected to "import-mapping" feature. +// Externally referenced files must be embedded in the corresponding golang packages. +// Urls can be supported but this task was out of the scope. +func GetSwagger() (swagger *openapi3.T, err error) { + var resolvePath = PathToRawSpec("") + + loader := openapi3.NewLoader() + loader.IsExternalRefsAllowed = true + loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { + var pathToFile = url.String() + pathToFile = path.Clean(pathToFile) + getSpec, ok := resolvePath[pathToFile] + if !ok { + err1 := fmt.Errorf("path not found: %s", pathToFile) + return nil, err1 + } + return getSpec() + } + var specData []byte + specData, err = rawSpec() + if err != nil { + return + } + swagger, err = loader.LoadFromData(specData) + if err != nil { + return + } + return +} diff --git a/web/index.html b/web/index.html index 8f46d19..773c583 100644 --- a/web/index.html +++ b/web/index.html @@ -3,7 +3,7 @@ - Warhammer Age of Sigmar API (Unofficial) + AoS API (Unofficial)