1package tusd
2
3import (
4	"net/http"
5
6	"github.com/bmizerany/pat"
7)
8
9// Handler is a ready to use handler with routing (using pat)
10type Handler struct {
11	*UnroutedHandler
12	http.Handler
13}
14
15// NewHandler creates a routed tus protocol handler. This is the simplest
16// way to use tusd but may not be as configurable as you require. If you are
17// integrating this into an existing app you may like to use tusd.NewUnroutedHandler
18// instead. Using tusd.NewUnroutedHandler allows the tus handlers to be combined into
19// your existing router (aka mux) directly. It also allows the GET and DELETE
20// endpoints to be customized. These are not part of the protocol so can be
21// changed depending on your needs.
22func NewHandler(config Config) (*Handler, error) {
23	if err := config.validate(); err != nil {
24		return nil, err
25	}
26
27	handler, err := NewUnroutedHandler(config)
28	if err != nil {
29		return nil, err
30	}
31
32	routedHandler := &Handler{
33		UnroutedHandler: handler,
34	}
35
36	mux := pat.New()
37
38	routedHandler.Handler = handler.Middleware(mux)
39
40	mux.Post("", http.HandlerFunc(handler.PostFile))
41	mux.Head(":id", http.HandlerFunc(handler.HeadFile))
42	mux.Add("PATCH", ":id", http.HandlerFunc(handler.PatchFile))
43
44	// Only attach the DELETE handler if the Terminate() method is provided
45	if config.StoreComposer.UsesTerminater {
46		mux.Del(":id", http.HandlerFunc(handler.DelFile))
47	}
48
49	// GET handler requires the GetReader() method
50	if config.StoreComposer.UsesGetReader {
51		mux.Get(":id", http.HandlerFunc(handler.GetFile))
52	}
53
54	return routedHandler, nil
55}
56