# oos-service

Central Go backend for owned and operated (O&O) sites. Replaces the legacy per-site P├── internal/                  # Internal packages
│   ├── utils/                # Shared helpers
│   ├── cache/                # In-memory cache implementation
│   └── cms/                  # CMS API service layer
│
├── middlewares/              # Request middleware chain
│   ├── client_config.go      # Host → config resolution
│   └── logging.go            # Access log (Apache-style)
│
├── routes/                   # HTTP handlers
│   ├── homepage.go
│   ├── article.go
│   ├── articles_list.go
│   ├── data.go               # Data API handlers (/data/*)
│   ├── robotstxt.go
│   └── notfound.go with a single service that manages multiple sites through hostname-based client configuration.

## Deploying to the dev server

`ssh dev-server 'sudo -u devgroup /var/www/go-projects/oos-service/deploy/dev/deploy.sh'` updates, builds and restarts all three repos. See [deploy/dev/README.md](deploy/dev/README.md).

## Local Setup

### Prerequisites

- **Go 1.21+** - `brew install go` or [golang.org/dl](https://go.dev/dl/)
- **make** - included with Xcode CLI tools on macOS

### Clone and build

```bash
git clone git@bitbucket.org:imediabrands/oos-service.git
cd oos-service
go mod tidy
make build
```

### Configure /etc/hosts

Add entries so your browser resolves the O&O domains to localhost:

```
0.0.0.0 bodytheory.com
0.0.0.0 pointwines.com
0.0.0.0 webcrawlers.com
0.0.0.0 centerweightloss.com
```

Edit with `sudo nano /etc/hosts` or `sudo vim /etc/hosts` or use a tool such as Gas Mask.

### Run

```bash
make run
```

The server starts on `0.0.0.0:8080` (configurable in `config.json`).

## Testing

Visit any of the configured domains in your browser at port 8080:

```
http://bodytheory.com:8080/
http://pointwines.com:8080/
```

Each domain resolves to a different client config, so the same endpoint returns site-specific responses depending on the `Host` header.

## Data API

The service provides cached access to external CMS data via `/data/*` endpoints:

- `GET /data/categories` - Get all categories
- `GET /data/category-articles/:catId` - Get articles by category
- `GET /data/article/:id` - Get article details

**Quick Start:**

```bash
# Configure API key in config.json
{
  "cms_api_key": "your-api-key-here",
  "cms_cache_ttl": "10m"
}

# Test endpoints
./test-data-api.sh

# Or test manually
curl http://localhost:8080/data/categories
```

**Cache warming:** with `"cms_warm": true` the service loads every site's categories, category lists and 24 newest articles in the background at startup, then again every half `cms_cache_ttl` (after a minute if a pass can't start), so the first visitor doesn't wait for the CMS. It is on in `environments/uat`, `environments/prod` and on the dev server (`deploy/dev/deploy.sh`), and off for a local `make run`.

**Documentation:**
- [DATA_API.md](./DATA_API.md) - Complete API reference
- [INTEGRATION_GUIDE.md](./INTEGRATION_GUIDE.md) - Frontend integration guide

## Directory sites (business listings)

Sites whose client config has `"template": "directory"` (localpages, cured, customercompany, qualifiedlawyers, businessknows, ilocalbook, accoona) serve business listings from `internal/listings` beside the CMS articles.

**Listings store.** With `listings_api_url` and `listings_api_key` in the config (dev and uat have the dev URL), listings come from the business listing API (`internal/listings/api.go`): one call per search, listing, state list or city list, each answer kept in memory for an hour. The request's client name is sent as `site`, so verified listings (ids `lp-{n}`, URLs `/{st}/{city}/lp-{n}-{slug}`) show only on localpages. A site category group is sent as the API's `categories` (its first 300 terms). getCities is cleaned before use: names that aren't city names (zips, addresses, HTML, double-decoded text) and cities without coordinates are dropped, and of the spellings with one slug the one with the most listings is kept. `loc` with a state is matched against that list; a bare city doesn't resolve (the API lists cities by state). Nearby listings are a search of the listing's city for its first category. Without the API keys, the global config key `listings_jsonl_path` names a JSON Lines import, loaded once at startup. Neither, or a file that fails to load (logged), leaves the store disabled: directory pages answer 503 (`Retry-After: 3600`, noindex) and the API `listings_unavailable`. The search, location and nearby rules below are the JSONL store's.

**Import format.** One JSON object per line, in the legacy DB's field names: `id, business_name, address, city, state, zip, lat, lon, phones (array of "(703) 723-8440 (Main)" or {number,label}), website, email, category (comma list), description, business_hour, payment_options (comma list), special_offer, special_offer_url, image (array), yext_id, record_id, attribution, suppression_id, change_code`, plus `business_hour` (live's `Monday : 8:00 AM - 5:00 PM<br>...`), `services`, `products`, `video` (YouTube URLs) and an optional `group` (the record's top-level category group). The API's listing adds `hours` (one line per day), `services`, `products`, `videos` (YouTube ids) and `yextId`. On load: values are trimmed (inner whitespace collapsed), lists split on commas without empty items, `website~~https://x||https://x` reads as `https://x` and a bare `www.x.com` as `https://www.x.com`, http images on a.mktgcdn.com / www.yext-static.com become https, phones are formatted `(AAA) BBB-CCCC` (numbers without 10 digits are dropped), and records with a `suppression_id`, `change_code` "D", a non-numeric id, or no name, city or US state are skipped. The first record of an id wins. `email` is never served.

**Search.** The keyword matches the name and categories (case-insensitive, every word must match; empty matches every business). The location is the exact city and state (`los-angeles` = `Los Angeles`), or with `directory.radiusMiles` every listing within that distance of the city's centre (the mean of its listings' coordinates), nearest first. Order: Yext-enriched records first, then name A to Z. A search (`/search?s=`, `/data/listings/search`) or browse slug naming a site category (its label, slug or keyword, any case) searches that category; a category with `keywords` is a category group and finds the listings in whose name and categories every word of one of its terms (or of its keyword) starts a word, in any order (`Pet Sitting` matches "Pet & Animal Sitting", `Appliance Dealers` "Home Appliances Dealers", `Arts` doesn't match "Auto Parts"), or whose `group` is its label. A group's members are worked out once per process, at its first search (one scan of every listing, on a worker per CPU), then each search only tests them. `loc` is read by the store's `ResolveLocation`: "City, ST", "ST, City", "ST,City/", "City ST", a 5-digit zip or a bare city.

**Data API.**
- `GET /data/listings/search?s={keyword}&loc={location}&page={n}&pageSize={n}`: `{keyword, category, location: {city, state, label, path}, listings, total, page, pageSize, totalPages}`. `category` is the slug of the site category `s` names, else "". `loc` empty or unresolvable means `directory.defaultLocation`. The page size is `directory.pageSize`; `pageSize` can only make it smaller.
- `GET /data/listings/states`: `{states: [{code, name, path, count}]}`, the states with listings, A to Z.
- `GET /data/listings/cities?state={st}`: `{state: {code, name, path}, cities: [{name, slug, path, count}]}`, A to Z. Unknown state or none with listings: 404 `{"error":"not_found"}`.
- `GET /data/listings/{id}`: `{listing, nearby}` (nearby: same city, a shared category, up to `directory.nearbyCount`). Unknown id: 404 `{"error":"not_found"}`.
- `Cache-Control: public, max-age=600`; store unavailable: 503 `{"error":"listings_unavailable"}` with `no-store`. Other sites: 404.
- `GET /data/places/{st}` and `/data/places/{st}/{citySlug}`: `{title, paragraphs, sections?, sourceUrl, license: "CC BY-SA 4.0"}`, the state or city text as `directory.placeText` says (`sections` only for state `"full"`). Off, not a directory site, or no text: 404 `{"error":"not_found"}`. `Cache-Control: public, max-age=86400`.
- Article results on the search page use the existing `GET /data/articles?q={s}&page={n}&limit={n}`.

**Place text.** `places/{st}.json` (lowercase state code), Wikipedia text, loaded once at startup from `/opt/oos-service/places` or `places/` in the checkout (a missing directory means no place text):
```json
{ "state": { "code": "VA", "name": "Virginia", "title": "Virginia", "sourceUrl": "https://en.wikipedia.org/wiki/Virginia",
             "intro": ["..."], "sections": [ { "heading": "History", "paragraphs": ["..."] } ] },
  "cities": { "ashburn": { "name": "Ashburn", "title": "Ashburn, Virginia", "sourceUrl": "...", "intro": ["..."] } } }
```

**URLs.** A path whose first segment is a US state code (50 states + dc) is a directory URL on these sites; anything else keeps the article routing.
- `/{st}` state page (its cities), `/{st}/{city}` city page, `/{st}/{city}/{category}[/{n}]` browse (a `directory.categories` slug, or any slug searched with hyphens as spaces), `/{st}/{city}/{id}-{slug}` listing, `/search?s=&loc=&page=` results, `/categories`, `/categories/{slug}` (a category group, i.e. a site category with `keywords`: its subcategories, from config), `/states`.
- Each 301s in one hop to its canonical form: lowercase state, city slug (`/CA/Los%20Angeles/...` and `/ca/los+angeles/...` → `/ca/los-angeles/...`), no trailing slash, `/1` dropped, and a listing's own URL for a wrong state, city or slug. `legacyUrls.redirects` targets that are directory URLs are canonicalised the same way, and (on directory sites only) targets that are article URLs go to the article's canonical URL, a deleted or another site's article being a 404; that CMS lookup is cut off after 2 s and the redirect then goes to the target as it is. Other sites redirect to the target as it is. On every site a target that would leave the site (starting `//` or `/\`, also percent-encoded) is a 404. Legacy `/search?search=` / `keyword=` / `q=` 301 to `s=`; a legacy redirect to `/search` whose query already has `s` drops them. `/VA` and `/va/` 301 to `/va`, `/states/` to `/states`, `/categories/Food-And-Dining` to `/categories/food-and-dining` (query dropped).
- 404: unknown listing id, a city no listing is in, a state with no cities (in any spelling, no 301 first), a page past the last, a browse slug that isn't a `directory.categories` slug and finds no listing (in any spelling, so no 301 first), an unknown `/categories/{slug}` or one of a category without `keywords`. An article-route URL the CMS doesn't have whose category isn't the site's (e.g. `/business/41625316`) is a 404 here, not the other sites' 301 home.
- `legacyUrls.listings`: regexps whose group 1 is a listing id (e.g. `"^/business/([0-9]+)-[^/]*/?$"`), tried before every other legacy rule and the article routing: a listing 301s to its URL (query dropped), an unknown id is a 404, an unavailable store the 503 page.

**Client config keys** (besides the usual site-template keys):
```json
"directory": {
  "defaultLocation": { "city": "Ashburn", "state": "VA" },
  "pageSize": 10,
  "nearbyCount": 5,
  "radiusMiles": 15,
  "categories": [ { "label": "Food & Dining", "slug": "food-and-dining", "keyword": "food and dining",
                    "keywords": ["Pizza", "Thai Restaurants"] } ],
  "home": { "categoryCount": 12, "nearbyCategory": "hotels", "nearbyCount": 4, "articleCount": 4,
            "states": [ { "code": "AL", "label": "Alabama" } ],
            "locations": [ { "label": "Boston", "path": "/ma/boston", "image": "https://..." } ] },
  "seo": { "indexBrowse": false, "indexDetail": false, "indexCity": false, "indexState": false, "indexCategory": false },
  "placeText": { "state": "intro", "city": "intro" },
  "yextPublisherId": "EAzeX9WdJk",
  "newsletter": true,
  "searchArticles": false
}
```
The whole block is also passed to the frontend. `radiusMiles` (default 0, the exact city) widens searches and browse pages to nearby towns. `keywords` makes a category a category group (see Search). `seo.*` lets search engines index browse, listing, city, state (`/{st}`, `/states`) and category (`/categories/{slug}`) pages (default noindex,follow); results are always noindex,follow. `placeText.state` is `"intro"`, `"full"` (with the article's sections) or off; `placeText.city` `"intro"` or off. `home.states`, `home.locations`, `yextPublisherId` (Yext pixels), `newsletter` (newsletter band) and `searchArticles` (article results on the search page) are read by the frontend only.

Other keys used by directory sites (any site may set them):
- `google_adsense_account`: `<meta name="google-adsense-account" content="...">` on every page (e.g. `"sites-2288675768043065"`).
- `headbid_aff_id`: one numeric id, or several joined by `_` (`"16678_127594_127595"`), passed verbatim to the Headbid monitor script.
- `shared.shop.affiliate`: the shop affiliate; the server-side product fallback reads it, then the older top-level `shop_affiliate`.
- `sitemapPages` may list `/categories` and `/states` on directory sites.

`seoMeta.<page>.title` / `.description` set each page's head, with the tokens `{keyword}` `{Keyword}` (a site category's label, else the keyword in ucwords) `{location}` `{city}` `{state}` `{stateName}` `{name}` `{category}` `{page}` `{displayName}`. Defaults:
- `listingResults`, `listingBrowse`: `{Keyword} in {location} - {displayName}` (browse adds ` - Page {page}` from page 2 unless the pattern has `{page}`)
- `listingDetail`: `{name} - {city}, {state} - {displayName}`; description: the listing's description cut to 155 characters on a word, else `{name}, {address}, {city}, {state} {zip}.`
- `listingCity`: `Businesses in {location} - {displayName}`
- `categories`: `Categories - {displayName}`
- `listingState`: `Businesses in {stateName} - {displayName}`
- `listingStates`: `Browse by state - {displayName}`
- `listingCategory`: `{category} - {displayName}`

A description without a pattern is the title. Listing pages carry LocalBusiness JSON-LD (name, address, telephone, url, geo, image, description, openingHours as `Mo 08:00-17:00`, paymentAccepted), og:image = the listing's first image, and a Home > City > category > name BreadcrumbList. There are no listing sitemaps.

## Shop sites

Sites whose client config has `"template": "shop"` (sparknoes, beyondcheap, brandzones) serve the commonshop catalogue at the legacy shop's URLs, beside the CMS blog. `/` is the usual homepage shell (`seoMeta.home`); the frontend renders every page from the URL. Other sites route these URLs as before.

**URLs.**
- `/search?keyword=&master_category=&category=&brand=&prices=&availability=&sort=&page=`: the listing. A non-canonical query 301s once to its canonical form: keys in that order, form-encoded (`Home+%26+Kitchen`), empty values, unknown keys (`per_page`...) and repeats dropped, `page` only above 1, `prices` only 1-5, `availability` not `0`, `sort` only `price` / `price-desc`. Legacy values are decoded: `-sp--and--sp-` and `--and--` to ` & `, `-sp-` to a space, `-obl-` to `'`, and beyondcheap's raw `&` (`master_category=Home & Kitchen`) joined back. A master category becomes the API's own name when its slug matches one (`home-and-kitchen` → `Home & Kitchen`); a category with a `-` between words becomes the API's spelling of it (`Vacuum-Food-Sealers` → `Vacuum Food Sealers`, `T-Shirts` stays); a value still unmatched has such a `-` read as a space. `/search/` 301s to `/search` on every site.
- `/product_detail/{sku}/{slug}[/]`: the product page. The slug is ignored; the canonical slug is `1` with `shared.shop.productSlug: "index"`, else the product name as the frontend's `titleToSlug` makes it. The API's 404 is the not-found page; no answer (400 for an affiliate it doesn't know, 5xx, timeout) is the shell with a generic title, noindex, `Cache-Control: no-store`. `/product_detail/{sku}` without a slug is a 404, as on live.
- `/deals`, `/top-brands`, `/categories`: only when `shared.shop.pages.{deals,topBrands,categories}` exists (title from its `title`), else routed as before (a 404). `/deals/` and `/top-brands/` 301 to them.

**Head.** `seoMeta.<page>` patterns, tokens `{category}` `{query}` `{name}` `{brand}` `{description}` `{page}` `{displayName}`; a description without a pattern is the title:
- `shopCategory` (a listing with only `master_category` and/or `category`, maybe `page`): `{category} - {displayName}` (the category, else the master category; ` - Page {page}` from page 2 unless the pattern has `{page}`). Indexed, canonical to itself, Home > master category > category BreadcrumbList.
- `shopSearch` (any other listing): `{query} - {displayName}` (keyword, else brand, category, master category, else "Search"). noindex,follow, canonical without `sort`.
- `shopProduct`: `{name} - {displayName}`; description `{description}` (the product's, cut to 155 characters on a word). Indexed, og:image, Product JSON-LD (name, image, description, sku, brand, gtin8/12/13/14 by length and mpn from `feature`, Offer with price, currency, availability, url), Home > master category (`/search?master_category=X`) > category (`/search?master_category=X&category=Y`) > name BreadcrumbList; the product lookup waits up to 7s.
- `deals`, `topBrands`, `categories`: `{page title} - {displayName}`.

**Sitemap.** `/sitemap_pages.xml` adds the site's `/deals`, `/top-brands`, `/categories` and the master category listings (from `getMasterCategories`); the CMS category sitemaps are as on other sites.

**Shop API.** `/data/shop/*` and the pages share a 5-minute in-process cache of the API's 200 and 404 answers (by URL, so by affiliate too; at most 2000 entries) and an 8s upstream timeout (below the 10s WriteTimeout). `GET /data/shop/suggest?keyword=` answers `{"success":true,"data":[]}` until the global config sets `shop_suggest_path` (e.g. `/commonshop/suggest`), then proxies `{shop_api_base_url}{shop_suggest_path}?keyword=`.

**Deals.** `GET /data/shop/deals` (a site with `shared.shop.pages.deals`, else 404): `{"success": true, "partial": bool, "data": [product_details...]}`, the live products of `pages.deals.skus` in config order, all at once. Each SKU's product, or its 404 (gone, left out), is kept 6 hours; a failed lookup is retried after 5 minutes and never counts as gone. Lookups run 6 at a time in the background: at startup, every 10 minutes for what expired, and when a request finds SKUs due, so a request never waits. `partial` is true while some SKU isn't known (then `Cache-Control: no-store`).

**No CMS, no CMS content.** A shop site the CMS doesn't list (beyondcheap) gets none of the CMS fallbacks that read an unlisted domain as every site: `/data/categories` is `{"data":{"<domain>":[]}}`, the article data endpoints are empty / `{"data":false}`, article and category URLs (`/blog/{id}-x`, `/article/{id}`, `/articles/category/{id}`) are 404s, and `/sitemap.xml` has no category sitemaps. `/sitemap` is a 404 on a shop site without `pages.sitemap` content, and isn't in its `sitemap_pages.xml`.

**Legacy URLs.** `/index.php?/{path}[&query]` 301s to `/{path}[?query]` (before `legacyUrls`); `/search?price=N` reads as `prices=N`; with `productSlug: "index"` a non-digit slug 301s to `/product_detail/{sku}/1`.

**Category paths (any site).** `shared.categoryPaths: {"<CMS category name>": "<slug>"}` serves a CMS category at that slug instead of its name's (brandzones: `{"Blogs": "blog"}` → `/blog`, `/blog/{id}-{slug}`, `/sitemap_blog.xml`); the name's own slug is then no page and its article URLs 301 to the new one.

## Project Structure

```
oos-service/
├── main.go                    # Entry point — config, router, middleware chain, server
├── config.json                # Local dev config (viper reads from CWD)
├── Makefile                   # build, run, test, fmt, vet, clean
│
├── client_configs/            # Per-site backend-level overrides (more to come)
│   ├── site_to_client.json    # hostname → client key mapping
│   ├── bodytheory.json
│   ├── centerweightloss.json
│   ├── pointwines.json
│   └── webcrawlers.json
│
├── environments/              # Environment-specific configs
│   ├── dev/config.json
│   ├── prod/config.json
│   └── global/global.json
│
├── healthchecks/              # /health-check and /health-check/probe
├── internal/utils/            # Shared helpers
├── middlewares/               # Request middleware chain
│   ├── client_config.go       # Host → config resolution
│   └── logging.go             # Access log (Apache-style)
│
├── routes/                    # HTTP handlers
│   ├── homepage.go
│   ├── article.go
│   ├── articles_list.go
│   ├── robotstxt.go
│   └── notfound.go
│
└── init/
    └── oos-service.service    # systemd unit for deployment
```

## Adding a New Site

1. Add hostname → client entries in `client_configs/site_to_client.json`
2. Create `client_configs/<client>.json` with site-specific overrides
3. Add `0.0.0.0 <domain>` to your `/etc/hosts` for local testing
4. Restart the server (configs are loaded at startup)
