2014-04-26 09:18:56 +00:00
package StaticFiles
2014-10-19 17:19:11 +00:00
import (
"fmt"
"github.com/SommerEngineering/Ocean/Log"
LM "github.com/SommerEngineering/Ocean/Log/Meta"
"github.com/SommerEngineering/Ocean/MimeTypes"
"github.com/SommerEngineering/Ocean/Shutdown"
"net/http"
"strings"
)
2014-04-26 09:18:56 +00:00
2015-06-17 15:44:52 +00:00
// Handler to deliver static files.
2014-04-26 09:18:56 +00:00
func HandlerStaticFiles ( response http . ResponseWriter , request * http . Request ) {
2015-06-17 15:44:52 +00:00
// Case: The system goes down.
2014-04-26 09:18:56 +00:00
if Shutdown . IsDown ( ) {
http . NotFound ( response , request )
return
}
2015-06-17 15:44:52 +00:00
// Prepare the path by removing the prefix:
2014-04-26 09:18:56 +00:00
path := strings . Replace ( request . RequestURI , ` /staticFiles/ ` , ` ` , 1 )
path = strings . Replace ( path , ` %20 ` , ` ` , - 1 )
fileType := ` `
// Determine the MIME type:
if mimeType , errMime := MimeTypes . DetectType ( path ) ; errMime != nil {
Log . LogFull ( senderName , LM . CategorySYSTEM , LM . LevelWARN , LM . SeverityMiddle , LM . ImpactMiddle , LM . MessageNameNOTFOUND , ` Was not able to detect the MIME type of the font. ` , errMime . Error ( ) , path )
http . NotFound ( response , request )
return
} else {
fileType = mimeType . MimeType
}
2015-06-17 15:44:52 +00:00
// Case: Was not able to determine the file's type.
2014-04-26 09:18:56 +00:00
if fileType == ` ` {
Log . LogFull ( senderName , LM . CategorySYSTEM , LM . LevelSECURITY , LM . SeverityCritical , LM . ImpactUnknown , LM . MessageNameNOTFOUND , ` The mime type is unknown. ` , path )
http . NotFound ( response , request )
return
}
2015-06-17 15:44:52 +00:00
// Read the file's content:
2014-04-26 09:18:56 +00:00
contentData := FindAndReadFile ( path )
2015-06-17 15:44:52 +00:00
// Case: Was not able to read the file.
2014-04-26 09:18:56 +00:00
if contentData == nil {
Log . LogFull ( senderName , LM . CategorySYSTEM , LM . LevelERROR , LM . SeverityCritical , LM . ImpactCritical , LM . MessageNameDATABASE , ` The desired file was not found. ` , path )
http . NotFound ( response , request )
return
}
2015-06-17 15:44:52 +00:00
// Send the meta data and the content to the client:
2014-04-26 09:18:56 +00:00
fileLenText := fmt . Sprintf ( ` %d ` , len ( contentData ) )
response . Header ( ) . Add ( ` Content-Length ` , fileLenText )
response . Header ( ) . Add ( ` Content-Type ` , fileType )
response . Write ( contentData )
2015-06-17 15:44:52 +00:00
// Log all static files accesses?
2014-04-26 09:18:56 +00:00
if logStaticFileRequests {
Log . LogShort ( senderName , LM . CategorySYSTEM , LM . LevelINFO , LM . MessageNameBROWSER , ` A static file was requested. ` , path )
}
return
}