favicon

package module
v0.0.0-...-5201576 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2024 License: MIT Imports: 15 Imported by: 0

README

go-favicon

PkgGoDev

fork of deanishe/go-favicon

Discover favicons for a website. Parses HTML and manifest files.

Import path is github.com/yulog/go-favicon.

Documentation

Overview

Package favicon finds icons for websites. It can find icons in HTML (favicons in <link> elements, Open Graph or Twitter images) and in JSON manifests, or check common paths on the server (e.g. /favicon.ico).

Package-level functions call the corresponding methods on a default Finder. For customised Finder behaviour, pass appropriate options to New().

Index

Examples

Constants

This section is empty.

Variables

View Source
var IconNames = []string{
	"favicon.ico",
	"apple-touch-icon.png",
}

IconNames are common names of icon files hosted in server roots.

View Source
var UserAgent = "go-favicon/0.1"

UserAgent is sent in the User-Agent HTTP header.

Functions

This section is empty.

Types

type ByWidth

type ByWidth []*Icon

ByWidth sorts icons by width (largest first), and then by image type (PNG > JPEG > SVG > ICO).

func (ByWidth) Len

func (v ByWidth) Len() int

Implement sort.Interface

func (ByWidth) Less

func (v ByWidth) Less(i, j int) bool

func (ByWidth) Swap

func (v ByWidth) Swap(i, j int)

type Filter

type Filter func(*Icon) *Icon

Filter accepts/rejects/modifies Icons. If if returns nil, the Icon is ignored. Set a Finder's filters by passing WithFilter(...) to New().

type Finder

type Finder struct {
	// contains filtered or unexported fields
}

Finder discovers favicons for a URL. By default, a Finder looks in the following places:

The HTML page at the given URL for...

  • icons in <link> tags
  • Open Graph images
  • Twitter images

The manifest file...

  • defined in the HTML page -- or --
  • /manifest.json

Standard favicon paths

  • /favicon.ico
  • /apple-touch-icon.png

Pass the IgnoreManifest and/or IgnoreWellKnown Options to New() to reduce the number of requests made to webservers.

func New

func New(option ...Option) *Finder

New creates a new Finder configured with the given options.

Example

Find favicons using default options.

// Find icons defined in HTML, the manifest file and at default locations
icons, err := favicon.Find("https://www.deanishe.net")
if err != nil {
	panic(err)
}
// icons are sorted widest first
for _, i := range icons {
	fmt.Printf("%dx%d\t%s\n", i.Width, i.Height, i.FileExt)
}
Output:

256x256	png
192x192	png
180x180	png
32x32	png
16x16	png
0x0	png
0x0	ico
Example (WithOptions)

Find favicons using custom options. Passing IgnoreManifest and IgnoreWellKnown causes the Finder to only retrieve the initial URL (HTML page).

f := favicon.New(
	// Don't look for or parse a manifest.json file
	favicon.IgnoreManifest,
	// Don't request files like /favicon.ico to see if they exist
	favicon.IgnoreWellKnown,
)
// Find icons defined in HTML, the manifest file and at default locations
icons, err := f.Find("https://www.deanishe.net")
if err != nil {
	panic(err)
}
// icons are sorted widest first
for _, i := range icons {
	fmt.Printf("%dx%d\t%s\n", i.Width, i.Height, i.MimeType)
}
Output:

180x180	image/png
32x32	image/png
16x16	image/png

func (*Finder) Find

func (f *Finder) Find(url string) ([]*Icon, error)

Find finds favicons for URL.

func (*Finder) FindGoQueryDocument

func (f *Finder) FindGoQueryDocument(doc *gq.Document, baseURL ...string) ([]*Icon, error)

FindGoQueryDocument finds a favicon in GoQueryDocument.

func (*Finder) FindNode

func (f *Finder) FindNode(n *html.Node, baseURL ...string) ([]*Icon, error)

FindNode finds a favicon in HTML Node.

func (*Finder) FindReader

func (f *Finder) FindReader(r io.Reader, baseURL ...string) ([]*Icon, error)

FindReader finds a favicon in HTML.

type Icon

type Icon struct {
	URL      string `json:"url"`       // Never empty
	MimeType string `json:"mimetype"`  // MIME type of icon; never empty
	FileExt  string `json:"extension"` // File extension; may be empty
	// Dimensions are extracted from markup/manifest, falling back to
	// searching for numbers in the URL.
	Width  int `json:"width"`
	Height int `json:"height"`
	// Hash of URL and dimensions to uniquely identify icon.
	Hash string `json:"hash"`
}

Icon is a favicon parsed from an HTML file or JSON manifest.

TODO: Use *Icon everywhere to be consistent with higher-level APIs that return nil for "not found".

func Find

func Find(url string) ([]*Icon, error)

Find finds favicons for URL.

func FindGoQueryDocument

func FindGoQueryDocument(doc *gq.Document, baseURL ...string) ([]*Icon, error)

FindGoQueryDocument finds a favicon in GoQueryDocument. It accepts an optional base URL, which is used to resolve relative links.

func FindNode

func FindNode(n *html.Node, baseURL ...string) ([]*Icon, error)

FindNode finds a favicon in HTML Node. It accepts an optional base URL, which is used to resolve relative links.

func FindReader

func FindReader(r io.Reader, baseURL ...string) ([]*Icon, error)

FindReader finds a favicon in HTML. It accepts an optional base URL, which is used to resolve relative links.

func (Icon) Copy

func (i Icon) Copy() *Icon

Copy returns a new Icon with the same values as this one.

func (Icon) IsSquare

func (i Icon) IsSquare() bool

IsSquare returns true if image has equally-long sides.

func (Icon) String

func (i Icon) String() string

String implements Stringer.

type Logger

type Logger interface {
	Printf(string, ...interface{})
}

Logger describes the logger used by Finder.

type Manifest

type Manifest struct {
	Icons []ManifestIcon `json:"icons"`
}

Manifest is the relevant parts of a manifest.json file.

type ManifestIcon

type ManifestIcon struct {
	URL      string `json:"src"`
	Type     string `json:"type"`
	RawSizes string `json:"sizes"`
}

ManifestIcon is an icon from a manifest.json file.

type Option

type Option func(*Finder)

Option configures Finder. Pass Options to New().

var (
	// IgnoreWellKnown ignores common locations like /favicon.ico.
	IgnoreWellKnown Option = func(f *Finder) { f.ignoreWellKnown = true }

	// IgnoreManifest ignores manifest.json files.
	IgnoreManifest Option = func(f *Finder) { f.ignoreManifest = true }

	// IgnoreNoSize ignores icons with no specified size.
	IgnoreNoSize Option = WithFilter(func(icon *Icon) *Icon {
		if icon.Width == 0 || icon.Height == 0 {
			return nil
		}
		return icon
	})

	// OnlyPNG ignores non-PNG files.
	OnlyPNG Option = OnlyMimeType("image/png")

	// OnlyICO ignores non-ICO files.
	OnlyICO Option = WithFilter(func(icon *Icon) *Icon {
		if icon.MimeType == "image/x-icon" || icon.MimeType == "image/vnd.microsoft.icon" {
			return icon
		}
		return nil
	})

	// OnlySquare ignores non-square files. NOTE: Icons without a known size are also returned.
	OnlySquare Option = WithFilter(func(icon *Icon) *Icon {
		if !icon.IsSquare() {
			return nil
		}
		return icon
	})

	// SortByWidth sorts icons by width (largest first), and then by image type
	// (PNG > JPEG > SVG > ICO).
	SortByWidth Option = WithSorter(func(icons []*Icon) sort.Interface {
		return ByWidth(icons)
	})

	// NopSort represents a no operation sorting.
	NopSort Option = WithSorter(nil)
)

func MaxHeight

func MaxHeight(height int) Option

MaxHeight ignores icons larger than the given height.

func MaxWidth

func MaxWidth(width int) Option

MaxWidth ignores icons larger than the given width.

func MinHeight

func MinHeight(height int) Option

MinHeight ignores icons smaller than the given height.

func MinWidth

func MinWidth(width int) Option

MinWidth ignores icons smaller than the given width.

func OnlyMimeType

func OnlyMimeType(mimeType ...string) Option

OnlyMimeType only finds Icons that have one of the specified MIME types, e.g. "image/png" or "image/jpeg".

func WithClient

func WithClient(client *http.Client) Option

WithClient configures Finder to use the given HTTP client.

func WithFilter

func WithFilter(filter ...Filter) Option

WithFilter only returns Icons accepted by Filter functions.

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets the logger used by Finder.

func WithSorter

func WithSorter(sorter Sorter) Option

WithSorter configures Finder to use the given Sorter.

type Sorter

type Sorter func([]*Icon) sort.Interface

Sorter Icons. Set a Finder's sorter by passing WithSorter(...) to New().

Directories

Path Synopsis
cmd
favicon
Command favicon finds favicons for a URL and prints their format, size and URL.
Command favicon finds favicons for a URL and prints their format, size and URL.

Jump to

Keyboard shortcuts

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