Documentation / Handlers & helpers
Handlers & helpers
Build with HyperChi’s handler, rendering, response, and collection APIs. Keep standard HTTP access available for the parts that actually need it.
Choose the handler for the job
app.Get,app.Post,app.Put,app.Patch, andapp.Deletetake afunc(c *hyperchi.Context) error. They register the HTTP method and pass returned errors to the application error handler. Optional middleware for that route follows the handler.- The handler chooses the response.
c.Viewrenders the full page, or only the template for an htmx partial request.c.Pagealways renders the page andc.Fragmentnever adds a layout. app.Handle(method, pattern, handler)andapp.Mountintegrate existingnet/httphandlers or routers. They are interoperability APIs, not necessary boilerplate for a new endpoint.
The runnable integration examples, the main showcase, and these documentation pages all use context handlers.
A complete context handler
With the core hyperchi package imported and app initialized:
app.Get("/hello/{name}", func(c *hyperchi.Context) error {
greeting := c.QueryDefault("greeting", "Hello")
return c.JSON(hyperchi.H{
"message": greeting + ", " + c.Param("name"),
})
})
A request to /hello/Morgan?greeting=Welcome returns a JSON object containing "message": "Welcome, Morgan". You do not need to set a JSON content type or construct an encoder.
Read inputs without repeating request plumbing
name := c.Param("name")
query := c.Query("q")
terrain := c.QueryDefault("terrain", "all")
tags := c.Queries("tag")
isHTMX := c.IsHTMX()
These helpers read inputs; they do not validate or authorize them. Keep allowlists, schemas, and permission checks explicit. c.Ctx() returns the request context for cancellation, and c.Request() remains available for HTTP features without a framework helper.
To decode and check a whole form or JSON body, describe it as a struct and call hyperchi.Bind:
type Signup struct {
Email string `form:"email" validate:"required,email"`
}
in, err := hyperchi.Bind[Signup](c)
if err != nil {
return err // 400 for an unreadable body, 422 when a check fails
}
Render through HyperChi
helpers.Must(app.LoadTemplates("templates/*.tmpl"))
app.Get("/trips", func(c *hyperchi.Context) error {
return c.View("trips.tmpl", catalog)
})
app.Get("/trip-cards", func(c *hyperchi.Context) error {
return c.Fragment("trip-cards.tmpl", catalog)
})
For a typed slice, the template reads the data through .Result:
{{range .Result}}
<article><h2>{{.Name}}</h2></article>
{{end}}
For top-level template keys, pass hyperchi.H, helpers.JSON, or map[string]any. All three merge keys into the template context, so hyperchi.H{"Title": "Trips"} is available as .Title. Strings still receive HTML escaping. A slice stays under .Result; a struct is under .Result too, and its exported fields are also top-level keys, so c.Fragment("trip-card", trip) renders a template that reads {{.Name}}. c.Layout("admin").Page(...) selects an explicit layout. Values set once at startup with app.SetGlobal, such as a site name, reach every template; handler data wins over a global, and a global wins over a query parameter. These helpers supply the registered template filters and request context.
Transform typed collections
Import github.com/regiellis/hyperchi/hyperchi/helpers for generic collection operations. Go’s method rules mean the typed helpers are package functions: helpers.FromSlice wraps an existing slice, and helpers.NewSlice builds one from values.
trips := helpers.FromSlice(catalog).Filter(func(trip Trip) bool {
return trip.Terrain == "coast"
}).OrEmpty()
count := trips.Len()
first, found := trips.First()
Filter produces a new result and preserves the element type. Chain OrEmpty() when JSON must contain [] instead of null. It normalizes a nil result without copying a non-nil slice. Use helpers.Map when the output type differs, and helpers.Reduce to aggregate values. See the trip finder recipe for these helpers in an actual handler.
Build a response with status or htmx headers
Chain c.Status before a response method to change the status, and use c.HX() to set htmx response headers:
return c.Status(http.StatusBadRequest).
JSON(hyperchi.H{"error": "Unknown terrain"})
c.HX().Retarget("#result").Reswap("innerHTML")
return c.HTML("<p>Ready.</p>")
The status example also imports net/http for its named constant. c.HX() also supports Trigger, PushURL, Location, and Refresh, and a chain can end in a response method: View, Fragment, HTML, JSON, or Empty. c.Redirect sends HX-Redirect to htmx and a 303 to any other client. Writing literal HTML is fine for application-owned markup; render visitor values through an escaping template.
Return errors at request time
Use helpers.Must for startup requirements such as loading templates. Inside a handler, return hyperchi.NotFound, hyperchi.BadRequest, or hyperchi.NewHTTPError to answer with that status. HyperChi renders it for the client: JSON for Accept: application/json, an error fragment for htmx, and an error page for a browser. Any other error is a 500 whose text stays in the log. An endpoint that promises JSON to every client sets the status itself, as in the JSON 400 above.
trip, ok := trips[c.Param("id")]
if !ok {
return hyperchi.NotFound("No such trip")
}
return c.View("trip", trip)
c.JSON and the template methods finish rendering before committing the status or body. Encoding and template errors can therefore reach the application error handler. A network write can still fail after committing the response; do not attempt a second response then. External renderers also need buffering. The templ and Jet integrations supply that boundary. Register them once and use c.RenderWith; the manager handles buffering and HTML response headers.
c.RenderWith works in any handler, so a page and its fragment can share one adapter. The integration pages deliberately use explicit HTML and JSON endpoints, so each handler keeps its contract direct.
Confirm a post with a flash message
After a form post, redirect, and carry the confirmation to the next page with c.Flash:
app.Post("/items", func(c *hyperchi.Context) error {
in, err := hyperchi.Bind[NewItem](c)
if err != nil {
return err
}
if err := store.Add(c.Ctx(), in.Name); err != nil {
return err
}
if err := c.Flash("success", "Item added."); err != nil {
return err
}
return c.Redirect("/items")
})
The page the redirect lands on receives the messages as .flashes when it renders with c.View, c.Page, or c.Fragment:
{{range .flashes}}<p class="flash flash-{{.Kind}}" role="status">{{.Message}}</p>{{end}}
Rendering reads the messages once, so a reload does not show them again. c.Flashes() reads them in Go. The messages travel in a signed cookie, or in the session when the route runs behind app.SessionMiddleware(). At most ten are kept, each up to 1024 bytes. The kind is your own label, usually turned into a class. This request's own render does not show a flash; pass the message in the template data for that.
Sign a cookie
c.SetSignedCookie signs a value so the browser can hold it but not change it, and c.SignedCookie checks the signature and the age:
err := c.SetSignedCookie(&http.Cookie{Name: "theme", Value: "dark", MaxAge: 365 * 24 * 60 * 60})
if err != nil {
return err
}
theme, err := c.SignedCookie("theme", 365*24*time.Hour)
if err != nil {
theme = "light" // missing, tampered with, or older than a year
}
The signature (HMAC-SHA256) covers the cookie name, the value, and when it was signed, so a value cannot be edited, moved to another cookie, or replayed after maxAge. Test the error with errors.Is against hyperchi.ErrCookieMissing, ErrCookieInvalid, or ErrCookieExpired. The value is signed, not encrypted: anyone holding the cookie can read it, so never put a secret in it. The cookie is sent HttpOnly, SameSite=Lax unless you set another mode, and Secure in production.
Both signed cookies and flash messages use the application secret key. Set SECRET_KEY (or config.Security.SecretKey) to at least 32 bytes in production, for example the output of openssl rand -base64 32; without it they fail with hyperchi.ErrNoSecretKey. Development signs with a random key, so signed values do not survive a restart. To rotate the key, move the old one to SECRET_KEY_PREVIOUS (comma-separated): values it signed keep verifying, and new ones use the new key.
Split a long form into steps
MultiStepForm serves a form over several pages and keeps the answers in the visitor's session until the last step. It needs sessions, and it needs them before the routes are registered:
helpers.Must(app.UseKVStoreMemoryAdvanced("sessions"))
helpers.Must(app.UseSessions(hyperchi.KVSessionConfig{Backend: "sessions"}))
app.Use(app.SessionMiddleware())
pm := app.Extensions().GetPatternManager()
pm.MultiStepForm("/signup", patterns.MultiStepFormConfig{
SuccessURL: "/signup/done",
Steps: []patterns.FormStep{
{
Name: "account", Title: "Your account", Template: "signup-account",
Fields: []string{"email"},
Validate: patterns.SchemaStep(validator.NewSchema().
Field("email", validator.String().Required().Email())),
},
{Name: "plan", Title: "Choose a plan", Template: "signup-plan", Fields: []string{"plan"}},
},
Complete: func(r *http.Request, answers url.Values) error {
return accounts.Create(r.Context(), answers.Get("email"), answers.Get("plan"))
},
})
This also imports net/http, net/url, and the patterns and validator packages, and assumes your accounts store. Each step's template posts its number in a step field and reads .values (the answers so far) and .errors (messages per field):
{{define "signup-account"}}
<form hx-post="/signup" hx-target="this" hx-swap="outerHTML">
<input type="hidden" name="step" value="{{.step}}">
<label>Email <input name="email" type="email" value="{{.values.Get "email"}}"></label>
{{range index .errors "email"}}<p class="field-error">{{.}}</p>{{end}}
<button>Continue</button>
</form>
{{end}}
- A
GET /signup?step=2renders that step with the stored answers, so going back shows what the visitor entered. A step cannot be reached before the ones ahead of it are answered. - A post keeps only the step's
Fields, then runs itsValidate. A rejected step renders again with status 422, its messages, and the submitted values, and nothing is stored. An accepted step is stored, and the response is the next step, with its URL pushed. - After the last step,
Completereceives every answer, the stored answers are cleared, and the visitor is redirected toSuccessURL. IfCompletereturns an error, the answers are kept for another try. patterns.SchemaStepadapts avalidator.Schema; anyfunc(url.Values) map[string][]stringworks asValidate.- Without session middleware every wizard request fails with a 500 whose cause is
patterns.ErrNoWizardStore.
Store an upload
Validate an upload, then store it with SaveAll, which names each file itself:
uploads := security.NewUploadValidator(security.DefaultUploadConfig())
app.Post("/photos", func(c *hyperchi.Context) error {
result := uploads.ValidateUpload(c.Request())
if !result.Valid {
return hyperchi.Unprocessable("That file was not accepted.", map[string][]string{"file": result.Errors})
}
saved, err := result.SaveAll("data/uploads", security.SaveOptions{})
if err != nil {
return err
}
return c.View("photo-saved", hyperchi.H{"files": saved})
})
A stored file's name is 128 random bits plus an extension chosen from the type sniffed from its content, never from the visitor's file name or declared type. Files are written through an os.Root, so nothing lands outside the folder, and an existing file is never overwritten. SaveAll stores every file or none. HTML, SVG, XML, and JavaScript are refused even when listed. security.DefaultSaveExtensions() returns the default type-to-extension map; copy it and add a type to store more. For one file, security.SaveUpload(dir, fileHeader, opts) does the same. Show SavedFile.OriginalName to the visitor, but never use it as a path.
DefaultUploadConfig sets RequireAuth, which rejects an upload unless the request context carries a verified user (security.WithUserID). Serve stored files with their content type and X-Content-Type-Options: nosniff.
Call another service with request cancellation
Configure one HTTP client at startup. The With* configuration methods mutate it, so finish configuration before concurrent requests. Inside handlers, use GetWithContext, PostWithContext, PutWithContext, PatchWithContext, DeleteWithContext, or PostFormWithContext to carry cancellation and deadlines.
client := helpers.NewHTTPClient().
WithBaseURL("https://api.example.com").
WithTimeout(5 * time.Second).
WithJSONHeaders()
app.Get("/inventory", func(c *hyperchi.Context) error {
res, err := client.GetWithContext(c.Ctx(), "/items")
if err != nil { return err }
defer res.Close()
if !res.IsSuccess() {
return fmt.Errorf("inventory service returned %d", res.StatusCode())
}
var items []Item
if err := res.Parse(&items); err != nil { return err }
return c.JSON(helpers.FromSlice(items).OrEmpty())
})
This recipe also imports fmt and time and assumes your Item model. HTTP 4xx and 5xx responses do not produce a transport error: check the status. Parse, Text, and JSON consume and close the body; defer Close to cover early returns. The shorter HTTP methods use a background context and the configured client timeout (30 seconds by default). Strings are sent raw; other non-nil request bodies are JSON encoded. Form requests set their own content type.
JSON objects and reliable defaults
options := helpers.NewJSON().
Set("limit", "24").
Set("enabled", false)
limit := options.GetIntOr("limit", 12)
enabled := options.GetBoolOr("enabled", true)
Defaults apply to absent or invalid values; valid zero and false values are preserved. Integer access accepts ints, float64 values (truncated), and integer strings. GetJSON accepts both plain maps and nested helpers.JSON values. FromJSON("null") returns an empty object. Retain the returned map when calling Set or Merge on a possibly nil object. Prefer typed structs for stable service contracts.
Choose intentional error handling
value, err := strconv.Atoi(configuredPort)
port := helpers.Default(value, err, 8080)
Default takes three arguments: value, error, and fallback. Use it only when a fallback is acceptable. Return errors from request handlers, and reserve helpers.Must for startup requirements. String JSON conveniences such as helpers.ToJSON and JSON.ToString return {} on encoding errors; use c.JSON or json.Marshal when errors must be reported.
Use the other helpers where they fit
app.Helpers.Env.GetOr("PORT", "8080")reads configuration with a fallback.helpers.S(value).Trim().Lower().String()composes string transformations.app.Helpers.Logger.Info,Warn, andErrorwrite to the application’s logger.helpers.NewJSON().Set("status", "ok")builds a JSON object;hyperchi.His convenient for a small response literal.
Typed models, context.Context, embedded assets, and standard HTTP middleware remain useful Go primitives. The goal is to avoid reimplementing conveniences that HyperChi already supplies, while keeping application logic clear.
Every helper
The complete list, grouped by what it is for: the request and response helpers on Context, input binding and errors from the core package, then the helpers package. Each entry shows its signature and what it does; open a group to browse it, or search the docs for a name.
Request (Context) 22 entries
import "github.com/regiellis/hyperchi/hyperchi"
Contexttype Context structContext carries one request through a Handler: read the request with its accessors, then answer with one of its response methods.
Context.Appfunc (c *Context) App() *HyperChiApp returns the application serving this request.
Context.CSRFTokenfunc (c *Context) CSRFToken() stringCSRFToken returns the request's CSRF token for forms and htmx headers that post back, or "" outside Middleware.CSRF.
Context.Cookiefunc (c *Context) Cookie(name string) stringCookie returns a request cookie's value, or "" when it is not set.
Context.Ctxfunc (c *Context) Ctx() context.ContextCtx returns the request's context.Context, for cancellation and deadlines.
Context.FormValuefunc (c *Context) FormValue(key string) stringFormValue returns a submitted form field, parsing the body on first use.
Context.Headerfunc (c *Context) Header(key string) stringHeader returns a request header.
Context.IsHTMXfunc (c *Context) IsHTMX() boolIsHTMX reports whether htmx sent the request.
Context.Methodfunc (c *Context) Method() stringMethod returns the request method.
Context.Paramfunc (c *Context) Param(key string) stringParam returns a route parameter, such as {id} in "/users/{id}".
Context.ParamIntfunc (c *Context) ParamInt(key string) (int, error)ParamInt returns a route parameter as an int.
Context.Pathfunc (c *Context) Path() stringPath returns the request URL path.
Context.Queriesfunc (c *Context) Queries(key string) []stringQueries returns every value of a query parameter.
Context.Queryfunc (c *Context) Query(key string) stringQuery returns the first value of a query string parameter.
Context.QueryDefaultfunc (c *Context) QueryDefault(key, fallback string) stringQueryDefault returns the first query value, or fallback when it is absent or empty.
Context.QueryIntfunc (c *Context) QueryInt(key string, fallback int) intQueryInt returns a query parameter as an int, or fallback when it is absent or not an integer.
Context.Requestfunc (c *Context) Request() *http.RequestRequest returns the underlying *http.Request.
Context.Responsefunc (c *Context) Response() http.ResponseWriterResponse returns the underlying http.ResponseWriter, for code that has to write the response itself (streaming, a third-party encoder).
Context.Sessionfunc (c *Context) Session() *KVSessionSession returns the request's session, or nil when the route does not run behind SessionMiddleware (see UseSessions).
Context.UserIDfunc (c *Context) UserID() stringUserID returns the authenticated user's ID set by the auth middleware, or "" for an anonymous request.
Context.Valuefunc (c *Context) Value(key string) anyValue returns a value attached to the request with WithContext, typically by middleware.
HyperChi.NewContextfunc (g *HyperChi) NewContext(w http.ResponseWriter, r *http.Request) *ContextNewContext builds a Context outside a route, for tests and for adapters that receive a plain net/http request.
Responses (Context) 38 entries
import "github.com/regiellis/hyperchi/hyperchi"
Context.Blobfunc (c *Context) Blob(contentType string, body []byte) errorBlob writes body with the given content type, for responses Text and HTML do not cover (Markdown, CSV, images).
Context.Emptyfunc (c *Context) Empty() errorEmpty sends the status (200 unless set with Status) and headers with no body, for responses whose headers are the answer.
Context.Fragmentfunc (c *Context) Fragment(name string, data any) errorFragment renders a template without a layout, for htmx swaps.
Context.HTMLfunc (c *Context) HTML(markup template.HTML) errorHTML writes trusted HTML.
Context.HXfunc (c *Context) HX() *HXHX returns the htmx helper for this request.
Context.JSONfunc (c *Context) JSON(data any) errorJSON writes data as a JSON response.
Context.Layoutfunc (c *Context) Layout(name string) *ContextLayout picks the layout template ("layout-<name>") for Page and View.
Context.NoContentfunc (c *Context) NoContent() errorNoContent sends 204 No Content.
Context.Pagefunc (c *Context) Page(name string, data any) errorPage renders a template inside its layout, whatever sent the request.
Context.Redirectfunc (c *Context) Redirect(url string) errorRedirect sends the client to url.
Context.RenderWithfunc (c *Context) RenderWith(name string, data any) errorRenderWith renders through a named integration (see Integrations), such as a templ or Jet adapter, buffering before any header is sent.
Context.SetCookiefunc (c *Context) SetCookie(cookie *http.Cookie) *ContextSetCookie adds a Set-Cookie header to the response.
Context.SetHeaderfunc (c *Context) SetHeader(key, value string) *ContextSetHeader sets a response header.
Context.Statusfunc (c *Context) Status(code int) *ContextStatus sets the status code for the response this handler sends next.
Context.Textfunc (c *Context) Text(s string) errorText writes a plain-text response.
Context.Viewfunc (c *Context) View(name string, data any) errorView renders a template the way the request needs it: the full page inside its layout for a normal or boosted navigation, and the template alone for an htmx partial request.
HXtype HX structHX reads htmx request headers and sets htmx response headers.
HX.Boostedfunc (h *HX) Boosted() boolBoosted reports a boosted link or form navigation (HX-Boosted).
HX.CurrentURLfunc (h *HX) CurrentURL() stringCurrentURL is the page the browser was on (HX-Current-URL).
HX.Emptyfunc (h *HX) Empty() errorEmpty finishes with an empty 200 response, for a request that only needs the htmx headers (a trigger, a refresh, a location change).
HX.Fragmentfunc (h *HX) Fragment(name string, data any) errorFragment finishes with Context.Fragment.
HX.HTMLfunc (h *HX) HTML(markup template.HTML) errorHTML finishes with Context.HTML.
HX.JSONfunc (h *HX) JSON(data any) errorJSON finishes with Context.JSON.
HX.Locationfunc (h *HX) Location(url string) *HXLocation navigates without a full reload (HX-Location).
HX.NoContentfunc (h *HX) NoContent() errorNoContent finishes with Context.NoContent, which still sends the headers.
HX.Pagefunc (h *HX) Page(name string, data any) errorPage finishes with Context.Page.
HX.PushURLfunc (h *HX) PushURL(url string) *HXPushURL pushes url onto browser history (HX-Push-Url).
HX.Refreshfunc (h *HX) Refresh() *HXRefresh makes the browser reload the page (HX-Refresh).
HX.ReplaceURLfunc (h *HX) ReplaceURL(url string) *HXReplaceURL replaces the current history entry (HX-Replace-Url).
HX.Reselectfunc (h *HX) Reselect(selector string) *HXReselect picks part of the response to swap (HX-Reselect).
HX.Reswapfunc (h *HX) Reswap(swap string) *HXReswap changes the swap strategy, such as "outerHTML" (HX-Reswap).
HX.Retargetfunc (h *HX) Retarget(selector string) *HXRetarget swaps the response into a different element (HX-Retarget).
HX.Sourcefunc (h *HX) Source() stringSource is the element that issued the request, as "tag#id" (HX-Source).
HX.Statusfunc (h *HX) Status(code int) *HXStatus sets the response status, as Context.Status does.
HX.Targetfunc (h *HX) Target() stringTarget identifies the element htmx will swap into, as "tagName#id" such as "div#results" (HX-Target).
HX.Triggerfunc (h *HX) Trigger(event string, detail ...any) *HXTrigger fires a client-side event after the swap.
HX.Viewfunc (h *HX) View(name string, data any) errorView finishes with Context.View.
HyperChi.SetGlobalfunc (g *HyperChi) SetGlobal(key string, value any)SetGlobal makes a value available to every template rendered through a Context, such as a site name or the Vite dev-server URL.
Input binding 3 entries
import "github.com/regiellis/hyperchi/hyperchi"
Bindfunc Bind[T any](c *Context) (T, error)Bind decodes the request into a new T and validates it.
Context.Bindfunc (c *Context) Bind(dst any) errorBind decodes and validates the request into dst, a pointer to a struct.
Context.ValidateSchemafunc (c *Context) ValidateSchema(name string) (map[string]any, error)ValidateSchema checks the submitted form or JSON body against a schema registered on app.Schemas, returning the cleaned data, or a 422 error with per-field messages.
Errors and statuses 18 entries
import "github.com/regiellis/hyperchi/hyperchi"
BadRequestfunc BadRequest(message string) *HTTPErrorBadRequest answers 400.
Conflictfunc Conflict(message string) *HTTPErrorConflict answers 409.
ErrorFunctype ErrorFunc func(c *Context, err error)ErrorFunc renders an error a Handler returned.
Errorffunc Errorf(code int, format string, args ...any) *HTTPErrorErrorf returns an HTTPError with a formatted message.
FieldErrorsfunc FieldErrors(err error) map[string][]stringFieldErrors returns the per-field messages of a validation error from Bind or BindMessage, or nil for any other error.
Forbiddenfunc Forbidden(message string) *HTTPErrorForbidden answers 403.
HTTPErrortype HTTPError structHTTPError is an error with an HTTP status.
HTTPError.Errorfunc (e *HTTPError) Error() stringError reports the status code, message, and wrapped cause.
HTTPError.Unwrapfunc (e *HTTPError) Unwrap() errorUnwrap returns the wrapped cause, for errors.Is and errors.As.
HTTPError.Wrapfunc (e *HTTPError) Wrap(err error) *HTTPErrorWrap attaches the underlying cause for logging.
HyperChi.DefaultErrorfunc (g *HyperChi) DefaultError(c *Context, err error)DefaultError renders err for the client that asked:
HyperChi.OnErrorfunc (g *HyperChi) OnError(fn ErrorFunc)OnError replaces the default error handler.
HyperChi.RespondStatusfunc (g *HyperChi) RespondStatus(w http.ResponseWriter, r *http.Request, code int, err error)RespondStatus answers a refusal from net/http middleware (a rate limiter, an auth check, an optional module) through the app's error pipeline, so it renders like every framework denial: OnError or DefaultError, with no-store headers.
JSONErrorsfunc JSONErrors(next http.Handler) http.HandlerJSONErrors makes the routes it wraps answer every error as JSON, whatever the request's Accept header says, for API routes whose clients never ask for HTML.
NewHTTPErrorfunc NewHTTPError(code int, message string) *HTTPErrorNewHTTPError returns an error that answers with code and message.
NotFoundfunc NotFound(message string) *HTTPErrorNotFound answers 404.
Unprocessablefunc Unprocessable(message string, fields map[string][]string) *HTTPErrorUnprocessable answers 422 with per-field messages, the shape Bind returns when validation fails.
Strings 67 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
CamelCasefunc CamelCase(s string) stringCamelCase converts s to camelCase: "hello world" and "hello_world" become "helloWorld".
Dedentfunc Dedent(s string) stringDedent removes the leading whitespace that every non-blank line shares.
Indentfunc Indent(s string, indent string) stringIndent prefixes each non-blank line of s with indent.
Joinfunc Join(sep string, parts ...string) stringJoin joins parts with sep.
JoinLinesfunc JoinLines(lines ...string) stringJoinLines joins lines with "\n".
JoinSpacesfunc JoinSpaces(parts ...string) stringJoinSpaces joins parts with single spaces.
KebabCasefunc KebabCase(s string) stringKebabCase converts s to kebab-case, splitting words as CamelCase does.
PascalCasefunc PascalCase(s string) stringPascalCase converts s to PascalCase, splitting words as CamelCase does.
RandomStringfunc RandomString(length int) stringRandomString returns length random characters from a-z, A-Z, and 0-9.
Sfunc S(s string) StrS converts s to a Str.
Slugifyfunc Slugify(s string) stringSlugify creates a URL-friendly slug of lowercase ASCII letters, digits, and hyphens: "Crème Brûlée à la carte" becomes "creme-brulee-a-la-carte".
SnakeCasefunc SnakeCase(s string) stringSnakeCase converts s to snake_case, splitting words as CamelCase does: "userID" becomes "user_id" and "HTTPServer" becomes "http_server".
Strtype Str stringStr is a string with chainable methods: S(" Hi ").Trim().Lower().
Str.Capitalizefunc (s Str) Capitalize() StrCapitalize uppercases the first rune and leaves the rest unchanged.
Str.Centerfunc (s Str) Center(width int, fill ...string) StrCenter centers the string in a field width runes wide.
Str.CollapseWhitespacefunc (s Str) CollapseWhitespace() StrCollapseWhitespace trims s and replaces each run of whitespace with one space.
Str.Containsfunc (s Str) Contains(substr string) boolContains reports whether substr is in s.
Str.ContainsAnyfunc (s Str) ContainsAny(chars string) boolContainsAny reports whether any rune in chars is in s.
Str.Countfunc (s Str) Count(substr string) intCount returns the number of non-overlapping occurrences of substr.
Str.EndsWithfunc (s Str) EndsWith(suffix string) boolEndsWith reports whether s ends with suffix.
Str.FindAllfunc (s Str) FindAll(pattern string) ([]string, error)FindAll returns every match of pattern, or the compile error for an invalid pattern.
Str.Indexfunc (s Str) Index(substr string) intIndex returns the rune offset of the first occurrence of substr, or -1.
Str.IsAlphafunc (s Str) IsAlpha() boolIsAlpha reports whether s is non-empty and every rune is a letter.
Str.IsAlphaNumericfunc (s Str) IsAlphaNumeric() boolIsAlphaNumeric reports whether s is non-empty and every rune is a letter or digit.
Str.IsBlankfunc (s Str) IsBlank() boolIsBlank reports whether s is empty or only whitespace.
Str.IsDigitsfunc (s Str) IsDigits() boolIsDigits reports whether s is non-empty and every rune is a Unicode digit.
Str.IsEmptyfunc (s Str) IsEmpty() boolIsEmpty reports whether s is "".
Str.IsNotBlankfunc (s Str) IsNotBlank() boolIsNotBlank reports whether s has a non-whitespace character.
Str.IsNotEmptyfunc (s Str) IsNotEmpty() boolIsNotEmpty reports whether s is not "".
Str.Joinfunc (s Str) Join(parts []string) StrJoin joins parts with s as the separator.
Str.LastIndexfunc (s Str) LastIndex(substr string) intLastIndex returns the rune offset of the last occurrence of substr, or -1.
Str.Leftfunc (s Str) Left(n int) StrLeft returns the leftmost n runes.
Str.Lenfunc (s Str) Len() intLen returns the number of runes in the string.
Str.Lowerfunc (s Str) Lower() StrLower returns s in lowercase.
Str.Matchesfunc (s Str) Matches(pattern string) (bool, error)Matches reports whether the string contains a match of the regular expression pattern.
Str.PadLeftfunc (s Str) PadLeft(width int, fill ...string) StrPadLeft pads the string on the left to width runes, filling with the first rune of fill (a space by default).
Str.PadRightfunc (s Str) PadRight(width int, fill ...string) StrPadRight pads the string on the right to width runes, filling with the first rune of fill (a space by default).
Str.RegexReplacefunc (s Str) RegexReplace(pattern, replacement string) (Str, error)RegexReplace replaces every match of pattern, or returns the compile error for an invalid pattern.
Str.RemoveWhitespacefunc (s Str) RemoveWhitespace() StrRemoveWhitespace removes every whitespace rune.
Str.Repeatfunc (s Str) Repeat(n int) StrRepeat repeats the string n times.
Str.Replacefunc (s Str) Replace(old, new string) StrReplace replaces every occurrence of old with new.
Str.ReplaceNfunc (s Str) ReplaceN(old, new string, n int) StrReplaceN replaces the first n occurrences of old with new.
Str.Reversefunc (s Str) Reverse() StrReverse reverses s rune by rune.
Str.Rightfunc (s Str) Right(n int) StrRight returns the rightmost n runes.
Str.Slicefunc (s Str) Slice(start, end int) StrSlice returns the runes from start up to end.
Str.Splitfunc (s Str) Split(sep string) []stringSplit splits s around each sep (see strings.Split).
Str.SplitLinesfunc (s Str) SplitLines() []stringSplitLines splits s at each "\n".
Str.SplitNfunc (s Str) SplitN(sep string, n int) []stringSplitN splits s around sep into at most n parts (see strings.SplitN).
Str.SplitWhitespacefunc (s Str) SplitWhitespace() []stringSplitWhitespace splits s around runs of whitespace (see strings.Fields).
Str.StartsWithfunc (s Str) StartsWith(prefix string) boolStartsWith reports whether s begins with prefix.
Str.Stringfunc (s Str) String() stringString returns s as a plain string.
Str.Titlefunc (s Str) Title() StrTitle uppercases the first letter of each word.
Str.ToBoolfunc (s Str) ToBool() boolToBool reports whether the trimmed s is "true", "1", "yes", or "on", ignoring case.
Str.ToFloatfunc (s Str) ToFloat() (float64, error)ToFloat parses the string as a float64.
Str.ToFloatOrfunc (s Str) ToFloatOr(defaultValue float64) float64ToFloatOr parses the string as a float64, returning defaultValue when it does not parse.
Str.ToIntfunc (s Str) ToInt() (int, error)ToInt parses the string as a base-10 int.
Str.ToIntOrfunc (s Str) ToIntOr(defaultValue int) intToIntOr parses the string as a base-10 int, returning defaultValue when it does not parse.
Str.Trimfunc (s Str) Trim() StrTrim removes leading and trailing whitespace.
Str.TrimLeftfunc (s Str) TrimLeft() StrTrimLeft removes leading whitespace.
Str.TrimPrefixfunc (s Str) TrimPrefix(prefix string) StrTrimPrefix removes prefix from the start of s if it is there.
Str.TrimRightfunc (s Str) TrimRight() StrTrimRight removes trailing whitespace.
Str.TrimSuffixfunc (s Str) TrimSuffix(suffix string) StrTrimSuffix removes suffix from the end of s if it is there.
Str.Upperfunc (s Str) Upper() StrUpper returns s in uppercase.
Templatefunc Template(template string, vars map[string]string) stringTemplate replaces each {{key}} in template with vars[key].
Truncatefunc Truncate(s string, maxLen int, suffix ...string) stringTruncate shortens s to at most maxLen runes, ending in suffix ("..." by default) when it cuts.
WordCountfunc WordCount(s string) intWordCount returns the number of whitespace-separated words in s.
Wordsfunc Words(s string) []stringWords splits s around runs of whitespace.
Collections 66 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
FlatMapfunc FlatMap[T, U any](slice Slice[T], fn func(T) Slice[U]) Slice[U]FlatMap calls fn on each element and concatenates the results.
Flattenfunc Flatten[T any](slices []Slice[T]) Slice[T]Flatten concatenates slices into one new slice.
FromSlicefunc FromSlice[T any](slice []T) Slice[T]FromSlice converts slice to a Slice.
GroupByfunc GroupBy[T any, K comparable](slice Slice[T], keyFn func(T) K) map[K]Slice[T]GroupBy returns the elements grouped by keyFn, each group in its original order.
Keysfunc Keys[K comparable, V any](m map[K]V) Slice[K]Keys returns the keys of m in no particular order.
Mapfunc Map[T, U any](slice Slice[T], fn func(T) U) Slice[U]Map returns a new slice holding fn applied to each element.
MapWithIndexfunc MapWithIndex[T, U any](slice Slice[T], fn func(int, T) U) Slice[U]MapWithIndex is Map with each element's index passed to fn.
MaxByfunc MaxBy[T any](slice Slice[T], less func(T, T) bool) (T, bool)MaxBy returns the largest element by less and true, or the zero value and false when slice is empty.
MinByfunc MinBy[T any](slice Slice[T], less func(T, T) bool) (T, bool)MinBy returns the smallest element by less and true, or the zero value and false when slice is empty.
NewSlicefunc NewSlice[T any](items ...T) Slice[T]NewSlice returns a Slice of items.
Pairtype Pair structPair is one element of a Zip result.
Rangefunc Range(start, end int) Slice[int]Range returns the integers from start up to but not including end.
RangeStepfunc RangeStep(start, end, step int) Slice[int]RangeStep returns start, start+step, and so on, stopping before end.
Reducefunc Reduce[T, U any](slice Slice[T], fn func(U, T) U, initial U) UReduce folds the slice into one value, starting from initial and calling fn(accumulator, element) for each element in order.
ReduceWithIndexfunc ReduceWithIndex[T, U any](slice Slice[T], fn func(U, int, T) U, initial U) UReduceWithIndex is Reduce with each element's index passed to fn.
Repeatfunc Repeat[T any](value T, n int) Slice[T]Repeat creates a slice with value repeated n times.
Slicetype Slice []TSlice is a slice with chainable query and transform methods.
Slice.Appendfunc (s Slice[T]) Append(items ...T) Slice[T]Append returns s with items added, using the built-in append: when s has spare capacity the result shares its backing array.
Slice.Chunkfunc (s Slice[T]) Chunk(size int) []Slice[T]Chunk splits s into consecutive pieces of size elements; the last piece may be shorter.
Slice.Containsfunc (s Slice[T]) Contains(value T) boolContains reports whether an element equals value.
Slice.ContainsAllfunc (s Slice[T]) ContainsAll(values ...T) boolContainsAll reports whether s contains every one of values.
Slice.ContainsAnyfunc (s Slice[T]) ContainsAny(values ...T) boolContainsAny reports whether s contains at least one of values.
Slice.Countfunc (s Slice[T]) Count(value T) intCount returns the number of elements equal to value.
Slice.CountIffunc (s Slice[T]) CountIf(predicate func(T) bool) intCountIf returns the number of elements for which predicate is true.
Slice.Differencefunc (s Slice[T]) Difference(other Slice[T]) Slice[T]Difference returns the elements of s that are not in other, in s's order.
Slice.Everyfunc (s Slice[T]) Every(predicate func(T) bool) boolEvery reports whether predicate is true for every element.
Slice.Filterfunc (s Slice[T]) Filter(predicate func(T) bool) Slice[T]Filter returns a new slice of the elements for which predicate is true.
Slice.FilterWithIndexfunc (s Slice[T]) FilterWithIndex(predicate func(int, T) bool) Slice[T]FilterWithIndex is Filter with each element's index passed to predicate.
Slice.Findfunc (s Slice[T]) Find(predicate func(T) bool) (T, bool)Find returns the first element for which predicate is true and true, or the zero value and false.
Slice.FindIndexfunc (s Slice[T]) FindIndex(predicate func(T) bool) intFindIndex returns the index of the first element for which predicate is true, or -1.
Slice.Firstfunc (s Slice[T]) First() (T, bool)First returns the first element and true, or the zero value and false when s is empty.
Slice.ForEachfunc (s Slice[T]) ForEach(fn func(T))ForEach calls fn with each element in order.
Slice.ForEachWithIndexfunc (s Slice[T]) ForEachWithIndex(fn func(int, T))ForEachWithIndex calls fn with each index and element in order.
Slice.Getfunc (s Slice[T]) Get(index int) (T, bool)Get returns the element at index and true, or the zero value and false when index is out of range.
Slice.GetOrfunc (s Slice[T]) GetOr(index int, defaultValue T) TGetOr returns the element at index, or defaultValue when index is out of range.
Slice.Indexfunc (s Slice[T]) Index(value T) intIndex returns the index of the first element equal to value, or -1.
Slice.Insertfunc (s Slice[T]) Insert(index int, items ...T) Slice[T]Insert returns a new slice with items placed before index.
Slice.Intersectfunc (s Slice[T]) Intersect(other Slice[T]) Slice[T]Intersect returns the elements of s that are also in other, without duplicates, in s's order.
Slice.IsEmptyfunc (s Slice[T]) IsEmpty() boolIsEmpty reports whether s has no elements.
Slice.IsNotEmptyfunc (s Slice[T]) IsNotEmpty() boolIsNotEmpty reports whether s has at least one element.
Slice.Lastfunc (s Slice[T]) Last() (T, bool)Last returns the last element and true, or the zero value and false when s is empty.
Slice.LastIndexfunc (s Slice[T]) LastIndex(value T) intLastIndex returns the index of the last element equal to value, or -1.
Slice.Lenfunc (s Slice[T]) Len() intLen returns the number of elements.
Slice.Nonefunc (s Slice[T]) None(predicate func(T) bool) boolNone reports whether predicate is false for every element.
Slice.OrEmptyfunc (s Slice[T]) OrEmpty() Slice[T]OrEmpty returns a non-nil slice so JSON encodes an empty collection as [].
Slice.Partitionfunc (s Slice[T]) Partition(predicate func(T) bool) (Slice[T], Slice[T])Partition returns the elements for which predicate is true, then the rest, each in original order.
Slice.Prependfunc (s Slice[T]) Prepend(items ...T) Slice[T]Prepend returns a new slice with items followed by the elements of s.
Slice.Removefunc (s Slice[T]) Remove(index int) Slice[T]Remove returns a new slice without the element at index.
Slice.RemoveAllfunc (s Slice[T]) RemoveAll(value T) Slice[T]RemoveAll returns a new slice without any element equal to value.
Slice.RemoveValuefunc (s Slice[T]) RemoveValue(value T) Slice[T]RemoveValue returns a new slice without the first element equal to value, or s itself when there is none.
Slice.Reversefunc (s Slice[T]) Reverse() Slice[T]Reverse returns a reversed copy of s.
Slice.Skipfunc (s Slice[T]) Skip(n int) Slice[T]Skip returns s without its first n elements.
Slice.SkipLastfunc (s Slice[T]) SkipLast(n int) Slice[T]SkipLast returns s without its last n elements.
Slice.Slicefunc (s Slice[T]) Slice(start, end int) Slice[T]Slice returns the elements from start up to end.
Slice.Somefunc (s Slice[T]) Some(predicate func(T) bool) boolSome reports whether predicate is true for at least one element.
Slice.Sortfunc (s Slice[T]) Sort(less func(T, T) bool) Slice[T]Sort returns a sorted copy of s, ordered by less.
Slice.Takefunc (s Slice[T]) Take(n int) Slice[T]Take returns the first n elements, or all of s when it is shorter.
Slice.TakeLastfunc (s Slice[T]) TakeLast(n int) Slice[T]TakeLast returns the last n elements, or all of s when it is shorter.
Slice.ToSlicefunc (s Slice[T]) ToSlice() []TToSlice returns s as a plain slice, sharing its backing array.
Slice.Unionfunc (s Slice[T]) Union(other Slice[T]) Slice[T]Union returns the elements of s followed by those of other, without duplicates (see Unique).
Slice.Uniquefunc (s Slice[T]) Unique() Slice[T]Unique returns the first occurrence of each element, preserving order.
Timesfunc Times[T any](n int, fn func(int) T) Slice[T]Times calls fn with 0..n-1 and collects the results.
ToMapfunc ToMap[T any, K comparable](slice Slice[T], keyFn func(T) K) map[K]TToMap returns a map from keyFn(element) to element.
ToMapValuefunc ToMapValue[T any, K comparable, V any](slice Slice[T], keyFn func(T) K, valueFn func(T) V) map[K]VToMapValue returns a map from keyFn(element) to valueFn(element).
Valuesfunc Values[K comparable, V any](m map[K]V) Slice[V]Values returns the values of m in no particular order.
Zipfunc Zip[T, U any](slice1 Slice[T], slice2 Slice[U]) Slice[Pair[T, U]]Zip pairs elements at the same index.
JSON and HTTP client 82 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
Deletefunc Delete(url string) (*HTTPResponse, error)Delete sends a DELETE request with a new default HTTPClient.
FetchJSONfunc FetchJSON(url string) (JSON, error)FetchJSON GETs url and parses the body as a JSON object.
FetchJSONOrfunc FetchJSONOr(url string) JSONFetchJSONOr is FetchJSON, returning an empty object on any error (request, body read, or decode).
FetchTextfunc FetchText(url string) (string, error)FetchText GETs url and returns the body as a string.
FetchTextOrfunc FetchTextOr(url, defaultValue string) stringFetchTextOr is FetchText, returning defaultValue on any error.
FromJSONfunc FromJSON(jsonStr string) (JSON, error)FromJSON parses a JSON object.
FromJSONOrfunc FromJSONOr(jsonStr string) JSONFromJSONOr parses a JSON object, or returns an empty one when jsonStr is not a valid object.
Getfunc Get(url string) (*HTTPResponse, error)Get sends a GET request with a new default HTTPClient.
HTTPClienttype HTTPClient structHTTPClient wraps http.Client with a base URL and default headers.
HTTPClient.Deletefunc (h *HTTPClient) Delete(path string) (*HTTPResponse, error)Delete sends a DELETE request.
HTTPClient.DeleteWithContextfunc (h *HTTPClient) DeleteWithContext(ctx context.Context, path string) (*HTTPResponse, error)DeleteWithContext is Delete with the caller's cancellation and deadline.
HTTPClient.Getfunc (h *HTTPClient) Get(path string) (*HTTPResponse, error)Get sends a GET request.
HTTPClient.GetWithContextfunc (h *HTTPClient) GetWithContext(ctx context.Context, path string) (*HTTPResponse, error)GetWithContext is Get with the caller's cancellation and deadline.
HTTPClient.Patchfunc (h *HTTPClient) Patch(path string, body any) (*HTTPResponse, error)Patch sends a PATCH request, encoding body as Post does.
HTTPClient.PatchWithContextfunc (h *HTTPClient) PatchWithContext(ctx context.Context, path string, body any) (*HTTPResponse, error)PatchWithContext is Patch with the caller's cancellation and deadline.
HTTPClient.Postfunc (h *HTTPClient) Post(path string, body any) (*HTTPResponse, error)Post sends a POST request.
HTTPClient.PostFormfunc (h *HTTPClient) PostForm(path string, data url.Values) (*HTTPResponse, error)PostForm sends data as an application/x-www-form-urlencoded POST.
HTTPClient.PostFormWithContextfunc (h *HTTPClient) PostFormWithContext(ctx context.Context, path string, data url.Values) (*HTTPResponse, error)PostFormWithContext is PostForm with the caller's cancellation and deadline.
HTTPClient.PostWithContextfunc (h *HTTPClient) PostWithContext(ctx context.Context, path string, body any) (*HTTPResponse, error)PostWithContext is Post with the caller's cancellation and deadline.
HTTPClient.Putfunc (h *HTTPClient) Put(path string, body any) (*HTTPResponse, error)Put sends a PUT request, encoding body as Post does.
HTTPClient.PutWithContextfunc (h *HTTPClient) PutWithContext(ctx context.Context, path string, body any) (*HTTPResponse, error)PutWithContext is Put with the caller's cancellation and deadline.
HTTPClient.WithAuthfunc (h *HTTPClient) WithAuth(username, password string) *HTTPClientWithAuth sends HTTP Basic credentials with every request.
HTTPClient.WithBaseURLfunc (h *HTTPClient) WithBaseURL(baseURL string) *HTTPClientWithBaseURL sets the URL that relative request paths are joined to.
HTTPClient.WithBearerTokenfunc (h *HTTPClient) WithBearerToken(token string) *HTTPClientWithBearerToken sends "Authorization: Bearer <token>" with every request.
HTTPClient.WithHeaderfunc (h *HTTPClient) WithHeader(key, value string) *HTTPClientWithHeader sets a header sent with every request.
HTTPClient.WithHeadersfunc (h *HTTPClient) WithHeaders(headers map[string]string) *HTTPClientWithHeaders sets several headers sent with every request.
HTTPClient.WithJSONHeadersfunc (h *HTTPClient) WithJSONHeaders() *HTTPClientWithJSONHeaders sends Content-Type and Accept as application/json.
HTTPClient.WithTimeoutfunc (h *HTTPClient) WithTimeout(timeout time.Duration) *HTTPClientWithTimeout sets the total time limit for each request.
HTTPResponsetype HTTPResponse structHTTPResponse wraps an http.Response.
HTTPResponse.Closefunc (r *HTTPResponse) Close() errorClose closes the response body.
HTTPResponse.Headerfunc (r *HTTPResponse) Header(key string) stringHeader returns the first value of the response header key.
HTTPResponse.Headersfunc (r *HTTPResponse) Headers() map[string][]stringHeaders returns the response headers.
HTTPResponse.IsErrorfunc (r *HTTPResponse) IsError() boolIsError reports whether the status is 400 or above.
HTTPResponse.IsOKfunc (r *HTTPResponse) IsOK() boolIsOK reports whether the status is exactly 200.
HTTPResponse.IsSuccessfunc (r *HTTPResponse) IsSuccess() boolIsSuccess reports whether the status is 2xx.
HTTPResponse.JSONfunc (r *HTTPResponse) JSON() (JSON, error)JSON reads and closes the body and parses it as a JSON object.
HTTPResponse.JSONOrfunc (r *HTTPResponse) JSONOr() JSONJSONOr returns JSON, or an empty object when reading or parsing fails.
HTTPResponse.Parsefunc (r *HTTPResponse) Parse(v any) errorParse decodes the JSON body into v and closes the body.
HTTPResponse.StatusCodefunc (r *HTTPResponse) StatusCode() intStatusCode returns the HTTP status code.
HTTPResponse.Textfunc (r *HTTPResponse) Text() (string, error)Text reads and closes the body and returns it as a string.
HTTPResponse.TextOrfunc (r *HTTPResponse) TextOr(defaultValue string) stringTextOr returns Text, or defaultValue when reading fails.
JSONtype JSON map[string]anyJSON is a decoded JSON object with typed getters.
JSON.Clonefunc (j JSON) Clone() JSONClone returns a shallow copy: nested maps and slices are shared.
JSON.Deletefunc (j JSON) Delete(key string) JSONDelete removes key and returns j.
JSON.Getfunc (j JSON) Get(key string) anyGet returns the value at key, or nil when it is missing.
JSON.GetBoolfunc (j JSON) GetBool(key string) boolGetBool returns the bool at key, or false when it is missing or not a bool.
JSON.GetBoolOrfunc (j JSON) GetBoolOr(key string, defaultValue bool) boolGetBoolOr returns the bool at key, or defaultValue when it is missing or not a bool.
JSON.GetFloatfunc (j JSON) GetFloat(key string) float64GetFloat returns GetFloatOr(key, 0).
JSON.GetFloatOrfunc (j JSON) GetFloatOr(key string, defaultValue float64) float64GetFloatOr returns the value at key as a float64.
JSON.GetIntfunc (j JSON) GetInt(key string) intGetInt returns GetIntOr(key, 0).
JSON.GetIntOrfunc (j JSON) GetIntOr(key string, defaultValue int) intGetIntOr returns the value at key as an int.
JSON.GetJSONfunc (j JSON) GetJSON(key string) JSONGetJSON returns the nested object at key, or an empty JSON when it is missing, nil, or not an object.
JSON.GetSlicefunc (j JSON) GetSlice(key string) []anyGetSlice returns the array at key, or an empty slice when it is missing or not a []any.
JSON.GetStringfunc (j JSON) GetString(key string) stringGetString returns the string at key, or "" when it is missing or not a string.
JSON.GetStringOrfunc (j JSON) GetStringOr(key, defaultValue string) stringGetStringOr returns the string at key, or defaultValue when it is missing or not a string.
JSON.Hasfunc (j JSON) Has(key string) boolHas reports whether key is present, even with a null value.
JSON.Keysfunc (j JSON) Keys() []stringKeys returns the keys in no particular order.
JSON.Mergefunc (j JSON) Merge(other JSON) JSONMerge copies every key of other into j, overwriting existing keys, and returns j.
JSON.Setfunc (j JSON) Set(key string, value any) JSONSet stores value at key and returns j, allocating a map when j is nil.
JSON.ToPrettyStringfunc (j JSON) ToPrettyString() stringToPrettyString encodes j as JSON indented by two spaces, or "{}" when encoding fails.
JSON.ToStringfunc (j JSON) ToString() stringToString encodes j as compact JSON, or "{}" when encoding fails.
JSON.Valuesfunc (j JSON) Values() []anyValues returns the values in no particular order.
NewHTTPClientfunc NewHTTPClient() *HTTPClientNewHTTPClient returns an HTTPClient with a 30-second timeout and no default headers.
NewJSONfunc NewJSON() JSONNewJSON returns an empty JSON object.
NewQueryParamsfunc NewQueryParams() *QueryParamsNewQueryParams returns an empty QueryParams.
ParseJSONfunc ParseJSON[T any](jsonStr string) (T, error)ParseJSON decodes jsonStr into a new T.
ParseJSONOrfunc ParseJSONOr[T any](jsonStr string, defaultValue T) TParseJSONOr decodes jsonStr into a new T, or returns defaultValue when decoding fails.
Postfunc Post(url string, body any) (*HTTPResponse, error)Post sends body as a JSON POST with a new default HTTPClient.
PostFormfunc PostForm(url string, data url.Values) (*HTTPResponse, error)PostForm sends data as a form POST with a new default HTTPClient.
Putfunc Put(url string, body any) (*HTTPResponse, error)Put sends body as a JSON PUT with a new default HTTPClient.
QueryParamstype QueryParams structQueryParams builds a URL query string.
QueryParams.Addfunc (qp *QueryParams) Add(key, value string) *QueryParamsAdd adds value to key, keeping earlier values.
QueryParams.Setfunc (qp *QueryParams) Set(key, value string) *QueryParamsSet sets key to value, replacing earlier values.
QueryParams.SetBoolfunc (qp *QueryParams) SetBool(key string, value bool) *QueryParamsSetBool sets key to "true" or "false".
QueryParams.SetIffunc (qp *QueryParams) SetIf(condition bool, key, value string) *QueryParamsSetIf sets key to value when condition is true.
QueryParams.SetIfNotEmptyfunc (qp *QueryParams) SetIfNotEmpty(key, value string) *QueryParamsSetIfNotEmpty sets key to value when value is not "".
QueryParams.SetIntfunc (qp *QueryParams) SetInt(key string, value int) *QueryParamsSetInt sets key to the decimal form of value.
QueryParams.Stringfunc (qp *QueryParams) String() stringString returns the encoded query, sorted by key, without a leading "?".
QueryParams.URLfunc (qp *QueryParams) URL(baseURL string) stringURL appends the query to baseURL with "?", or with "&" when baseURL already has a query.
QueryParams.Valuesfunc (qp *QueryParams) Values() url.ValuesValues returns the underlying url.Values, not a copy.
ToJSONfunc ToJSON(v any) stringToJSON encodes v as compact JSON, or "{}" when encoding fails.
ToPrettyJSONfunc ToPrettyJSON(v any) stringToPrettyJSON encodes v as JSON indented by two spaces, or "{}" when encoding fails.
Error handling 29 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
Catchfunc Catch(fn func() error, handler func(error))Catch calls fn through Try and passes any error, including a recovered panic, to handler.
CatchValuefunc CatchValue[T any](fn func() (T, error), handler func(error) T) TCatchValue calls fn through TryValue and returns its value.
Chaintype Chain structChain runs a sequence of steps and stops at the first error, which it keeps.
Chain.Dofunc (c *Chain) Do(fn func() error) *ChainDo calls fn unless an earlier step failed.
Chain.DoValuefunc (c *Chain) DoValue(fn func() error) *ChainDoValue is the same as Do.
Chain.Errorfunc (c *Chain) Error() errorError returns the first error a step returned, or nil if every step succeeded.
Chain.Resultfunc (c *Chain) Result() errorResult is the same as Error.
Chain.Successfunc (c *Chain) Success() boolSuccess reports whether every step so far succeeded.
Defaultfunc Default[T any](value T, err error, defaultValue T) TDefault returns value if err is nil, otherwise defaultValue.
ErrorHandlertype ErrorHandler structErrorHandler controls what Must does with a non-nil error: log it with the caller's file and line, then panic.
ErrorHandler.Mustfunc (eh *ErrorHandler) Must(err error)Must panics with err if err is not nil.
ErrorHandler.Silentfunc (eh *ErrorHandler) Silent() *ErrorHandlerSilent makes Must panic without logging, for code that reports the panic at a higher level.
ErrorHandler.WithLoggerfunc (eh *ErrorHandler) WithLogger(logger func(string, ...any)) *ErrorHandlerWithLogger sets the printf-style function Must logs through.
ErrorInfotype ErrorInfo structErrorInfo pairs an error with the file, line, and function where GetErrorInfo was called.
ErrorInfo.Stringfunc (ei *ErrorInfo) String() stringString formats the error as "file:line in function: error".
GetErrorInfofunc GetErrorInfo(err error) *ErrorInfoGetErrorInfo records err with the caller's file, line, and function name.
Ignorefunc Ignore(err error)Ignore discards err.
IgnoreValuefunc IgnoreValue[T any](value T, err error) TIgnoreValue returns value and discards err.
Mustfunc Must(err error)Must panics with err if err is not nil, logging the caller's file and line first through the package default handler (see SetDefaultLogger and SetDefaultSilent).
MustValuefunc MustValue[T any](value T, err error) TMustValue returns value if err is nil and otherwise panics like Must.
NewChainfunc NewChain() *ChainNewChain returns an empty Chain with no error.
NewErrorHandlerfunc NewErrorHandler() *ErrorHandlerNewErrorHandler returns an ErrorHandler that logs with log.Printf before panicking.
OrLogfunc OrLog[T any](value T, err error) TOrLog returns value if err is nil.
OrLogDefaultfunc OrLogDefault[T any](value T, err error, defaultValue T) TOrLogDefault returns value if err is nil.
OrPanicfunc OrPanic[T any](value T, err error) TOrPanic returns value if err is nil and otherwise panics with err.
SetDefaultLoggerfunc SetDefaultLogger(logger func(string, ...any))SetDefaultLogger sets the printf-style function the package-level Must and MustValue log through.
SetDefaultSilentfunc SetDefaultSilent(silent bool)SetDefaultSilent sets whether the package-level Must and MustValue skip logging before they panic.
Tryfunc Try(fn func() error) (err error)Try calls fn and returns its error.
TryValuefunc TryValue[T any](fn func() (T, error)) (result T, err error)TryValue calls fn and returns its result, recovering a panic as Try does.
Pointers and values 42 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
IsNilfunc IsNil(v any) boolIsNil reports whether v is nil, including a typed nil pointer, slice, map, channel, or func stored in an interface.
IsNotNilfunc IsNotNil(v any) boolIsNotNil is !IsNil(v).
NewSafefunc NewSafe[T any](ptr *T) Safe[T]NewSafe wraps ptr, which may be nil.
NewSafeMapfunc NewSafeMap[K comparable, V any](m map[K]V) SafeMap[K, V]NewSafeMap wraps m, which may be nil.
NewSafeSlicefunc NewSafeSlice[T any](slice []T) SafeSlice[T]NewSafeSlice wraps slice, which may be nil.
NewSafeStringfunc NewSafeString(s *string) SafeStringNewSafeString wraps s, which may be nil.
Ptrfunc Ptr[T any](v T) *TPtr returns a pointer to a copy of v, for filling pointer fields from literals: Ptr(42), Ptr("name").
Safetype Safe structSafe wraps a possibly nil pointer so a value can be read and transformed without nil checks.
Safe.Filterfunc (s Safe[T]) Filter(predicate func(T) bool) Safe[T]Filter returns s when its value is non-nil and predicate is true for it, and a nil Safe otherwise.
Safe.FlatMapfunc (s Safe[T]) FlatMap(fn func(T) Safe[T]) Safe[T]FlatMap returns fn applied to the value.
Safe.Getfunc (s Safe[T]) Get() TGet returns the wrapped value, or the zero value of T when it is nil.
Safe.GetOrfunc (s Safe[T]) GetOr(defaultValue T) TGetOr returns the wrapped value, or defaultValue when it is nil.
Safe.IfPresentfunc (s Safe[T]) IfPresent(fn func(T))IfPresent calls fn with the value when it is not nil.
Safe.IsNilfunc (s Safe[T]) IsNil() boolIsNil reports whether the wrapped pointer is nil.
Safe.IsNotNilfunc (s Safe[T]) IsNotNil() boolIsNotNil reports whether the wrapped pointer is not nil.
Safe.Mapfunc (s Safe[T]) Map(fn func(T) T) Safe[T]Map returns a Safe holding fn applied to the value.
Safe.OrElsefunc (s Safe[T]) OrElse(other Safe[T]) Safe[T]OrElse returns s when its value is not nil, and other otherwise.
SafeMaptype SafeMap structSafeMap wraps a map, which may be nil, for lookups that return Safe values.
SafeMap.Getfunc (sm SafeMap[K, V]) Get(key K) Safe[V]Get returns a Safe holding a copy of the value at key, or a nil Safe when key is absent.
SafeMap.GetOrfunc (sm SafeMap[K, V]) GetOr(key K, defaultValue V) VGetOr returns the value at key, or defaultValue when key is absent.
SafeMap.Hasfunc (sm SafeMap[K, V]) Has(key K) boolHas reports whether key is present.
SafeMap.IsEmptyfunc (sm SafeMap[K, V]) IsEmpty() boolIsEmpty reports whether the map has no entries.
SafeMap.IsNotEmptyfunc (sm SafeMap[K, V]) IsNotEmpty() boolIsNotEmpty reports whether the map has at least one entry.
SafeMap.Keysfunc (sm SafeMap[K, V]) Keys() []KKeys returns the keys in no particular order, or an empty slice for a nil map.
SafeMap.Lenfunc (sm SafeMap[K, V]) Len() intLen returns the number of entries.
SafeMap.Valuesfunc (sm SafeMap[K, V]) Values() []VValues returns the values in no particular order, or an empty slice for a nil map.
SafeSlicetype SafeSlice structSafeSlice wraps a slice for bounds-checked element access.
SafeSlice.Firstfunc (ss SafeSlice[T]) First() Safe[T]First returns Get(0).
SafeSlice.Getfunc (ss SafeSlice[T]) Get(index int) Safe[T]Get returns a Safe pointing at the element at index, or a nil Safe when index is out of range.
SafeSlice.IsEmptyfunc (ss SafeSlice[T]) IsEmpty() boolIsEmpty reports whether the slice has no elements.
SafeSlice.IsNotEmptyfunc (ss SafeSlice[T]) IsNotEmpty() boolIsNotEmpty reports whether the slice has at least one element.
SafeSlice.Lastfunc (ss SafeSlice[T]) Last() Safe[T]Last returns a Safe pointing at the last element, or a nil Safe when the slice is empty.
SafeSlice.Lenfunc (ss SafeSlice[T]) Len() intLen returns the number of elements.
SafeStringtype SafeString structSafeString wraps a possibly nil *string.
SafeString.Containsfunc (ss SafeString) Contains(substr string) boolContains reports whether the string contains substr.
SafeString.Getfunc (ss SafeString) Get() stringGet returns the string, or "" when the pointer is nil.
SafeString.GetOrfunc (ss SafeString) GetOr(defaultValue string) stringGetOr returns the string, or defaultValue when the pointer is nil.
SafeString.IsEmptyfunc (ss SafeString) IsEmpty() boolIsEmpty reports whether the pointer is nil or the string is "".
SafeString.IsNotEmptyfunc (ss SafeString) IsNotEmpty() boolIsNotEmpty reports whether the pointer is non-nil and the string is not "".
SafeString.Trimfunc (ss SafeString) Trim() SafeStringTrim returns a SafeString holding the string without leading and trailing whitespace.
Valuefunc Value[T any](ptr *T) TValue returns *ptr, or the zero value of T when ptr is nil.
ValueOrfunc ValueOr[T any](ptr *T, defaultValue T) TValueOr returns *ptr, or defaultValue when ptr is nil.
Files 49 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
AppendFilefunc AppendFile(filename, content string) errorAppendFile appends content to filename, creating it with mode 0644 if it does not exist.
AppendLinefunc AppendLine(filename, line string) errorAppendLine appends line to filename, adding a trailing newline when line lacks one.
CopyFilefunc CopyFile(src, dst string) errorCopyFile copies the contents of src to dst, creating dst's parent directories and truncating an existing dst.
CreateDirfunc CreateDir(path string) errorCreateDir creates path and any missing parents with mode 0755.
Dirfunc Dir(path string) *DirHelperDir returns a DirHelper for path.
DirHelpertype DirHelper structDirHelper chains operations on one directory path.
DirHelper.Createfunc (d *DirHelper) Create() *DirHelperCreate creates the directory and any missing parents.
DirHelper.Dirsfunc (d *DirHelper) Dirs() []stringDirs returns the paths of the directory's subdirectories.
DirHelper.Errorfunc (d *DirHelper) Error() errorError returns the error from the first failed operation, or nil.
DirHelper.Existsfunc (d *DirHelper) Exists() boolExists reports whether the path exists and is a directory.
DirHelper.Filesfunc (d *DirHelper) Files() []stringFiles returns the paths of the directory's non-directory entries.
DirHelper.Findfunc (d *DirHelper) Find(pattern string) []stringFind returns the files under the directory whose base name matches pattern (see FindFiles).
DirHelper.Listfunc (d *DirHelper) List() ([]string, error)List returns the paths of the directory's entries (see ListAll), or the stored error from an earlier step.
DirHelper.Pathfunc (d *DirHelper) Path() stringPath returns the directory path.
DirHelper.Removefunc (d *DirHelper) Remove() *DirHelperRemove removes the directory and everything under it.
DirHelper.Walkfunc (d *DirHelper) Walk() []stringWalk returns every non-directory under the directory (see WalkFiles).
Filefunc File(path string) *FileHelperFile returns a FileHelper for path.
FileExistsfunc FileExists(filename string) boolFileExists reports whether filename can be stat'd.
FileHelpertype FileHelper structFileHelper chains operations on one file path.
FileHelper.Appendfunc (f *FileHelper) Append(content string) *FileHelperAppend appends content to the file (see AppendFile).
FileHelper.Copyfunc (f *FileHelper) Copy(dst string) *FileHelperCopy copies the file to dst (see CopyFile).
FileHelper.Deletefunc (f *FileHelper) Delete() *FileHelperDelete removes the file.
FileHelper.Errorfunc (f *FileHelper) Error() errorError returns the error from the first failed operation, or nil.
FileHelper.Existsfunc (f *FileHelper) Exists() boolExists reports whether the path exists (see FileExists).
FileHelper.Movefunc (f *FileHelper) Move(dst string) *FileHelperMove renames the file to dst (see MoveFile).
FileHelper.Pathfunc (f *FileHelper) Path() stringPath returns the file path, which Move updates.
FileHelper.Readfunc (f *FileHelper) Read() (string, error)Read returns the file's contents, or the stored error from an earlier step.
FileHelper.ReadOrfunc (f *FileHelper) ReadOr(defaultContent string) stringReadOr returns the file's contents, or defaultContent when Read fails.
FileHelper.Sizefunc (f *FileHelper) Size() int64Size returns the file size in bytes, or 0 when it cannot be stat'd.
FileHelper.Writefunc (f *FileHelper) Write(content string) *FileHelperWrite replaces the file's contents (see WriteFile).
FileNotExistsfunc FileNotExists(filename string) boolFileNotExists is !FileExists(filename).
FileSizefunc FileSize(filename string) int64FileSize returns the size of filename in bytes, or 0 when it cannot be stat'd.
FindFilesfunc FindFiles(root, pattern string) []stringFindFiles returns every non-directory under root whose base name matches pattern (filepath.Match syntax).
IsDirfunc IsDir(path string) boolIsDir reports whether path exists and is a directory.
IsFilefunc IsFile(path string) boolIsFile reports whether path exists and is not a directory.
ListAllfunc ListAll(dir string) []stringListAll returns the paths of every entry in dir, not recursing.
ListDirsfunc ListDirs(dir string) []stringListDirs returns the paths of the subdirectories of dir, not recursing.
ListFilesfunc ListFiles(dir string) []stringListFiles returns the paths (dir joined with the name) of the non-directory entries in dir, not recursing.
MoveFilefunc MoveFile(src, dst string) errorMoveFile renames src to dst, creating dst's parent directories.
ReadFilefunc ReadFile(filename string) (string, error)ReadFile reads a whole file as a string.
ReadFileLinesfunc ReadFileLines(filename string) ([]string, error)ReadFileLines reads a file and returns its lines without line endings ("\n" or "\r\n").
ReadFileOrfunc ReadFileOr(filename, defaultContent string) stringReadFileOr reads a file, returning defaultContent when it cannot be read for any reason (missing, unreadable, a directory).
RemoveDirfunc RemoveDir(path string) errorRemoveDir removes path and everything under it.
RemoveFilefunc RemoveFile(filename string) errorRemoveFile removes filename, or an empty directory.
TempDirfunc TempDir(pattern string) (string, error)TempDir creates a directory in os.TempDir (see os.MkdirTemp) and returns its path.
TempFilefunc TempFile(pattern string) (string, error)TempFile creates an empty file in os.TempDir with a name built from pattern (see os.CreateTemp) and returns its path.
WalkDirsfunc WalkDirs(root string) []stringWalkDirs returns the path of every directory under root, recursively, excluding root itself.
WalkFilesfunc WalkFiles(root string) []stringWalkFiles returns the path of every non-directory under root, recursively.
WriteFilefunc WriteFile(filename, content string) errorWriteFile writes content to filename with mode 0644, creating parent directories as needed.
Environment 36 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
Envtype Env structEnv reads configuration from .env files, the process environment, and values set in code.
Env.Allfunc (e *Env) All() map[string]stringAll returns every variable from every source, merged with the same precedence as Get.
Env.Clearfunc (e *Env) Clear()Clear forgets every .env and Set value and the list of loaded files, so files can be loaded again.
Env.Dumpfunc (e *Env) Dump() map[string]stringDump returns a copy of the values loaded from .env files and set with Set.
Env.Getfunc (e *Env) Get(key string) stringGet returns the value for key: a value set in code, else the process environment, else a .env value (see Env for OverrideSystemEnv).
Env.GetBoolfunc (e *Env) GetBool(key string) boolGetBool reports whether the value for key is "true", "1", "yes", or "on", ignoring case.
Env.GetBoolOrfunc (e *Env) GetBoolOr(key string, defaultValue bool) boolGetBoolOr returns defaultValue when key is unset or empty, and GetBool otherwise.
Env.GetFloatfunc (e *Env) GetFloat(key string) (float64, error)GetFloat parses the value for key as a float64.
Env.GetFloatOrfunc (e *Env) GetFloatOr(key string, defaultValue float64) float64GetFloatOr returns the value for key as a float64, or defaultValue when it is unset, empty, or not a number.
Env.GetIntfunc (e *Env) GetInt(key string) (int, error)GetInt parses the value for key as an int.
Env.GetIntOrfunc (e *Env) GetIntOr(key string, defaultValue int) intGetIntOr returns the value for key as an int, or defaultValue when it is unset, empty, or not an integer.
Env.GetOrfunc (e *Env) GetOr(key, defaultValue string) stringGetOr returns the value for key, or defaultValue when it is unset or empty.
Env.GetSlicefunc (e *Env) GetSlice(key string) []stringGetSlice splits the value for key on commas and trims each part.
Env.Hasfunc (e *Env) Has(key string) boolHas reports whether any source has key, even with an empty value.
Env.Keysfunc (e *Env) Keys() []stringKeys returns the keys of All in no particular order.
Env.LoadConfigfunc (e *Env) LoadConfig(config EnvConfig) errorLoadConfig loads config.Files (or the LoadDefault files), applies config.Defaults, and returns an error listing any config.Required key that is still unset.
Env.LoadDefaultfunc (e *Env) LoadDefault() errorLoadDefault loads .env, .env.local, and .env.development from the working directory, in that order, skipping any that do not exist.
Env.LoadFilefunc (e *Env) LoadFile(filename string) errorLoadFile reads KEY=value lines from filename.
Env.LoadFilesfunc (e *Env) LoadFiles(filenames ...string) errorLoadFiles calls LoadFile for each name in order and stops at the first error.
Env.LoadedFilesfunc (e *Env) LoadedFiles() []stringLoadedFiles returns a copy of the names of the files loaded so far, in load order.
Env.Savefunc (e *Env) Save(filename string) errorSave writes the current .env variables to filename, sorted by key.
Env.Setfunc (e *Env) Set(key, value string)Set sets a value in code (in memory only).
Env.SetSystemfunc (e *Env) SetSystem(key, value string) errorSetSystem calls Set and also sets key in the process environment.
Env.Validatefunc (e *Env) Validate(required []string) errorValidate returns an error listing every key in required that no source has.
EnvConfigtype EnvConfig structEnvConfig configures Env.LoadConfig.
GetEnvfunc GetEnv(key string) stringGetEnv returns the package-level Env's value for key (see Env.Get).
GetEnvBoolfunc GetEnvBool(key string) boolGetEnvBool reports whether the value for key is "true", "1", "yes", or "on", ignoring case.
GetEnvBoolOrfunc GetEnvBoolOr(key string, defaultValue bool) boolGetEnvBoolOr returns defaultValue when key is unset or empty, and GetEnvBool otherwise.
GetEnvIntfunc GetEnvInt(key string) (int, error)GetEnvInt parses the value for key as an int.
GetEnvIntOrfunc GetEnvIntOr(key string, defaultValue int) intGetEnvIntOr returns the value for key as an int, or defaultValue when it is unset, empty, or not an integer.
GetEnvOrfunc GetEnvOr(key, defaultValue string) stringGetEnvOr returns the value for key, or defaultValue when it is unset or empty.
HasEnvfunc HasEnv(key string) boolHasEnv reports whether any source has key, even with an empty value.
LoadEnvfunc LoadEnv(filenames ...string) errorLoadEnv loads the named .env files into the package-level Env, or the LoadDefault files when no names are given.
NewEnvfunc NewEnv() *EnvNewEnv returns an empty Env.
RequireEnvfunc RequireEnv(keys ...string) errorRequireEnv returns an error listing every key that no source has.
SetEnvfunc SetEnv(key, value string) errorSetEnv sets key on the package-level Env and in the process environment.
Logging 37 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
ConfigureLoggerfunc ConfigureLogger(config LoggerConfig)ConfigureLogger applies config to the logger behind the package-level functions.
Debugfunc Debug(format string, args ...any)Debug logs a formatted message at DEBUG level through the default logger.
Errorfunc Error(format string, args ...any)Error logs a formatted message at ERROR level through the default logger.
Fatalfunc Fatal(format string, args ...any)Fatal logs a formatted message at FATAL level through the default logger, then exits the process with status 1.
Infofunc Info(format string, args ...any)Info logs a formatted message at INFO level through the default logger.
Logfunc Log(args ...any)Log logs its arguments, joined as fmt.Sprint does, at DEBUG level.
LogErrorfunc LogError(err error, context ...string)LogError logs err at ERROR level as "Error (context...): err".
LogErrorffunc LogErrorf(err error, format string, args ...any)LogErrorf logs err at ERROR level with a formatted context, as "Error (context): err".
LogLeveltype LogLevel intLogLevel is a Logger severity.
LogLevel.Colorfunc (l LogLevel) Color() stringColor returns the ANSI escape that colors the level name, or the reset code for an unknown level.
LogLevel.Stringfunc (l LogLevel) String() stringString returns the level name, such as "WARN", or "UNKNOWN".
Logffunc Logf(format string, args ...any)Logf logs a formatted message at DEBUG level.
Loggertype Logger structLogger writes leveled, printf-style log lines of the form "2006-01-02 15:04:05 [LEVEL] [prefix] file:line message".
Logger.Debugfunc (l *Logger) Debug(format string, args ...any)Debug logs a formatted message at DEBUG level.
Logger.Errorfunc (l *Logger) Error(format string, args ...any)Error logs a formatted message at ERROR level.
Logger.Fatalfunc (l *Logger) Fatal(format string, args ...any)Fatal logs a formatted message at FATAL level, then exits the process with status 1.
Logger.Infofunc (l *Logger) Info(format string, args ...any)Info logs a formatted message at INFO level.
Logger.SetColoredfunc (l *Logger) SetColored(colored bool) *LoggerSetColored turns ANSI colors on the level name on or off.
Logger.SetLevelfunc (l *Logger) SetLevel(level LogLevel) *LoggerSetLevel sets the lowest level the logger writes.
Logger.SetOutputfunc (l *Logger) SetOutput(w io.Writer) *LoggerSetOutput sets the writer log lines go to.
Logger.SetPrefixfunc (l *Logger) SetPrefix(prefix string) *LoggerSetPrefix sets text written in brackets after the level on every line.
Logger.SetShowCallerfunc (l *Logger) SetShowCaller(show bool) *LoggerSetShowCaller turns the caller's file:line on or off.
Logger.Warnfunc (l *Logger) Warn(format string, args ...any)Warn logs a formatted message at WARN level.
Logger.WithFieldfunc (l *Logger) WithField(key, value string) *LoggerWithField returns a copy of the logger whose prefix gains "key=value".
Logger.WithFieldsfunc (l *Logger) WithFields(fields map[string]string) *LoggerWithFields returns a copy of the logger whose prefix gains "key=value" for each field, sorted by key.
LoggerConfigtype LoggerConfig structLoggerConfig holds the settings ConfigureLogger applies.
NewLoggerfunc NewLogger() *LoggerNewLogger returns a Logger that writes INFO and above to os.Stdout with colored level names and no caller information.
Printfunc Print(args ...any)Print logs its arguments, joined as fmt.Sprint does, at INFO level.
Printffunc Printf(format string, args ...any)Printf logs a formatted message at INFO level.
SetLogColoredfunc SetLogColored(colored bool)SetLogColored turns colored level names on or off for the package-level functions.
SetLogLevelfunc SetLogLevel(level LogLevel)SetLogLevel sets the lowest level the package-level functions write.
SetLogOutputfunc SetLogOutput(w io.Writer)SetLogOutput sets the writer the package-level functions write to.
SetLogShowCallerfunc SetLogShowCaller(show bool)SetLogShowCaller turns caller file:line on or off for the package-level functions.
SetupDevelopmentLoggingfunc SetupDevelopmentLogging()SetupDevelopmentLogging makes the package-level functions write DEBUG and above to stdout, colored, with caller information.
SetupProductionLoggingfunc SetupProductionLogging()SetupProductionLogging makes the package-level functions write INFO and above to stdout, uncolored, without caller information.
SetupTestLoggingfunc SetupTestLogging()SetupTestLogging discards all package-level log output.
Warnfunc Warn(format string, args ...any)Warn logs a formatted message at WARN level through the default logger.
Profiler 23 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
MemoryStatstype MemoryStats structMemoryStats is a snapshot of runtime memory figures, in megabytes, plus the GC count and goroutine count.
NewProfilerfunc NewProfiler() *ProfilerNewProfiler returns an enabled Profiler with no data.
PathStatstype PathStats structPathStats summarizes the recorded requests for one path.
ProfileStatstype ProfileStats structProfileStats is the snapshot GetStats returns.
Profilertype Profiler structProfiler records request timings through its Middleware and named timings through StartTimer and TimeOperation.
Profiler.Disablefunc (p *Profiler) Disable() *ProfilerDisable turns recording off and returns p.
Profiler.Enablefunc (p *Profiler) Enable() *ProfilerEnable turns recording on and returns p.
Profiler.GetRequestsByPathfunc (p *Profiler) GetRequestsByPath() map[string]PathStatsGetRequestsByPath returns timing statistics for each recorded path.
Profiler.GetStatsfunc (p *Profiler) GetStats() ProfileStatsGetStats returns a snapshot of the recorded requests, the named timers with at least one completed run, and current memory figures.
Profiler.GetTopSlowRequestsfunc (p *Profiler) GetTopSlowRequests(n int) []RequestProfileGetTopSlowRequests returns up to n recorded requests, slowest first.
Profiler.IsEnabledfunc (p *Profiler) IsEnabled() boolIsEnabled reports whether the profiler is recording.
Profiler.Middlewarefunc (p *Profiler) Middleware() func(http.Handler) http.HandlerMiddleware returns middleware that records each request's method, path, status, duration, and bytes allocated, for app.Use.
Profiler.PrintStatsfunc (p *Profiler) PrintStats()PrintStats writes a readable summary of GetStats to stdout.
Profiler.Resetfunc (p *Profiler) Reset()Reset discards every recorded request and timer and restarts the uptime clock.
Profiler.StartTimerfunc (p *Profiler) StartTimer(name string) *TimerStartTimer starts a new run of the named timer and returns it.
Profiler.StatsHandlerfunc (p *Profiler) StatsHandler() http.HandlerStatsHandler returns an http.Handler that serves GetStats as JSON.
Profiler.StopTimerfunc (p *Profiler) StopTimer(name string) time.DurationStopTimer stops the most recently started run of the named timer that is still running and returns its duration, or 0 when none is running.
Profiler.TimeOperationfunc (p *Profiler) TimeOperation(name string, fn func()) (duration time.Duration)TimeOperation calls fn, records the run under name, and returns its duration.
Profiler.TimeOperationWithResultfunc (p *Profiler) TimeOperationWithResult(name string, fn func() any) (result any, duration time.Duration)TimeOperationWithResult is TimeOperation for a function that returns a value; it returns that value and the duration.
RequestProfiletype RequestProfile structRequestProfile is one request the Middleware recorded.
Timertype Timer structTimer is one run of a named timer, returned by StartTimer.
Timer.Stopfunc (t *Timer) Stop() time.DurationStop ends this run, records it in the timer's statistics, and returns its duration.
TimerStatstype TimerStats structTimerStats summarizes the completed runs of one named timer.
Live reload (Air) 25 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
AirBuildConfigtype AirBuildConfig structAirBuildConfig is the [build] section of an Air configuration.
AirConfigtype AirConfig structAirConfig is an Air live-reload configuration.
AirConfig.SaveAirConfigfunc (ac *AirConfig) SaveAirConfig(filename string) errorSaveAirConfig writes ToTOML to filename, or to .air.toml when filename is empty.
AirConfig.ToTOMLfunc (ac *AirConfig) ToTOML() stringToTOML renders the configuration as the contents of an .air.toml file, with the [build], [color], log, and [misc] sections.
AirHelpertype AirHelper structAirHelper sets up Air for the project in one directory.
AirHelper.AddBuildArgsfunc (ah *AirHelper) AddBuildArgs(args ...string) *AirHelperAddBuildArgs adds arguments Air passes to the binary when it runs it.
AirHelper.AddExcludeDirfunc (ah *AirHelper) AddExcludeDir(directories ...string) *AirHelperAddExcludeDir adds directories Air does not watch.
AirHelper.AddWatchExtfunc (ah *AirHelper) AddWatchExt(extensions ...string) *AirHelperAddWatchExt adds file extensions, without dots, that trigger a rebuild.
AirHelper.CreateDevScriptfunc (ah *AirHelper) CreateDevScript() errorCreateDevScript writes an executable dev.sh to the project root.
AirHelper.GetInstallInstructionsfunc (ah *AirHelper) GetInstallInstructions() stringGetInstallInstructions returns text describing the ways to install Air.
AirHelper.InitAirfunc (ah *AirHelper) InitAir() errorInitAir creates tmp/ and writes .air.toml in the project root.
AirHelper.IsAirInstalledfunc (ah *AirHelper) IsAirInstalled() boolIsAirInstalled reports whether an air binary exists in /usr/local/bin, /usr/bin, $GOPATH/bin, or $HOME/go/bin.
AirHelper.SetBinPathfunc (ah *AirHelper) SetBinPath(path string) *AirHelperSetBinPath sets the path of the binary Air runs after a build.
AirHelper.SetBuildCmdfunc (ah *AirHelper) SetBuildCmd(cmd string) *AirHelperSetBuildCmd sets the command Air runs to build the binary.
AirHelper.UpdateConfigfunc (ah *AirHelper) UpdateConfig(modifier func(*AirConfig)) *AirHelperUpdateConfig calls modifier with the configuration so it can change any field.
AirInstallHelpfunc AirInstallHelp() stringAirInstallHelp returns text describing the ways to install Air.
AirLogConfigtype AirLogConfig structAirLogConfig is the log section of an Air configuration.
AirMiscConfigtype AirMiscConfig structAirMiscConfig is the [misc] section of an Air configuration.
AirWatchConfigtype AirWatchConfig structAirWatchConfig holds the watch lists kept in AirConfig.Watch.
CreateHyperChiAirConfigfunc CreateHyperChiAirConfig(filename string) errorCreateHyperChiAirConfig writes HyperChiAirConfig to filename, or to .air.toml when filename is empty.
DefaultAirConfigfunc DefaultAirConfig() *AirConfigDefaultAirConfig returns an Air configuration that builds ./tmp/main from the current directory and watches Go, template, HTML, JS, and CSS files.
HyperChiAirConfigfunc HyperChiAirConfig() *AirConfigHyperChiAirConfig returns DefaultAirConfig extended for a HyperChi project: it also watches .md, .env, .gotmpl, and .gohtml files and skips the static, uploads, logs, storage, and cache directories.
InitAirConfigfunc InitAirConfig() errorInitAirConfig runs AirHelper.InitAir in the current directory.
IsAirAvailablefunc IsAirAvailable() boolIsAirAvailable reports whether Air is installed (see AirHelper.IsAirInstalled).
NewAirHelperfunc NewAirHelper(projectRoot string) *AirHelperNewAirHelper returns an AirHelper for projectRoot, or for the current directory when projectRoot is empty.
Deployment 19 entries
import "github.com/regiellis/hyperchi/hyperchi/helpers"
CreateDeploymentFilesfunc CreateDeploymentFiles(projectRoot, appName string) errorCreateDeploymentFiles writes every deployment file for appName into projectRoot: Dockerfile, compose file, production .env, build and deploy scripts, nginx and systemd configs, and a health check.
DeploymentConfigtype DeploymentConfig structDeploymentConfig describes how an app is deployed.
DeploymentHelpertype DeploymentHelper structDeploymentHelper writes deployment files (Dockerfile, compose file, scripts, server configs) for one project directory and app name.
DeploymentHelper.CreateBuildScriptfunc (dh *DeploymentHelper) CreateBuildScript() errorCreateBuildScript writes an executable build.sh that cross-compiles release archives into dist/ and builds a Docker image.
DeploymentHelper.CreateDeployScriptfunc (dh *DeploymentHelper) CreateDeployScript() errorCreateDeployScript writes an executable deploy.sh.
DeploymentHelper.CreateDeploymentFilesfunc (dh *DeploymentHelper) CreateDeploymentFiles() errorCreateDeploymentFiles writes the Dockerfile, docker-compose.yml, systemd unit, deploy.sh, and nginx.conf.
DeploymentHelper.CreateDockerComposefunc (dh *DeploymentHelper) CreateDockerCompose() errorCreateDockerCompose writes docker-compose.yml with the app service on port 8080, a data volume, and an nginx service in front of it.
DeploymentHelper.CreateDockerfilefunc (dh *DeploymentHelper) CreateDockerfile() errorCreateDockerfile writes a multi-stage Dockerfile, and a .dockerignore when the project has none.
DeploymentHelper.CreateHealthCheckfunc (dh *DeploymentHelper) CreateHealthCheck() errorCreateHealthCheck writes health.go, standard-library health, readiness, and liveness handlers for package main.
DeploymentHelper.CreateNginxConfigfunc (dh *DeploymentHelper) CreateNginxConfig() errorCreateNginxConfig writes nginx.conf, a reverse proxy in front of the app on port 8080.
DeploymentHelper.CreateProductionEnvfunc (dh *DeploymentHelper) CreateProductionEnv() errorCreateProductionEnv writes a .env.production template with mode 0600.
DeploymentHelper.CreateSystemdServicefunc (dh *DeploymentHelper) CreateSystemdService() errorCreateSystemdService writes <appName>.service, a systemd unit that runs the app.
DeploymentHelper.DefaultDeploymentConfigfunc (dh *DeploymentHelper) DefaultDeploymentConfig() *DeploymentConfigDefaultDeploymentConfig returns a production config for linux/amd64 on port 8080 with a /health check.
DeploymentHelper.GetBuildInfofunc (dh *DeploymentHelper) GetBuildInfo() map[string]stringGetBuildInfo returns the Go version, OS, architecture, current UTC time, app name, and a Unix-time deployment ID as strings.
DeploymentHelper.GetProductionConfigfunc (dh *DeploymentHelper) GetProductionConfig() *ProductionConfigGetProductionConfig returns recommended production settings as a ProductionConfig.
DeploymentHelper.SwitchToProductionfunc (dh *DeploymentHelper) SwitchToProduction() errorSwitchToProduction loads .env.production from the project root and returns an error when APP_NAME, ENVIRONMENT, JWT_SECRET, or SESSION_SECRET is missing.
NewDeploymentHelperfunc NewDeploymentHelper(projectRoot, appName string) *DeploymentHelperNewDeploymentHelper returns a DeploymentHelper for projectRoot (default ".") and appName (default "hyperchi-app").
ProductionConfigtype ProductionConfig structProductionConfig is a set of recommended production settings returned by GetProductionConfig.
SwitchEnvironmentfunc SwitchEnvironment(env string) errorSwitchEnvironment copies .env.<env> over .env in the working directory.
Follow the working examples
Start with Passing data for app.Get, query defaults, typed filtering, and JSON responses. Compare templ and Jet for the external rendering boundary. The helpers package contains the full collection, string, file, logging, and HTTP-client APIs.