application

package
v0.0.0-...-b2a5d9a Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2016 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultContentType = "image/png"
View Source
const DefaultFormat = "png"
View Source
const DefaultPort = 3001
View Source
const DefaultQuality = 95
View Source
const DefaultShardDepth = 0
View Source
const DefaultShardWidth = 0
View Source
const SIG_PARAM_NAME = "sig"
View Source
const Version = "0.3"

Current version of the picfit

Variables

View Source
var DeleteHandler = func(res Response, req *http.Request, app *Application) {
	if app.SourceStorage == nil {
		res.Abort(500, "Your application doesn't have a source storage")
		return
	}

	params := mux.Vars(req)

	filename := params["path"]

	app.Logger.Infof("Deleting source storage file: %s", filename)
	_ = app.SourceStorage.Delete(filename)

	app.ImageCleanup(filename)

	content, err := json.Marshal(map[string]string{
		"filename": filename,
	})

	if err != nil {
		panic(err)
	}

	res.ContentType("application/json")
	res.ResponseWriter.Write(content)
}
View Source
var Extractors = map[string]Extractor{
	"op":   Operation,
	"url":  URL,
	"path": Path,
}
View Source
var UploadHandler = func(res Response, req *http.Request, app *Application) {
	if !app.EnableUpload {
		res.Forbidden()
		return
	}

	if app.SourceStorage == nil {
		res.Abort(500, "Your application doesn't have a source storage")
		return
	}

	var err error

	multipartForm := new(MultipartForm)
	errs := binding.Bind(req, multipartForm)
	if errs.Handle(res) {
		return
	}

	file, err := multipartForm.Upload(app.SourceStorage)

	if err != nil {
		panic(err)
	}

	content, err := json.Marshal(map[string]string{
		"filename": file.Filename(),
		"path":     file.Path(),
		"url":      file.URL(),
	})

	if err != nil {
		panic(err)
	}

	res.ContentType("application/json")
	res.ResponseWriter.Write(content)
}

Functions

func NotFoundHandler

func NotFoundHandler() http.Handler

func Run

func Run(path string) error

Types

type Application

type Application struct {
	EnableUpload  bool
	EnableDelete  bool
	Prefix        string
	SecretKey     string
	KVStore       gokvstores.KVStore
	SourceStorage gostorages.Storage
	DestStorage   gostorages.Storage
	Shard         Shard
	Raven         *raven.Client
	Logger        *logrus.Logger
	Engine        engines.Engine
	Jq            *jsonq.JsonQuery
}

func NewApplication

func NewApplication() *Application

func NewFromConfig

func NewFromConfig(content string) (*Application, error)

func NewFromConfigPath

func NewFromConfigPath(path string) (*Application, error)

func NewFromJsonQuery

func NewFromJsonQuery(jq *jsonq.JsonQuery) (*Application, error)

func (*Application) ImageCleanup

func (a *Application) ImageCleanup(filepath string)

func (*Application) ImageFileFromRequest

func (a *Application) ImageFileFromRequest(req *Request, async bool, load bool) (*image.ImageFile, error)

func (*Application) InitRouter

func (a *Application) InitRouter() *negroni.Negroni

func (*Application) Port

func (a *Application) Port() int

func (*Application) ServeHTTP

func (app *Application) ServeHTTP(h Handler) http.Handler

func (*Application) ShardFilename

func (a *Application) ShardFilename(filename string) string

func (*Application) Store

func (a *Application) Store(filepath string, i *image.ImageFile) error

func (*Application) WithPrefix

func (a *Application) WithPrefix(str string) string

type Extractor

type Extractor func(key string, req *Request) (interface{}, error)
var Operation Extractor = func(key string, req *Request) (interface{}, error) {
	operation, ok := engines.Operations[req.QueryString[key]]

	if !ok {
		return nil, fmt.Errorf("Invalid method %s or invalid parameters", operation)
	}

	return operation, nil
}
var Path Extractor = func(key string, req *Request) (interface{}, error) {
	return req.QueryString[key], nil
}
var URL Extractor = func(key string, req *Request) (interface{}, error) {
	value, ok := req.QueryString[key]

	if !ok {
		return nil, nil
	}

	url, err := url.Parse(value)

	if err != nil {
		return nil, fmt.Errorf("URL %s is not valid", value)
	}

	mimetype := mime.TypeByExtension(filepath.Ext(value))

	_, ok = image.Extensions[mimetype]

	if !ok {
		return nil, fmt.Errorf("Mimetype %s is not supported", mimetype)
	}

	return url, nil
}

type Handler

type Handler func(Response, *Request, *Application)
var GetHandler Handler = func(res Response, req *Request, app *Application) {
	file, err := app.ImageFileFromRequest(req, false, false)

	if err != nil {
		panic(err)
	}

	content, err := json.Marshal(map[string]string{
		"filename": file.Filename(),
		"path":     file.Path(),
		"url":      file.URL(),
	})

	if err != nil {
		panic(err)
	}

	res.ContentType("application/json")
	res.ResponseWriter.Write(content)
}
var ImageHandler Handler = func(res Response, req *Request, app *Application) {
	file, err := app.ImageFileFromRequest(req, true, true)

	if err != nil {
		panic(err)
	}

	res.SetHeaders(file.Headers, true)
	res.ResponseWriter.Write(file.Content())
}
var RedirectHandler Handler = func(res Response, req *Request, app *Application) {
	file, err := app.ImageFileFromRequest(req, false, false)

	if err != nil {
		panic(err)
	}

	res.PermanentRedirect(file.URL())
}

type Initializer

type Initializer func(jq *jsonq.JsonQuery, app *Application) error
var BasicInitializer Initializer = func(jq *jsonq.JsonQuery, app *Application) error {
	var format string
	var quality int

	f, _ := jq.String("options", "format")

	if f != "" {
		format = f
	}

	q, err := jq.Int("options", "quality")

	if err != nil {
		quality = q
	}

	if quality == 0 {
		quality = DefaultQuality
	}

	app.SecretKey, _ = jq.String("secret_key")
	app.Engine = &engines.GoImageEngine{
		DefaultFormat:  DefaultFormat,
		Format:         format,
		DefaultQuality: quality,
	}

	enableUpload, err := jq.Bool("options", "enable_upload")

	if err == nil {
		app.EnableUpload = enableUpload
	}

	enableDelete, err := jq.Bool("options", "enable_delete")

	if err == nil {
		app.EnableDelete = enableDelete
	}

	return nil
}
var KVStoreInitializer Initializer = func(jq *jsonq.JsonQuery, app *Application) error {
	_, err := jq.Object("kvstore")

	if err != nil {
		app.KVStore = &dummy.DummyKVStore{}

		return nil
	}

	key, err := jq.String("kvstore", "type")

	if err != nil {
		return err
	}

	parameter, ok := KVStores[key]

	if !ok {
		return fmt.Errorf("KVStore %s does not exist", key)
	}

	config, err := jq.Object("kvstore")

	if err != nil {
		return err
	}

	params := util.MapInterfaceToMapString(config)
	store, err := parameter(params)

	if err != nil {
		return err
	}

	app.Prefix = params["prefix"]
	app.KVStore = store

	return nil
}
var SentryInitializer Initializer = func(jq *jsonq.JsonQuery, app *Application) error {
	dsn, err := jq.String("sentry", "dsn")

	if err != nil {
		return nil
	}

	results, err := jq.Object("sentry", "tags")

	var tags map[string]string

	if err != nil {
		tags = map[string]string{}
	} else {
		tags = util.MapInterfaceToMapString(results)
	}

	client, err := raven.NewClient(dsn, tags)

	if err != nil {
		return err
	}

	app.Raven = client

	return nil
}
var ShardInitializer Initializer = func(jq *jsonq.JsonQuery, app *Application) error {
	width, err := jq.Int("shard", "width")

	if err != nil {
		width = DefaultShardWidth
	}

	depth, err := jq.Int("shard", "depth")

	if err != nil {
		depth = DefaultShardDepth
	}

	app.Shard = Shard{Width: width, Depth: depth}

	return nil
}
var StorageInitializer Initializer = func(jq *jsonq.JsonQuery, app *Application) error {
	_, err := jq.Object("storage")

	if err != nil {
		app.SourceStorage = &dummy.DummyStorage{}
		app.DestStorage = &dummy.DummyStorage{}

		return nil
	}

	sourceStorage, err := getStorageFromConfig("src", jq)

	if err != nil {
		return err
	}

	app.SourceStorage = sourceStorage

	destStorage, err := getStorageFromConfig("dst", jq)

	if err != nil {
		app.DestStorage = sourceStorage
	} else {
		app.DestStorage = destStorage
	}

	return nil
}

type KVStoreParameter

type KVStoreParameter func(params map[string]string) (gokvstores.KVStore, error)
var CacheKVStoreParameter KVStoreParameter = func(params map[string]string) (gokvstores.KVStore, error) {
	value, ok := params["max_entries"]

	var maxEntries int

	if !ok {
		maxEntries = -1
	} else {
		maxEntries, _ = strconv.Atoi(value)
	}

	return gokvstores.NewCacheKVStore(maxEntries), nil
}
var RedisKVStoreParameter KVStoreParameter = func(params map[string]string) (gokvstores.KVStore, error) {
	host := params["host"]

	password := params["password"]

	port, _ := strconv.Atoi(params["port"])

	db, _ := strconv.Atoi(params["db"])

	return gokvstores.NewRedisKVStore(host, port, password, db), nil
}

type MultipartForm

type MultipartForm struct {
	Data *multipart.FileHeader `json:"data"`
}

func (*MultipartForm) FieldMap

func (f *MultipartForm) FieldMap() binding.FieldMap

func (*MultipartForm) Upload

func (f *MultipartForm) Upload(storage gostorages.Storage) (*image.ImageFile, error)

type Request

type Request struct {
	Request     *http.Request
	Operation   *engines.Operation
	Connection  gokvstores.KVStoreConnection
	Key         string
	URL         *url.URL
	Filepath    string
	Params      map[string]string
	QueryString map[string]string
}

func NewRequest

func NewRequest(req *http.Request, con gokvstores.KVStoreConnection) (*Request, error)

func (*Request) IsAuthorized

func (r *Request) IsAuthorized(key string) bool

type Response

type Response struct {
	http.ResponseWriter
}

func NewResponse

func NewResponse(res http.ResponseWriter) Response

func (*Response) Abort

func (r *Response) Abort(status int, body string)

Abort is a helper method that sends an HTTP header and an optional body. It is useful for returning 4xx or 5xx errors. Once it has been called, any return value from the handler will not be written to the response.

func (*Response) BadRequest

func (r *Response) BadRequest()

BadRequest writes a 400 HTTP response

func (*Response) ContentType

func (r *Response) ContentType(val string) string

ContentType sets the Content-Type header for an HTTP response. For example, ctx.ContentType("json") sets the content-type to "application/json" If the supplied value contains a slash (/) it is set as the Content-Type verbatim. The return value is the content type as it was set, or an empty string if none was found.

func (*Response) Forbidden

func (r *Response) Forbidden()

Forbidden writes a 403 HTTP response

func (*Response) NotAllowed

func (r *Response) NotAllowed()

NotAllowed writes a 405 HTTP response

func (*Response) NotFound

func (r *Response) NotFound(message string)

NotFound writes a 404 HTTP response

func (*Response) NotModified

func (r *Response) NotModified()

Notmodified writes a 304 HTTP response

func (*Response) Ok

func (r *Response) Ok(message string)

NotFound writes a 200 HTTP response

func (*Response) PermanentRedirect

func (r *Response) PermanentRedirect(url string)

PermanentRedirect is a helper method for 301 redirect

func (*Response) Redirect

func (r *Response) Redirect(status int, url_ string)

Redirect is a helper method for 3xx redirects.

func (*Response) SetHeader

func (r *Response) SetHeader(hdr string, val string, unique bool)

SetHeader sets a response header. If `unique` is true, the current value of that header will be overwritten . If false, it will be appended.

func (*Response) SetHeaders

func (r *Response) SetHeaders(headers map[string]string, unique bool)

SetHeaders sets response headers. If `unique` is true, the current value of that header will be overwritten . If false, it will be appended.

func (*Response) Unauthorized

func (r *Response) Unauthorized()

Unauthorized writes a 401 HTTP response

func (*Response) WriteString

func (r *Response) WriteString(content string)

WriteString writes string data into the response object.

type Shard

type Shard struct {
	Depth int
	Width int
}

type StorageParameter

type StorageParameter func(params map[string]string) (gostorages.Storage, error)
var FileSystemStorageParameter StorageParameter = func(params map[string]string) (gostorages.Storage, error) {
	return gostorages.NewFileSystemStorage(params["location"], params["base_url"]), nil
}
var HTTPFileSystemStorageParameter StorageParameter = func(params map[string]string) (gostorages.Storage, error) {
	storage, err := FileSystemStorageParameter(params)

	if err != nil {
		return nil, err
	}

	if _, ok := params["base_url"]; !ok {
		return nil, fmt.Errorf("You can't use the http wrapper without setting *base_url* in your config file")
	}

	return &http.HTTPStorage{storage}, nil
}
var HTTPS3StorageParameter StorageParameter = func(params map[string]string) (gostorages.Storage, error) {
	storage, err := S3StorageParameter(params)

	if err != nil {
		return nil, err
	}

	if _, ok := params["base_url"]; !ok {
		return nil, fmt.Errorf("You can't use the http wrapper without setting *base_url* in your config file")
	}

	return &http.HTTPStorage{storage}, nil
}
var S3StorageParameter StorageParameter = func(params map[string]string) (gostorages.Storage, error) {

	ACL, ok := gostorages.ACLs[params["acl"]]

	if !ok {
		return nil, fmt.Errorf("The ACL %s does not exist", params["acl"])
	}

	Region, ok := aws.Regions[params["region"]]

	if !ok {
		return nil, fmt.Errorf("The Region %s does not exist", params["region"])
	}

	return gostorages.NewS3Storage(
		params["access_key_id"],
		params["secret_access_key"],
		params["bucket_name"],
		params["location"],
		Region,
		ACL,
		params["base_url"],
	), nil
}

Jump to

Keyboard shortcuts

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