Split the job tracker out of web_server into its own app
Test and publish / test (push) Successful in 6m39s
Test and publish / publish (push) Failing after 0s

The applications tracker, leads inbox, email pipeline and capture userscript
move here from web_server's backend, Python service and Vue app, as one Go
binary that serves its own Vue SPA under /jobs/.

- The Go services, resolvers and tests move over almost unchanged.
- The three Claude calls are ported from Python to Go (internal/claude),
  with the same prompts, per-model request shaping and error messages.
- There is no login: internal/auth asks the site backend's
  /auth/validate-admin with the visitor's cookies, and relays refreshed
  cookies back.
- A Settings page replaces the admin-panel capture token card and adds the
  Microsoft sign-in link and a manual email sync.
- The userscript is 2.0.0, at /jobs/, and migrates a saved API base.
- Dockerfile, a standalone compose with Postgres, Makefile, and a Gitea CI
  workflow that tests and publishes the image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 16:24:16 +01:00
co-authored by Claude Opus 5.5
commit 67cb8137f9
88 changed files with 22715 additions and 0 deletions
+83
View File
@@ -0,0 +1,83 @@
package handlers
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
// REST endpoints for the job-application email pipeline: a manual
// admin-triggered sync, and the OAuth redirect target (which has to be REST
// because Microsoft redirects a browser to it).
// TriggerEmailSync backs the admin-only POST /api/email/sync and runs one sync
// synchronously, so the response reflects the result. If the scheduler is
// mid-sync the service refuses via TryLock and this returns 500.
func (store *Store) TriggerEmailSync(ctx *gin.Context) {
// A nil HTTPClient is the service's readiness flag — see
// services.EmailSyncService.
if store.EmailSync == nil || store.EmailSync.HTTPClient == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured or not authenticated"})
return
}
err := store.EmailSync.SyncEmails(ctx.Request.Context())
if err != nil {
log.Printf("[EmailSync] Manual sync error: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "sync failed", "details": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "sync completed"})
}
// CompleteEmailAuth handles Microsoft's OAuth redirect to
// GET /api/email/callback and stores the resulting token.
//
// The route is unauthenticated (Microsoft's redirect carries no site cookie),
// which is safe only because the code is worthless without the app's client
// secret. Note that completing auth here does not start the scheduler, which
// only checks readiness at start-up — a restart is needed for that.
func (store *Store) CompleteEmailAuth(ctx *gin.Context) {
if store.EmailSync == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured"})
return
}
code := ctx.Query("code")
if code == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "missing authorization code"})
return
}
if err := store.EmailSync.CompleteAuth(ctx.Request.Context(), code); err != nil {
log.Printf("[EmailSync] Auth completion error: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "authentication failed"})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "email authentication successful"})
}
// EmailSyncStatus backs the admin-only GET /api/email/status, which the
// settings page reads to say whether mail is being read and, on the Graph
// backend before sign-in, to offer the Microsoft authorisation link. Until
// the tracker had a page of its own that link was only printed to the log.
func (store *Store) EmailSyncStatus(ctx *gin.Context) {
if store.EmailSync == nil || store.EmailSync.Config == nil {
ctx.JSON(http.StatusOK, gin.H{"backend": "", "enabled": false, "ready": false})
return
}
svc := store.EmailSync
status := gin.H{
"backend": svc.Config.Backend,
// Enabled is the timer; a ready service can still be synced by hand.
"enabled": svc.Config.Enabled,
"ready": svc.HTTPClient != nil,
}
if svc.HTTPClient == nil && svc.OAuthConfig != nil {
status["authUrl"] = svc.AuthURL()
}
ctx.JSON(http.StatusOK, status)
}
+233
View File
@@ -0,0 +1,233 @@
package handlers
import (
"context"
"errors"
"log"
"net/http"
"strings"
"time"
"adam-french.co.uk/job-tracker/internal/claude"
"adam-french.co.uk/job-tracker/internal/models"
"adam-french.co.uk/job-tracker/internal/services"
"github.com/gin-gonic/gin"
)
// Job capture: the three endpoints behind web/public/job-capture.user.js,
// which adds the posting open in the browser to the job tracker.
//
// These are REST, and token-authenticated, because the caller is a userscript
// running on someone else's origin (linkedin.com, an ATS). The auth cookies
// are SameSite=Lax and never accompany such a request, so the GraphQL
// mutations, which rely on them, are out of reach from there.
//
// The token is deliberately narrow: it opens these routes and nothing else,
// so a token leaked from the browser can add rows to the tracker and spend
// Claude calls, but cannot read the tracker, edit other data or log in.
//
// The Claude call lives in internal/claude (posting.go); everything touching
// the database stays here.
const (
// maxCaptureBody bounds a capture request. A long posting is tens of
// kilobytes of text; the userscript trims the page to maxPageRunes before
// sending, so anything near this limit is not a job page.
maxCaptureBody = 512 << 10
// maxPageRunes caps both the text sent to Claude and the description
// stored.
maxPageRunes = 40_000
)
// CaptureTokenMiddleware guards the capture routes with the token generated
// on the settings page (services.CaptureToken), presented as
// "Authorization: Bearer <token>".
//
// Until a token has been generated the routes are off (503) rather than
// open; "no token" must never be satisfied by a request that sends none.
func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) {
if store.CaptureToken == nil {
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"})
return
}
if set, _ := store.CaptureToken.Status(); !set {
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "no capture token has been generated"})
return
}
presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ")
if !ok || !store.CaptureToken.Verify(presented) {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
ctx.Next()
}
// The three handlers below manage that token from the tracker's settings
// page. They sit behind the admin check (auth.Require), not behind the token:
// the token must not be able to replace itself.
func captureTokenStatus(token *services.CaptureToken) gin.H {
set, createdAt := token.Status()
if !set {
return gin.H{"set": false}
}
return gin.H{"set": true, "createdAt": createdAt}
}
// GetCaptureToken backs GET /api/admin/capture-token: whether a token exists and
// when it was made. The token itself is not recoverable — only its hash is
// stored.
func (store *Store) GetCaptureToken(ctx *gin.Context) {
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
}
// GenerateCaptureToken backs POST /api/admin/capture-token. It replaces any
// existing token, so the userscript must be reconfigured with the new one,
// and its response is the only time the token is ever sent anywhere.
func (store *Store) GenerateCaptureToken(ctx *gin.Context) {
token, createdAt, err := store.CaptureToken.Generate()
if err != nil {
log.Println("Generating capture token failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to store the token"})
return
}
// The response carries a credential; keep it out of any cache.
ctx.Header("Cache-Control", "no-store")
ctx.JSON(http.StatusOK, gin.H{"token": token, "createdAt": createdAt})
}
// RevokeCaptureToken backs DELETE /api/admin/capture-token, switching the capture
// routes off until a new token is generated.
func (store *Store) RevokeCaptureToken(ctx *gin.Context) {
if err := store.CaptureToken.Revoke(); err != nil {
log.Println("Revoking capture token failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to revoke the token"})
return
}
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
}
// capturedJob is the slice of an application the userscript needs back: enough
// to show "already tracked as …" and no more. The token is not meant to be
// able to read the tracker, so notes and the description stay out of it.
type capturedJob struct {
ID uint `json:"id"`
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Status string `json:"status"`
}
func capturedJobOf(app *models.JobApplication) *capturedJob {
return &capturedJob{ID: app.ID, JobTitle: app.JobTitle, Company: app.Company, Status: app.Status}
}
// JobCaptureStatus backs GET /api/capture/status?url=. It is what lets the
// userscript show a posting's tracked status instead of an "add" button.
func (store *Store) JobCaptureStatus(ctx *gin.Context) {
raw := ctx.Query("url")
canonical, ok := services.CanonicalJobURL(raw)
if !ok {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
return
}
app, err := services.FindApplicationByURL(store.DB, canonical, raw)
if err != nil {
log.Println("Job capture status lookup failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
return
}
if app == nil {
ctx.JSON(http.StatusOK, gin.H{"found": false})
return
}
ctx.JSON(http.StatusOK, gin.H{"found": true, "application": capturedJobOf(app)})
}
// PostingExtractor is the Claude call behind the extract route (normally a
// *claude.Client; the tests substitute a fake). Its errors are claude's: a
// *claude.ReadError carries a message fit for the popup, anything else is
// only logged.
type PostingExtractor interface {
ExtractPosting(ctx context.Context, url, title, text string) (claude.JobPosting, error)
}
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
// is still valid UTF-8 for Postgres and for JSON.
func truncateRunes(s string, max int) string {
runes := []rune(s)
if len(runes) <= max {
return s
}
return string(runes[:max])
}
// bindCapture decodes a size-limited JSON body, answering 400 itself when it
// cannot.
func bindCapture(ctx *gin.Context, into any) bool {
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxCaptureBody)
if err := ctx.ShouldBindJSON(into); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return false
}
return true
}
// JobCaptureExtract backs POST /api/capture/extract: page text in, the
// popup's pre-filled fields out. Nothing is stored; saving is a separate
// request made once the fields have been checked by eye.
func (store *Store) JobCaptureExtract(ctx *gin.Context) {
var input struct {
URL string `json:"url"`
Title string `json:"title"`
Text string `json:"text"`
}
if !bindCapture(ctx, &input) {
return
}
text := strings.TrimSpace(input.Text)
if text == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "text is required"})
return
}
posting, err := store.Extractor.ExtractPosting(ctx.Request.Context(),
truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes))
if err != nil {
log.Println("Job extract failed:", err)
var readErr *claude.ReadError
if errors.As(err, &readErr) {
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.Msg})
return
}
ctx.JSON(http.StatusBadGateway, gin.H{"error": "failed to read the page"})
return
}
ctx.JSON(http.StatusOK, posting)
}
// JobCapture backs POST /api/capture, an upsert: a posting already in the
// tracker is updated in place rather than added again. The matching and
// merging rules are services.UpsertJobApplication's; this handler owns the
// request body and the status codes.
func (store *Store) JobCapture(ctx *gin.Context) {
var input services.JobCaptureInput
if !bindCapture(ctx, &input) {
return
}
input.Description = truncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
app, action, err := services.UpsertJobApplication(store.DB, input, time.Now())
var invalid *services.JobInputError
switch {
case errors.As(err, &invalid):
ctx.JSON(http.StatusBadRequest, gin.H{"error": invalid.Error()})
case err != nil:
log.Println("Job capture failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
case action == "created":
ctx.JSON(http.StatusCreated, gin.H{"action": action, "application": capturedJobOf(app)})
default:
ctx.JSON(http.StatusOK, gin.H{"action": action, "application": capturedJobOf(app)})
}
}
@@ -0,0 +1,230 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"adam-french.co.uk/job-tracker/internal/claude"
"adam-french.co.uk/job-tracker/internal/services"
"github.com/gin-gonic/gin"
)
// The capture handlers themselves need a database, and the only driver in
// go.mod is postgres, so what is covered here is everything around the
// queries: the token gate, the URL key that decides whether a posting is
// already tracked, the merge rule for a repeat capture, and the extract
// route around the posting reader.
func TestCaptureTokenMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode)
serve := func(store *Store, header string) int {
r := gin.New()
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
req := httptest.NewRequest(http.MethodGet, "/x", nil)
if header != "" {
req.Header.Set("Authorization", header)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec.Code
}
newToken := func() *services.CaptureToken {
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
return tok
}
// The case the middleware exists to get right: with no token generated,
// a request presenting nothing (or an empty bearer) must not get in.
t.Run("no token generated switches the routes off", func(t *testing.T) {
store := &Store{CaptureToken: newToken()}
for _, header := range []string{"", "Bearer ", "Bearer anything"} {
if got := serve(store, header); got != http.StatusServiceUnavailable {
t.Fatalf("header %q: status = %d, want 503", header, got)
}
}
})
t.Run("a store built without the token service is off too", func(t *testing.T) {
if got := serve(&Store{}, "Bearer x"); got != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", got)
}
})
store := &Store{CaptureToken: newToken()}
token, _, err := store.CaptureToken.Generate()
if err != nil {
t.Fatalf("Generate: %v", err)
}
cases := []struct {
name string
header string
want int
}{
{"the generated token is let through", "Bearer " + token, http.StatusOK},
{"a wrong token is refused", "Bearer nope", http.StatusUnauthorized},
{"no header is refused", "", http.StatusUnauthorized},
{"the bare token without the scheme is refused", token, http.StatusUnauthorized},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := serve(store, c.header); got != c.want {
t.Fatalf("status = %d, want %d", got, c.want)
}
})
}
}
// The admin endpoints, driven without the admin middleware (covered
// elsewhere): generate shows the token once, status never does, and a second
// generate or a revoke stops the first token working.
func TestCaptureTokenAdminEndpoints(t *testing.T) {
gin.SetMode(gin.TestMode)
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
store := &Store{CaptureToken: tok}
r := gin.New()
r.GET("/t", store.GetCaptureToken)
r.POST("/t", store.GenerateCaptureToken)
r.DELETE("/t", store.RevokeCaptureToken)
call := func(method string) (map[string]any, *httptest.ResponseRecorder) {
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(method, "/t", nil))
if rec.Code != http.StatusOK {
t.Fatalf("%s: status = %d, body = %s", method, rec.Code, rec.Body)
}
var out map[string]any
json.Unmarshal(rec.Body.Bytes(), &out)
return out, rec
}
if out, _ := call(http.MethodGet); out["set"] != false {
t.Fatalf("fresh status = %v", out)
}
out, rec := call(http.MethodPost)
first, _ := out["token"].(string)
if !tok.Verify(first) {
t.Fatalf("generated token %q does not verify", first)
}
if rec.Header().Get("Cache-Control") != "no-store" {
t.Fatal("the response carrying the token must not be cacheable")
}
out, _ = call(http.MethodGet)
if out["set"] != true || out["createdAt"] == nil {
t.Fatalf("status after generate = %v", out)
}
if _, leaked := out["token"]; leaked {
t.Fatal("status must never return the token")
}
call(http.MethodPost)
if tok.Verify(first) {
t.Fatal("regenerating must invalidate the previous token")
}
if out, _ := call(http.MethodDelete); out["set"] != false {
t.Fatalf("status after revoke = %v", out)
}
}
func TestTruncateRunes(t *testing.T) {
if got := truncateRunes("££££", 2); got != "££" {
t.Fatalf("got %q; the cut must fall on a rune boundary", got)
}
if got := truncateRunes("short", 10); got != "short" {
t.Fatalf("got %q", got)
}
}
// fakeExtractor answers every page with posting and err, recording the
// arguments it was called with.
type fakeExtractor struct {
posting claude.JobPosting
err error
got []string
}
func (f *fakeExtractor) ExtractPosting(_ context.Context, url, title, text string) (claude.JobPosting, error) {
f.got = []string{url, title, text}
return f.posting, f.err
}
func extractRoute(f *fakeExtractor) func(body string) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
store := &Store{Extractor: f}
r := gin.New()
r.POST("/extract", store.JobCaptureExtract)
return func(body string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/extract", strings.NewReader(body)))
return rec
}
}
// Claude's own failure messages are worded for the popup and are relayed;
// anything else (no API key, say) is logged and replaced.
func TestJobCaptureExtractErrors(t *testing.T) {
cases := []struct {
name string
err error
want string
}{
{"extractor failure is relayed", &claude.ReadError{Msg: "failed to parse the posting"}, "failed to parse the posting"},
{"missing key is not relayed", claude.ErrNotConfigured, "failed to read the page"},
{"anything else is not relayed", errors.New("boom"), "failed to read the page"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
rec := extractRoute(&fakeExtractor{err: c.err})(`{"url": "https://x.com/1", "title": "t", "text": "page"}`)
var body map[string]string
json.Unmarshal(rec.Body.Bytes(), &body)
if rec.Code != http.StatusBadGateway || body["error"] != c.want {
t.Fatalf("status = %d, body = %s; want 502 %q", rec.Code, rec.Body, c.want)
}
})
}
}
// The extract handler runs without a database, so it can be driven whole: the
// page text must be cut to maxPageRunes before it is sent to Claude.
func TestJobCaptureExtractTruncatesAndRelays(t *testing.T) {
london := "London"
f := &fakeExtractor{posting: claude.JobPosting{JobTitle: "Engineer", Company: "Acme", Location: &london}}
post := extractRoute(f)
long, _ := json.Marshal(map[string]string{"url": "https://x.com/1", "title": "Engineer | Acme", "text": strings.Repeat("é", maxPageRunes+500)})
rec := post(string(long))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body)
}
if f.got[0] != "https://x.com/1" || f.got[1] != "Engineer | Acme" {
t.Fatalf("hints passed as %q", f.got[:2])
}
if n := len([]rune(f.got[2])); n != maxPageRunes {
t.Fatalf("forwarded %d runes, want %d", n, maxPageRunes)
}
// The body is the userscript's contract: these four keys.
if rec.Body.String() != `{"jobTitle":"Engineer","company":"Acme","location":"London","notes":null}` {
t.Fatalf("body = %s", rec.Body)
}
if rec := post(`{"url": "https://x.com/1", "text": " "}`); rec.Code != http.StatusBadRequest {
t.Fatalf("blank text: status = %d", rec.Code)
}
if rec := post(`not json`); rec.Code != http.StatusBadRequest {
t.Fatalf("bad body: status = %d", rec.Code)
}
}
+65
View File
@@ -0,0 +1,65 @@
package handlers
import (
"net/http"
"os"
"path"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
)
// SPA serves the built Vue app from dir for every GET under base that no API
// route claimed. It is installed as gin's NoRoute handler rather than as a
// base+"/*path" route because gin will not let a catch-all sit beside the
// /api routes at the same level.
//
// History-mode routing means a path such as /jobs/leads is a page of the app,
// not a file, so anything that is not a file in dir gets index.html — except
// under /api/ and /assets/, where a miss is a real 404: an API typo should
// not come back as a page of HTML, and neither should a stale asset hash.
//
// Caching: Vite fingerprints everything under assets/, so those are cached
// for a year; index.html is never cached, so a deploy is picked up on the
// next load.
func SPA(dir, base string) gin.HandlerFunc {
return func(ctx *gin.Context) {
p := ctx.Request.URL.Path
if ctx.Request.Method != http.MethodGet && ctx.Request.Method != http.MethodHead {
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if p == base {
ctx.Redirect(http.StatusMovedPermanently, base+"/")
return
}
rel, ok := strings.CutPrefix(p, base+"/")
if !ok || strings.HasPrefix(rel, "api/") {
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
// path.Clean on a rooted path cannot climb above the root, so the
// result always stays inside dir.
rel = strings.TrimPrefix(path.Clean("/"+rel), "/")
if rel != "" {
file := filepath.Join(dir, filepath.FromSlash(rel))
if info, err := os.Stat(file); err == nil && !info.IsDir() {
if strings.HasPrefix(rel, "assets/") {
ctx.Header("Cache-Control", "public, max-age=31536000, immutable")
} else {
ctx.Header("Cache-Control", "no-cache")
}
ctx.File(file)
return
}
if strings.HasPrefix(rel, "assets/") {
ctx.Status(http.StatusNotFound)
return
}
}
ctx.Header("Cache-Control", "no-cache")
ctx.File(filepath.Join(dir, "index.html"))
}
}
+61
View File
@@ -0,0 +1,61 @@
package handlers
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
)
func TestSPA(t *testing.T) {
gin.SetMode(gin.TestMode)
dir := t.TempDir()
os.MkdirAll(filepath.Join(dir, "assets"), 0o755)
os.WriteFile(filepath.Join(dir, "index.html"), []byte("index"), 0o644)
os.WriteFile(filepath.Join(dir, "assets", "app-1a2b.js"), []byte("js"), 0o644)
os.WriteFile(filepath.Join(dir, "job-capture.user.js"), []byte("userscript"), 0o644)
// Outside dir: must never be reachable.
os.WriteFile(filepath.Join(filepath.Dir(dir), "secret"), []byte("secret"), 0o644)
r := gin.New()
r.GET("/jobs/api/health", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
r.NoRoute(SPA(dir, "/jobs"))
cases := []struct {
method, path string
code int
body string
cache string
}{
{"GET", "/jobs/", 200, "index", "no-cache"},
{"GET", "/jobs/leads", 200, "index", "no-cache"},
{"GET", "/jobs/settings/anything", 200, "index", "no-cache"},
{"GET", "/jobs/assets/app-1a2b.js", 200, "js", "public, max-age=31536000, immutable"},
{"GET", "/jobs/job-capture.user.js", 200, "userscript", "no-cache"},
{"GET", "/jobs/api/health", 200, "ok", ""},
{"GET", "/jobs/api/nope", 404, `{"error":"not found"}`, ""},
{"GET", "/jobs/assets/gone.js", 404, "404 page not found", ""},
// net/http refuses a path that climbs, before anything is read.
{"GET", "/jobs/../secret", 400, "invalid URL path\n", ""},
{"GET", "/jobs/%2e%2e/secret", 400, "invalid URL path\n", ""},
{"POST", "/jobs/leads", 404, `{"error":"not found"}`, ""},
{"GET", "/elsewhere", 404, `{"error":"not found"}`, ""},
}
for _, c := range cases {
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(c.method, c.path, nil))
if rec.Code != c.code || rec.Body.String() != c.body || rec.Header().Get("Cache-Control") != c.cache {
t.Errorf("%s %s = %d %q (cache %q), want %d %q (cache %q)",
c.method, c.path, rec.Code, rec.Body, rec.Header().Get("Cache-Control"), c.code, c.body, c.cache)
}
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest("GET", "/jobs", nil))
if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/jobs/" {
t.Errorf("GET /jobs = %d to %q, want a redirect to /jobs/", rec.Code, rec.Header().Get("Location"))
}
}
+27
View File
@@ -0,0 +1,27 @@
package handlers
import (
"adam-french.co.uk/job-tracker/internal/services"
"gorm.io/gorm"
)
// Package handlers holds the REST endpoints and the shared Store that every
// request handler — and, through graph.Resolver, every GraphQL resolver —
// depends on. It is built once in main and passed around by pointer.
type Store struct {
DB *gorm.DB
// EmailSync is the mailbox pipeline (services/email_sync.go).
EmailSync *services.EmailSyncService
// JobLeads is the lead fetcher (services/job_leads.go). The GraphQL
// resolvers use it to start a run and report on one.
JobLeads *services.JobLeadService
// Extractor reads a posting's page for the capture popup
// (handle_job_capture.go).
Extractor PostingExtractor
// Bearer token for the browser capture routes (handle_job_capture.go),
// generated from the settings page. Nil, or holding no token, means those
// routes are switched off, not open.
CaptureToken *services.CaptureToken
}