besticon

package module
v3.13.1 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2023 License: MIT Imports: 30 Imported by: 0

README

favicon-service (besticon)

This is a favicon service:

  • Supports favicon.ico and apple-touch-icon.png
  • Simple URL API
  • Fallback icon generation
  • Docker image & single binary download for easy hosting

Try out the demo at https://besticon-demo.herokuapp.com or find out how to deploy your own version right now.

Build Status Go Report Card Donate at PayPal

What's this?

Websites used to have a favicon.ico, or not. With the introduction of the apple-touch-icon.png finding “the icon” for a website became more complicated. This service finds and — if necessary — generates icons for web sites.

API

GET /icon

This endpoint always returns an icon image for the given site — it redirects to an official icon if possible or creates and returns a fallback image if needed.

Parameter Example Description Default
url http://yelp.com required
size 32..50..100 Desired size range (min..perfect..max) If no image of size perfect..max nor perfect..min can be found a fallback icon will be generated. required
formats png,ico Comma-separated list of accepted image formats: png, ico, gif, jpg gif,ico,jpg,png,svg
fallback_icon_url HTTP image URL If provided, a redirect to this image will be returned in case no suitable icon could be found. This overrides the default fallback image behaviour.
fallback_icon_color ff0000 If provided, letter icons will be colored with the hex value provided, rather than be grey, when no color can be found for any icon.
Examples
Input URL Icon
https://besticon-demo.herokuapp.com/icon?url=yelp.com&size=32..50..120 Icon for yelp.com
https://besticon-demo.herokuapp.com/icon?url=yelp.com&size=64..64..120 Icon for yelp.com
https://besticon-demo.herokuapp.com/icon?url=yelp.com size missing
https://besticon-demo.herokuapp.com/icon?url=httpbin.org/status/404&size=32..64..120 Icon for non-existent page
https://besticon-demo.herokuapp.com/icon?url=httpbin.org/status/404&size=32..64..120&fallback_icon_color=ff0000 Icon for non-existent page
https://besticon-demo.herokuapp.com/icon?url=фминобрнауки.рф&size=32..64..120 Icon with cyrillic letter ф
GET /allicons.json

This endpoint returns all icons for a given site.

Parameter Example Description Default
url http://yelp.com required
formats png,ico Comma-separated list of accepted image formats: png, ico, gif, jpg png,ico,gif,jpg
Examples

Bugs & limitations

I tried hard to make this useful but please note there are some known limitations:

  • Poor i18n support for letter icons (#13)

Feel free to file other bugs - and offer your help - at https://github.com/mat/besticon/issues.

Hosting

Simple options to host this service are, for example:

Docker

A docker image is available at https://hub.docker.com/r/matthiasluedtke/iconserver/, generated from the Dockerfile in this repo. I try to keep it updated for every release.

Note that this docker image is not used to run https://besticon-demo.herokuapp.com and therefore not well tested.

Monitoring

Prometheus metrics are exposed under /metrics. A Grafana dashboard config based on these metrics can be found in grafana-dashboard.json.

Server Executable

Download binaries

Binaries for some operating systems can be downloaded from https://github.com/mat/besticon/releases/latest

Build your own

If you have Go installed on your system you can use go get to fetch the source code and build the server:

$ go get -u github.com/mat/besticon/...

If you want to build executables for a different target operating system you can add the GOOS and GOARCH environment variables:

$ GOOS=linux GOARCH=amd64 go get -u github.com/mat/besticon/...
Running

To start the server on default port 8080 just do

$ iconserver

To use a different port use

$ PORT=80 iconserver

To listen on a different address (say localhost) use

$ ADDRESS=127.0.0.1 iconserver

To enable CORS headers you need to set CORS_ENABLED=true. Optionally, you can set additional environment variables which will be passed as options to the rs/cors middleware.

$ CORS_ENABLED=true iconserver

Now when you open http://localhost:8080/icons?url=instagram.com you should see something like Screenshot of The Favicon Finder

Configuration

There is not a lot to configure, but these environment variables exist

Variable Description Default Value
ADDRESS HTTP server listen address 0.0.0.0
CACHE_SIZE_MB Size for the groupcache, set to 0 to disable 32
CORS_ENABLED Enables the rs/cors middleware false
CORS_ALLOWED_HEADERS Comma-separated, passed to middleware
CORS_ALLOWED_METHODS Comma-separated, passed to middleware
CORS_ALLOWED_ORIGINS Comma-separated, passed to middleware
CORS_ALLOW_CREDENTIALS Boolean, passed to middleware
CORS_DEBUG Boolean, passed to middleware
DISABLE_BROWSE_PAGES Boolean, if true, the server will not serve any of the HTML pages false
HOST_ONLY_DOMAINS *
HTTP_CLIENT_TIMEOUT Timeout used for HTTP requests. Supports units like ms, s, m. 5s
HTTP_MAX_AGE_DURATION Cache duration for all dynamically generated HTTP responses. Supports units like ms, s, m. 720h (30 days)
HTTP_USER_AGENT User-Agent used for HTTP requests iPhone user agent string
METRICS_PATH Path at which the Prometheus metrics are served. Set to disable to disable Prometheus metrics /metrics
POPULAR_SITES Comma-separated list of domains used on /popular page some random web sites
PORT HTTP server port 8080
SERVER_MODE Set to download to proxy downloads through besticon or redirect to let browser to download instead. (example at #40) redirect

Contributors

License

MIT License (MIT)

Copyright (c) 2015-2020 Matthias Lüdtke, Hamburg - https://github.com/mat

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Donate

If you find this useful and want to donate... you would make my day :-)

Donate at PayPal

Documentation

Overview

Package besticon includes functions finding icons for a given web site.

Index

Constants

View Source
const VersionString = "v3.13.0"

Version string, same as VERSION, generated my Make

Variables

View Source
var BuildDate string // set via ldflags on Make

Functions

func MainColorForIcons

func MainColorForIcons(icons []Icon) *color.RGBA

func NewDefaultHTTPClient

func NewDefaultHTTPClient() *http.Client

func NewDefaultHTTPTransport

func NewDefaultHTTPTransport(userAgent string) http.RoundTripper

Types

type Besticon

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

Besticon is the main interface to the besticon package.

func New

func New(opts ...Option) *Besticon

New returns a new Besticon instance.

func (*Besticon) CacheEnabled

func (b *Besticon) CacheEnabled() bool

func (*Besticon) Get

func (b *Besticon) Get(urlstring string) (*http.Response, error)

func (*Besticon) GetBodyBytes

func (b *Besticon) GetBodyBytes(r *http.Response) ([]byte, error)

func (*Besticon) GetCacheStats

func (b *Besticon) GetCacheStats() groupcache.CacheStats

GetCacheStats returns cache statistics.

func (*Besticon) NewIconFinder

func (b *Besticon) NewIconFinder() *IconFinder

type Icon

type Icon struct {
	URL       string `json:"url"`
	Width     int    `json:"width"`
	Height    int    `json:"height"`
	Format    string `json:"format"`
	Bytes     int    `json:"bytes"`
	Error     error  `json:"error"`
	Sha1sum   string `json:"sha1sum"`
	ImageData []byte `json:",omitempty"`
}

Icon holds icon information.

func (*Icon) Image

func (ico *Icon) Image() (*image.Image, error)

type IconFinder

type IconFinder struct {
	FormatsAllowed  []string
	HostOnlyDomains []string
	// contains filtered or unexported fields
}

func (*IconFinder) FetchIcons

func (f *IconFinder) FetchIcons(url string) ([]Icon, error)

func (*IconFinder) IconInSizeRange

func (f *IconFinder) IconInSizeRange(r SizeRange) *Icon

func (*IconFinder) Icons

func (f *IconFinder) Icons() []Icon

func (*IconFinder) MainColorForIcons

func (f *IconFinder) MainColorForIcons() *color.RGBA

type Logger

type Logger interface {
	LogError(err error)
	// LogResponse is called when an HTTP request has been executed. The duration is the time it took to execute the
	// request. When error is nil, the response is the response object. Otherwise, the response is nil.
	LogResponse(req *http.Request, resp *http.Response, duration time.Duration, err error)
}

func NewDefaultLogger

func NewDefaultLogger(w io.Writer) Logger

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithCache

func WithCache(sizeInMB int64) Option

func WithDefaultFormats

func WithDefaultFormats(formats ...string) Option

WithDefaultFormats sets the default accepted formats.

func WithDiscardImageBytes

func WithDiscardImageBytes(discardImageBytes bool) Option

WithDiscardImageBytes sets whether to discard image bodies.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets the http client to use for requests.

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets the logger to use for logging.

type SizeRange

type SizeRange struct {
	Min     int
	Perfect int
	Max     int
}

SizeRange represents the desired icon dimensions

func ParseSizeRange

func ParseSizeRange(s string, maxIconSize int) (*SizeRange, error)

ParseSizeRange parses a string like 60..100..200 into a SizeRange

Directories

Path Synopsis
Package ico registers image.Decode and DecodeConfig support for the icon (container) format.
Package ico registers image.Decode and DecodeConfig support for the icon (container) format.

Jump to

Keyboard shortcuts

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