webtools

package module
v0.6.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 11, 2026 License: BSD-3-Clause Imports: 8 Imported by: 0

README

webtools

Go Reference License Build

Package webtools is a collection of helper functions, types, and abstractions for building standalone websites. In particular, sites that make use of oauth based sessions for user identity and authentication.

Getting Started

The webtools packages can be added to a Go project with go get.

go get cattlecloud.net/go/webtools@latest
import "cattlecloud.net/go/webtools"
Package Contents
package webtools

For setting common headers with correct values on http.ResponseWriter objects, including:

  • Content-Type
webtools.SetContentType(w, webtools.ContentTypeRSS)
  • X-Robots-Tag
webtools.SetRobotsTag(w, webtools.RobotsYesIndex)
  • Cache-Control
webtools.SetCacheControl(w, 24 * time.Hour)
  • Authorization
webtools.SetBasicAuth(w, "admin", "passw0rd")
sanitize a url

Use Sanitize to remove known trackers from URL parameters.

u := webtools.Sanitize("https://example.org?utm_source=abc123&page=1")
// utm_source=abc123 is removed from the url

Also helps with crafting net/url.URL values with correctly encoded URL paramter values.

creating a url
u := webtools.CreateURL("example.org", "/some/path", map[string]string {
  "token": "abc123",
  "page":  "2",
})

There is also the Origins convenience function for parsing the user-agent of an http.Request and creating a struct of interesting values regarding the request.

ua := webtools.Origins(r)

fmt.Println(ua.String()) # e.g. curl/unknown
fmt.Println(ua.Anchor()) # e.g. example.org/path/to/page
fmt.Println(ua.From())   # e.g. 10.0.0.1
package webtools/htmx

Provides utilities for building HTMX-compatible responses. The package includes an Interface for rendering HTMX responses, along with support for plain text, raw HTML, and templated content.

Response interfaces
type Interface interface {
    Write(io.Writer) error
}
Rendering responses
htmx.Write(
		w, // any io.Writer; typically http.ResponseWriter
    htmx.Text{Content: "Hello, World!"},
)
Using templates
//go:embed templates/*
var templates embed.FS

tmplFS := htmx.FS(templates, "templates")

http.HandleFunc("GET /partial", func(w http.ResponseWriter, r *http.Request) {
    htmx.Write(w, &htmx.Template{
        FS:       tmplFS,
        Filename: "button.html",
        Fields:   data,
    })
})
Inline templates with Component

Use Component for rendering raw HTML templates defined inline:

html := `<button hx-post="/click">{{ .Count }} clicks</button>`

htmx.Write(w, &htmx.Component{
    HTML:   html,
    Fields: struct{ Count int }{Count: 42},
})
Client-side redirects

Use SetRedirect instead of http.Redirect when handling HTMX requests to perform a client-side redirect:

func handler(w http.ResponseWriter, r *http.Request) {
    htmx.SetRedirect(w, "/new-page")
}
Preventing swap

Use SetNoSwap to keep existing content in place after a HTMX transition. Useful for setting error messages on forms:

func errorHandler(w http.ResponseWriter, err error) {
    htmx.SetNoSwap(w)
    htmx.Write(w, htmx.Text{Content: err.Error()})
}
package webtools/middles

Provides a generic sessions http.Handler which can be used to set and validate user sessions. The primary interface is (optionally) implemented by using the oauth and identity packages in this module.

type Sessions[I identity.UserIdentity] interface {
	Create(I, time.Duration) *http.Cookie
	Match(I, *conceal.Text) error
}
package webtools/httpclient

Provides a sharable http.Client that sets sensible values for maintaining a pool of idle connections.

client := httpclient.Get()
package webtools/middles/identity

Provides a set of generic structs used for marshaling identity. The interfaces are (optionally) implemented by using the oauth and identity packages in this module.

type UserIdentity any

type UserData[I UserIdentity] interface {
	Identity() I
	Token() *conceal.Text
}

type UserSession[I UserIdentity] interface {
	Identity() I
	Active() bool
}
package webtools/middles/oauth

Provides implementations for cookie creation, session management, and TTL enabled session token caching. Intended to be used as the implementation details of the middles and identity packages, and by using the nonces, applekeys, googlekeys, and microsoftkeys packages as OAuth provider token validators.

package webtools/middles/oauth/nonces

Provides an implementation to manage nonce values used during the OAuth token exchange. The primary interface enables you to Create a nonce, and then Consume the nonce exactly once.

type Mint interface {
	Create() *conceal.Text
	Consume(*conceal.Text) error
}
package webtools/middles/oauth/applekeys

Provides an interface and implementation for validation JWT token claims as issued by Apple.

type Validator interface {
	Validate(string) (*Claims, error)
}
package webtools/middles/oauth/googlekeys

Provides an interface and implementation for validation JWT token claims as issued by Google.

type Validator interface {
	Validate(string) (*Claims, error)
}
package webtools/middles/oauth/microsoftkeys

Provides an interface and implementation for validation JWT token claims as issued by Microsoft.

type Validator interface {
	Validate(string) (*Claims, error)
}
Notes on OAuth

The implementation details of what belongs in your http.Handler are currently not a part of this suite of packages.

Firstly, you'll need to enable CSRF protection, which the Go standard library has good support for as of Go 1.25; e.g.

csrf := http.NewCrossOriginProtection()
_ = csrf.AddTrustedOrigin("https://appleid.apple.com")

// ...

server := &http.Server{
	Addr:    address,
	Handler: csrf.Handler(router),
}

For getting users logged in via their oauth provider, you'll need to have handler(s) that go through the oauth handshake.

License

The cattlecloud.net/go/webtools module is opensource under the BSD-3-Clause license.

Documentation

Overview

Package webtools is a collection of helper types, functions, abstractions, and additional packages for building standalone websites. In particular, sites that make use of oauth based sessions for user identity and authentication.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateURL

func CreateURL(origin, path string, params map[string]string) *url.URL

CreateURL creates a *url.URL from the given origin, path, and request parameters that has been properly encoded and formatted.

resource url must be valid; an invalid url will panic.

func GetDomain added in v0.2.2

func GetDomain(s string) string

GetDomain extracts the domain name from a given url s.

If s is not a valid url, the empty string is returned.

func Sanitize added in v0.6.0

func Sanitize(s string) string

Sanitize purges known tracker URL parameters.

If s fails to parse as a url, the original string is returned.

func SetBasicAuth

func SetBasicAuth(r *http.Request, username, password string)

SetBasicAuth sets the Authorization header on r, using the given username and password.

NOTE: if either username or password is empty, no header is set.

func SetCacheControl

func SetCacheControl(w http.ResponseWriter, ttl time.Duration)

SetCacheControl sets a private Cache-Control headers on w with the given duration, rounded to seconds.

func SetContentType

func SetContentType(w http.ResponseWriter, filetype MIMEType)

SetContentType sets the Content-Type header on w to the givien MIME compatible content type string.

func SetRobotsTag

func SetRobotsTag(w http.ResponseWriter, instruction RobotIndex)

SetRobotsTag to a crawl control value (e.g. noindex)

Types

type MIMEType

type MIMEType string

MIMEType are correct identifier strings for various MIME types.

Consider using one of the pre-defined types.

const (
	ContentTypeText MIMEType = "text/plain; charset=utf8"
	ContentTypeHTML MIMEType = "text/html; charset=utf-8"
	ContentTypeXML  MIMEType = "text/xml; charset=utf8"
	ContentTypeRSS  MIMEType = "application/rss+xml; charset=utf8"
	ContentTypeJSON MIMEType = "application/json" // implicit utf8 charset
)

type Origin

type Origin struct {
	// about the request
	Method    string
	Host      string
	UserAgent useragent.UserAgent

	// about the requesting entity
	Remote    string
	Forward   string
	Reference string
}

Origin contins request origination context from parsing request headers.

func Origins

func Origins(r *http.Request) *Origin

Origins parses the request headers to get information about the origins of the request, including ...

- Method - Host - Forwarder - Referer - User-Agent

func (*Origin) Anchor added in v0.2.1

func (o *Origin) Anchor() string

Anchor returns a parsed version of the Referer headers, including the domain and path without the protocol or query.

func (*Origin) From

func (o *Origin) From() string

From returns the value of the X-Forwarded-For if set, otherwise defaulting to the Remote address.

func (*Origin) String

func (o *Origin) String() string

String returns the parsed user agent, including only the name and type of device being used (or bot).

type RobotIndex

type RobotIndex string

RobotIndex are correct sentinel values for indicating whether a page should be indexed, as set in the X-Robots-Tag HTTP response header.

Consider using one of the pre-defined types.

const (
	RobotsNoIndex  RobotIndex = "noindex"
	RobotsYesIndex RobotIndex = "all"
)

Directories

Path Synopsis
Package expcache provides an in-memory expiry cache.
Package expcache provides an in-memory expiry cache.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL