1package webfinger
2
3import (
4	"net/http"
5
6	"github.com/captncraig/cors"
7)
8
9// Service is the webfinger service containing the required
10// HTTP handlers and defaults for webfinger implementations.
11type Service struct {
12
13	// PreHandlers are invoked at the start of each HTTP method, used to
14	// setup things like CORS, caching, etc. You can delete or replace
15	// a handler by setting service.PreHandlers[name] = nil
16	PreHandlers map[string]http.Handler
17
18	// NotFoundHandler is the handler to invoke when a URL is not matched. It does NOT
19	// handle the case of a non-existing users unless your Resolver.DummyUser returns
20	// an error that matches Resolver.IsNotFoundError(err) == true.
21	NotFoundHandler http.Handler
22
23	// MethodNotSupportedHandler is the handler invoked when an unsupported
24	// method is called on the webfinger HTTP service.
25	MethodNotSupportedHandler http.Handler
26
27	// MalformedRequestHandler is the handler invoked if the request routes
28	// but is malformed in some way. The default behavior is to return 400 BadRequest,
29	// per the webfinger specification
30	MalformedRequestHandler http.Handler
31
32	// NoTLSHandler is the handler invoked if the request is not
33	// a TLS request. The default behavior is to redirect to the TLS
34	// version of the URL, per the webfinger specification. Setting
35	// this to nil will allow nonTLS connections, but that is not advised.
36	NoTLSHandler http.Handler
37
38	// ErrorHandler is the handler invoked when an error is called. The request
39	// context contains the error in the webfinger.ErrorKey and can be fetched
40	// via webfinger.ErrorFromContext(ctx)
41	ErrorHandler http.Handler
42
43	// Resolver is the interface for resolving user details
44	Resolver Resolver
45}
46
47// Default creates a new service with the default registered handlers
48func Default(ur Resolver) *Service {
49	var c = cors.Default()
50
51	s := &Service{}
52	s.Resolver = ur
53	s.ErrorHandler = http.HandlerFunc(s.defaultErrorHandler)
54	s.NotFoundHandler = http.HandlerFunc(s.defaultNotFoundHandler)
55	s.MethodNotSupportedHandler = http.HandlerFunc(s.defaultMethodNotSupportedHandler)
56	s.MalformedRequestHandler = http.HandlerFunc(s.defaultMalformedRequestHandler)
57	s.NoTLSHandler = http.HandlerFunc(s.defaultNoTLSHandler)
58
59	s.PreHandlers = make(map[string]http.Handler)
60	s.PreHandlers[NoCacheMiddleware] = http.HandlerFunc(noCache)
61	s.PreHandlers[CorsMiddleware] = http.HandlerFunc(c.HandleRequest)
62	s.PreHandlers[ContentTypeMiddleware] = http.HandlerFunc(jrdSetup)
63
64	return s
65}
66