Skip to content

Instantly share code, notes, and snippets.

@alexandrevicenzi
Created July 28, 2017 12:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexandrevicenzi/1b4969c03339e4481084861f94dfffdb to your computer and use it in GitHub Desktop.
Save alexandrevicenzi/1b4969c03339e4481084861f94dfffdb to your computer and use it in GitHub Desktop.
Tus Server with Authentication
package main
import (
"net/http"
"github.com/tus/tusd"
"github.com/tus/tusd/filestore"
)
func UserIsAuthenticated(r *http.Request) {
// TODO: validate cookie or header.
return true
}
func main() {
store := filestore.FileStore{
Path: "./uploads",
}
composer := tusd.NewStoreComposer()
composer.UseCore(store)
composer.UseGetReader(store)
composer.UseTerminater(store)
composer.UseFinisher(store)
composer.UseLocker(store)
tusHandler, err := tusd.NewHandler(tusd.Config{
BasePath: "./uploads/",
StoreComposer: composer,
MaxSize: 0,
NotifyCompleteUploads: false,
NotifyTerminatedUploads: false,
RespectForwardedHeaders: true,
})
if err != nil {
return nil, err
}
mux := http.NewServeMux()
mux.Handle("/uploads/", func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// OPTIONS is used to gather information about the Server's current configuration.
// It can't ask for authentication, otherwise it won't work with XHR requests.
if r.Method == "OPTIONS" {
next.ServeHTTP(w, r)
} else {
// check if user is authenticated.
if ok := UserIsAuthenticated(r); ok {
next.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}
})
}(http.StripPrefix("/uploads/", tusHandler)))
// 127.0.0.1:8000/uploads
err = http.ListenAndServe("127.0.0.1:8000", mux)
if err != nil {
panic("unable to listen.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment