running go fmt

This commit is contained in:
Vincent Batts 2013-03-27 16:30:24 -04:00
parent 7ba7c07041
commit 9a5ded48a6
10 changed files with 906 additions and 925 deletions

View File

@ -15,15 +15,15 @@ import (
func PutFileFromPath(host, filename string) (path string, err error) {
ext := filepath.Ext(filename)
file, err := os.Open(filename)
if (err != nil) {
if err != nil {
return
}
resp, err := http.Post(host, mime.TypeByExtension(ext), bufio.NewReader(file))
if (err != nil) {
if err != nil {
return
}
bytes, err := ioutil.ReadAll(resp.Body)
if (err != nil) {
if err != nil {
return
}
return string(bytes), nil
@ -41,14 +41,14 @@ func FetchFileFromURL(url string) (filename string, err error) {
}
resp, err := client.Get(url)
defer resp.Body.Close()
if (err != nil) {
if err != nil {
return
}
mtime := resp.Header.Get("last-modified")
if (len(mtime) > 0) {
if len(mtime) > 0 {
t, err = time.Parse(http.TimeFormat, mtime)
if (err != nil) {
if err != nil {
return
}
} else {
@ -60,11 +60,11 @@ func FetchFileFromURL(url string) (filename string, err error) {
log.Println(resp)
bytes, err := ioutil.ReadAll(resp.Body)
if (err != nil) {
if err != nil {
return
}
err = ioutil.WriteFile(filepath.Join(os.TempDir(), url_filename), bytes, 0644)
if (err != nil) {
if err != nil {
return
}
err = os.Chtimes(filepath.Join(os.TempDir(), url_filename), t, t)
@ -72,4 +72,3 @@ func FetchFileFromURL(url string) (filename string, err error) {
// lastly, return
return filepath.Join(os.TempDir(), url_filename), nil
}

View File

@ -1,8 +1,8 @@
package main
import (
"launchpad.net/goyaml"
"io/ioutil"
"launchpad.net/goyaml"
)
type Config map[string]interface{}
@ -11,8 +11,10 @@ func (c *Config) GetBool(option string) (value bool) {
conf := Config{}
conf = *c
switch conf[option] {
default: value = false
case "yes", "on", "true": value = true
default:
value = false
case "yes", "on", "true":
value = true
}
return
}
@ -26,12 +28,12 @@ func (c *Config) GetString(option string) (value string) {
func ReadConfigFile(filename string) (config Config, err error) {
bytes, err := ioutil.ReadFile(filename)
if (err != nil) {
if err != nil {
return
}
err = goyaml.Unmarshal(bytes, &config)
if (err != nil) {
if err != nil {
return
}
@ -41,4 +43,3 @@ func ReadConfigFile(filename string) (config Config, err error) {
func WriteConfigFile(filename string, data []byte) (err error) {
return
}

View File

@ -1,4 +1,3 @@
package main
import (
@ -9,7 +8,7 @@ import (
func GetFileByFilename(filename string) (this_file File, err error) {
err = gfs.Find(bson.M{"filename": filename}).One(&this_file)
if (err != nil) {
if err != nil {
return this_file, err
}
return this_file, nil
@ -18,13 +17,13 @@ func GetFileByFilename(filename string) (this_file File, err error) {
func GetFileRandom() (this_file File, err error) {
r := Rand64()
err = gfs.Find(bson.M{"random": bson.M{"$gt": r}}).One(&this_file)
if (err != nil) {
if err != nil {
return this_file, err
}
if (len(this_file.Md5) == 0) {
if len(this_file.Md5) == 0 {
err = gfs.Find(bson.M{"random": bson.M{"$lt": r}}).One(&this_file)
}
if (err != nil) {
if err != nil {
return this_file, err
}
return this_file, nil
@ -33,7 +32,7 @@ func GetFileRandom() (this_file File, err error) {
/* Check whether this File filename is on Mongo */
func HasFileByFilename(filename string) (exists bool, err error) {
c, err := gfs.Find(bson.M{"filename": filename}).Count()
if (err != nil) {
if err != nil {
return false, err
}
exists = (c > 0)
@ -42,7 +41,7 @@ func HasFileByFilename(filename string) (exists bool, err error) {
func HasFileByMd5(md5 string) (exists bool, err error) {
c, err := gfs.Find(bson.M{"md5": md5}).Count()
if (err != nil) {
if err != nil {
return false, err
}
exists = (c > 0)
@ -51,10 +50,9 @@ func HasFileByMd5(md5 string) (exists bool, err error) {
func HasFileByKeyword(keyword string) (exists bool, err error) {
c, err := gfs.Find(bson.M{"metadata": bson.M{"keywords": keyword}}).Count()
if (err != nil) {
if err != nil {
return false, err
}
exists = (c > 0)
return exists, nil
}

View File

@ -35,4 +35,3 @@ func GetSmallHash() (small_hash string) {
io.WriteString(h, fmt.Sprintf("%d", time.Now().Unix()))
return fmt.Sprintf("%X", h.Sum(nil))
}

View File

@ -9,10 +9,10 @@ func TestRand64(t *testing.T) {
var i interface{}
i = Rand64()
v, ok := i.(int64)
if (!ok) {
if !ok {
t.Errorf("Rand64 returned wrong type")
}
if (v < 0) {
if v < 0 {
t.Errorf("Rand64 returned a too small number [%d]", v)
}
}
@ -21,7 +21,7 @@ func TestMd5Bytes(t *testing.T) {
var blob = []byte("Hurp til you Derp")
var expected = "3ef08fa896a154eee3c97f037c9d6dfc"
var actual = fmt.Sprintf("%x", GetMd5FromBytes(blob))
if (actual != expected) {
if actual != expected {
t.Errorf("Md5FromBytes sum did not match! %s != %s", actual, expected)
}
}
@ -30,11 +30,10 @@ func TestMd5String(t *testing.T) {
var blob = "Hurp til you Derp"
var expected = "3ef08fa896a154eee3c97f037c9d6dfc"
var actual = fmt.Sprintf("%x", GetMd5FromString(blob))
if (actual != expected) {
if actual != expected {
t.Errorf("Md5FromString sum did not match! %s != %s", actual, expected)
}
}
func TestHash(t *testing.T) {
}

View File

@ -58,40 +58,40 @@ func main() {
// to override variables
loadConfiguration(ConfigFile)
if (len(FetchUrl) > 0) {
if len(FetchUrl) > 0 {
file, err := FetchFileFromURL(FetchUrl)
if (err != nil) {
if err != nil {
log.Println(err)
return
}
log.Println(file)
} else if (RunAsServer) {
} else if RunAsServer {
log.Printf("%s", ServerIP)
runServer(ServerIP, ServerPort)
} else {
if (len(RemoteHost) == 0) {
if len(RemoteHost) == 0 {
log.Println("Please provide a remotehost!")
return
}
if (len(PutFile) == 0 ) { //&& len(flag.Args()) == 0) {
if len(PutFile) == 0 { //&& len(flag.Args()) == 0) {
log.Println("Please provide files to be uploaded!")
return
}
_, basename := filepath.Split(PutFile)
queryParams := "?filename=" + basename
if (len(FileKeywords) > 0) {
if len(FileKeywords) > 0 {
queryParams = queryParams + "&keywords=" + FileKeywords
} else {
log.Println("WARN: you didn't provide any keywords :-(")
}
url, err := url.Parse(RemoteHost + "/f/" + queryParams)
if (err != nil) {
if err != nil {
log.Println(err)
return
}
log.Printf("POSTing: %s\n", url.String())
url_path, err := PutFileFromPath(url.String(), PutFile)
if (err != nil) {
if err != nil {
log.Println(err)
return
}
@ -162,7 +162,7 @@ func init() {
func loadConfiguration(filename string) (c Config) {
//log.Printf("Attempting to load config file: %s", filename)
c, err := ReadConfigFile(filename)
if (err != nil) {
if err != nil {
//log.Println(err)
return Config{}
}
@ -178,31 +178,30 @@ func loadConfiguration(filename string) (c Config) {
// Only set variables from config file,
// if they weren't passed as flags
if (DefaultRunAsServer == RunAsServer && cRunAsServer) {
if DefaultRunAsServer == RunAsServer && cRunAsServer {
RunAsServer = cRunAsServer
}
if (DefaultServerIP == ServerIP && len(cServerIp) > 0) {
if DefaultServerIP == ServerIP && len(cServerIp) > 0 {
ServerIP = cServerIp
}
if (DefaultServerPort == ServerPort && len(cServerPort) > 0) {
if DefaultServerPort == ServerPort && len(cServerPort) > 0 {
ServerPort = cServerPort
}
if (DefaultMongoHost == MongoHost && len(cMongoHost) > 0) {
if DefaultMongoHost == MongoHost && len(cMongoHost) > 0 {
MongoHost = cMongoHost
}
if (DefaultMongoDB == MongoDB && len(cMongoDB) > 0) {
if DefaultMongoDB == MongoDB && len(cMongoDB) > 0 {
MongoDB = cMongoDB
}
if (DefaultMongoUsername == MongoUsername && len(cMongoUsername) > 0) {
if DefaultMongoUsername == MongoUsername && len(cMongoUsername) > 0 {
MongoUsername = cMongoUsername
}
if (DefaultMongoPassword == MongoPassword && len(cMongoPassword) > 0) {
if DefaultMongoPassword == MongoPassword && len(cMongoPassword) > 0 {
MongoPassword = cMongoPassword
}
if (DefaultRemoteHost == RemoteHost && len(cRemoteHost) > 0) {
if DefaultRemoteHost == RemoteHost && len(cRemoteHost) > 0 {
RemoteHost = cRemoteHost
}
return c
}

View File

@ -8,7 +8,6 @@ import (
var emptyInterface interface{}
var headTemplate = template.Must(template.New("head").Parse(headTemplateHTML))
var headTemplateHTML = `
<html>
@ -129,46 +128,46 @@ var listTemplateHTML = `
func UrliePage(w io.Writer) (err error) {
err = headTemplate.Execute(w, map[string]string{"title": "FileSrv :: URLie"})
if (err != nil) {
if err != nil {
return err
}
err = navbarTemplate.Execute(w, nil)
if (err != nil) {
if err != nil {
return err
}
err = containerBeginTemplate.Execute(w, nil)
if (err != nil) {
if err != nil {
return err
}
err = formGetUrlTemplate.Execute(w, &emptyInterface)
if (err != nil) {
if err != nil {
return err
}
err = tailTemplate.Execute(w, map[string]string{"footer": fmt.Sprintf("Version: %s", VERSION)})
if (err != nil) {
if err != nil {
return err
}
return
}
func UploadPage(w io.Writer) (err error) {
err = headTemplate.Execute(w, map[string]string{"title": "FileSrv :: Upload"})
if (err != nil) {
if err != nil {
return err
}
err = navbarTemplate.Execute(w, nil)
if (err != nil) {
if err != nil {
return err
}
err = containerBeginTemplate.Execute(w, nil)
if (err != nil) {
if err != nil {
return err
}
err = formFileUploadTemplate.Execute(w, &emptyInterface)
if (err != nil) {
if err != nil {
return err
}
err = tailTemplate.Execute(w, map[string]string{"footer": fmt.Sprintf("Version: %s", VERSION)})
if (err != nil) {
if err != nil {
return err
}
return
@ -176,38 +175,28 @@ func UploadPage(w io.Writer) (err error) {
func ListFilesPage(w io.Writer, files []File) (err error) {
err = headTemplate.Execute(w, map[string]string{"title": "FileSrv"})
if (err != nil) {
if err != nil {
return err
}
err = navbarTemplate.Execute(w, nil)
if (err != nil) {
if err != nil {
return err
}
err = containerBeginTemplate.Execute(w, nil)
if (err != nil) {
if err != nil {
return err
}
err = listTemplate.Execute(w, files)
if (err != nil) {
if err != nil {
return err
}
err = tailTemplate.Execute(w, map[string]string{"footer": fmt.Sprintf("Version: %s", VERSION)})
if (err != nil) {
if err != nil {
return err
}
return
}
var bootstrapCSS = `
/*!
* Bootstrap v2.2.2
@ -6249,5 +6238,3 @@ a.badge:hover {
position: fixed;
}
`

209
server.go
View File

@ -16,6 +16,43 @@ import (
var defaultPageLimit int = 25
/* Run as the image server */
func runServer(ip, port string) {
var addr = fmt.Sprintf("%s:%s", ip, port)
initMongo()
defer mongo_session.Close()
http.HandleFunc("/", routeRoot)
http.HandleFunc("/assets/", routeAssets)
http.HandleFunc("/upload", routeUpload)
http.HandleFunc("/urlie", routeGetFromUrl)
http.HandleFunc("/all", routeAll)
http.HandleFunc("/f/", routeFiles)
http.HandleFunc("/k/", routeKeywords)
http.HandleFunc("/ip/", routeIPs)
http.HandleFunc("/ext/", routeExt)
http.HandleFunc("/md5/", routeMD5s)
log.Printf("Serving on %s ...", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}
func initMongo() {
mongo_session, err := mgo.Dial(MongoHost)
if err != nil {
log.Panic(err)
}
images_db = mongo_session.DB(MongoDB)
if len(MongoUsername) > 0 && len(MongoPassword) > 0 {
err = images_db.Login(MongoUsername, MongoPassword)
if err != nil {
log.Panic(err)
}
}
gfs = images_db.GridFS("fs")
}
func serverErr(w http.ResponseWriter, r *http.Request, e error) {
log.Printf("Error: %s", e)
LogRequest(r, 503)
@ -39,7 +76,7 @@ func linkToFile(root string, filename string) (html string) {
*/
func chunkURI(uri string) (chunks []string) {
var str string
if (uri[0] == '/') {
if uri[0] == '/' {
str = uri[1:]
} else {
str = uri
@ -81,24 +118,24 @@ func LogRequest(r *http.Request, statusCode int) {
// Show a page of most recent images, and tags, and uploaders ...
func routeFilesGET(w http.ResponseWriter, r *http.Request) {
uriChunks := chunkURI(r.URL.Path)
if ( len(uriChunks) > 2 ) {
if len(uriChunks) > 2 {
LogRequest(r, 404)
http.NotFound(w, r)
return
}
if (len(uriChunks) == 2 && len(uriChunks[1]) > 0) {
if len(uriChunks) == 2 && len(uriChunks[1]) > 0 {
log.Printf("Searching for [%s] ...", uriChunks[1])
query := gfs.Find(bson.M{"filename": uriChunks[1]})
c, err := query.Count()
// preliminary checks, if they've passed an image name
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
log.Printf("Results for [%s] = %d", uriChunks[1], c)
if (c == 0) {
if c == 0 {
LogRequest(r, 404)
http.NotFound(w, r)
return
@ -110,7 +147,7 @@ func routeFilesGET(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
file, err := gfs.Open(uriChunks[1])
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -131,9 +168,9 @@ func routeFilesGET(w http.ResponseWriter, r *http.Request) {
// look for an image in the r.Body
func routeFilesPOST(w http.ResponseWriter, r *http.Request) {
uriChunks := chunkURI(r.URL.Path)
if (len(uriChunks) > 2 &&
if len(uriChunks) > 2 &&
((len(uriChunks) == 2 && len(uriChunks[1]) == 0) &&
len(r.URL.RawQuery) == 0 )) {
len(r.URL.RawQuery) == 0) {
LogRequest(r, 403)
http.Error(w, "Not Acceptable", 403)
return
@ -147,16 +184,16 @@ func routeFilesPOST(w http.ResponseWriter, r *http.Request) {
}
filename = r.FormValue("filename")
if (len(filename) == 0 && len(uriChunks) == 2 && len(uriChunks[1]) != 0) {
if len(filename) == 0 && len(uriChunks) == 2 && len(uriChunks[1]) != 0 {
filename = uriChunks[1]
}
log.Printf("%s\n", filename)
var p_ext string
p_ext = r.FormValue("ext")
if (len(filename) > 0 && len(p_ext) == 0) {
if len(filename) > 0 && len(p_ext) == 0 {
p_ext = filepath.Ext(filename)
} else if (len(p_ext) > 0 && strings.HasPrefix(p_ext, ".")) {
} else if len(p_ext) > 0 && strings.HasPrefix(p_ext, ".") {
p_ext = fmt.Sprintf(".%s", p_ext)
}
@ -165,8 +202,8 @@ func routeFilesPOST(w http.ResponseWriter, r *http.Request) {
"keys", "keywords",
} {
v := r.FormValue(word)
if (len(v) > 0) {
if (strings.Contains(v, ",")) {
if len(v) > 0 {
if strings.Contains(v, ",") {
info.Keywords = append(info.Keywords, strings.Split(v, ",")...)
} else {
info.Keywords = append(info.Keywords, v)
@ -174,9 +211,9 @@ func routeFilesPOST(w http.ResponseWriter, r *http.Request) {
}
}
if (len(filename) == 0) {
if len(filename) == 0 {
str := GetSmallHash()
if (len(p_ext) == 0) {
if len(p_ext) == 0 {
filename = fmt.Sprintf("%s.jpg", str)
} else {
filename = fmt.Sprintf("%s%s", str, p_ext)
@ -184,10 +221,10 @@ func routeFilesPOST(w http.ResponseWriter, r *http.Request) {
}
exists, err := HasFileByFilename(filename)
if (err == nil && !exists) {
if err == nil && !exists {
file, err := gfs.Create(filename)
defer file.Close()
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -196,30 +233,30 @@ func routeFilesPOST(w http.ResponseWriter, r *http.Request) {
// copy the request body into the gfs file
n, err := io.Copy(file, r.Body)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
if (n != r.ContentLength) {
if n != r.ContentLength {
log.Printf("WARNING: [%s] content-length (%d), content written (%d)",
filename,
r.ContentLength,
n)
}
} else if (exists) {
if (r.Method == "PUT") {
} else if exists {
if r.Method == "PUT" {
// TODO nothing will get here presently. Workflow needs more review
file, err := gfs.Open(filename)
defer file.Close()
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
var mInfo Info
err = file.GetMeta(&mInfo)
if (err != nil) {
if err != nil {
log.Printf("ERROR: failed to get metadata for %s. %s\n", filename, err)
}
mInfo.Keywords = append(mInfo.Keywords, info.Keywords...)
@ -232,7 +269,7 @@ func routeFilesPOST(w http.ResponseWriter, r *http.Request) {
return
}
if (strings.Contains(r.Header.Get("Accept"), "text/html")) {
if strings.Contains(r.Header.Get("Accept"), "text/html") {
io.WriteString(w,
fmt.Sprintf("<a href=\"/f/%s\">/f/%s</a>\n", filename, filename))
} else {
@ -251,20 +288,20 @@ func routeFilesPUT(w http.ResponseWriter, r *http.Request) {
func routeFilesDELETE(w http.ResponseWriter, r *http.Request) {
uriChunks := chunkURI(r.URL.Path)
if ( len(uriChunks) > 2 ) {
if len(uriChunks) > 2 {
LogRequest(r, 404)
http.NotFound(w, r)
return
} else if (len(uriChunks) == 2 && len(uriChunks[1]) == 0) {
} else if len(uriChunks) == 2 && len(uriChunks[1]) == 0 {
}
exists, err := HasFileByFilename(uriChunks[1])
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
if (exists) {
if exists {
err = gfs.Remove(uriChunks[1])
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -294,7 +331,7 @@ func routeFiles(w http.ResponseWriter, r *http.Request) {
}
func routeRoot(w http.ResponseWriter, r *http.Request) {
if (r.Method != "GET") {
if r.Method != "GET" {
LogRequest(r, 404)
http.NotFound(w, r)
return
@ -305,7 +342,7 @@ func routeRoot(w http.ResponseWriter, r *http.Request) {
//iter := gfs.Find(bson.M{"uploadDate": bson.M{"$gt": time.Now().Add(-time.Hour)}}).Limit(defaultPageLimit).Iter()
var files []File
err := gfs.Find(nil).Sort("-metadata.timestamp").Limit(defaultPageLimit).All(&files)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -314,7 +351,7 @@ func routeRoot(w http.ResponseWriter, r *http.Request) {
}
func routeAll(w http.ResponseWriter, r *http.Request) {
if (r.Method != "GET") {
if r.Method != "GET" {
LogRequest(r, 404)
http.NotFound(w, r)
return
@ -325,7 +362,7 @@ func routeAll(w http.ResponseWriter, r *http.Request) {
// Show a page of all the images
var files []File
err := gfs.Find(nil).All(&files)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -344,13 +381,13 @@ func routeAll(w http.ResponseWriter, r *http.Request) {
*/
func routeKeywords(w http.ResponseWriter, r *http.Request) {
uriChunks := chunkURI(r.URL.Path)
if (r.Method != "GET" ||
if r.Method != "GET" ||
len(uriChunks) > 3 ||
(len(uriChunks) == 3 && uriChunks[2] != "r")) {
(len(uriChunks) == 3 && uriChunks[2] != "r") {
LogRequest(r, 404)
http.NotFound(w, r)
return
} else if (len(uriChunks) == 1 || (len(uriChunks) == 2 && len(uriChunks[1]) == 0)) {
} else if len(uriChunks) == 1 || (len(uriChunks) == 2 && len(uriChunks[1]) == 0) {
routeRoot(w, r)
return
}
@ -358,19 +395,19 @@ func routeKeywords(w http.ResponseWriter, r *http.Request) {
log.Printf("K: %s (%d)", uriChunks, len(uriChunks))
var iter *mgo.Iter
if (uriChunks[len(uriChunks)-1] == "r") {
if uriChunks[len(uriChunks)-1] == "r" {
// TODO determine how to show a random image by keyword ...
log.Println("random isn't built yet")
LogRequest(r, 404)
return
} else if (len(uriChunks) == 2) {
} else if len(uriChunks) == 2 {
log.Println(uriChunks[1])
iter = gfs.Find(bson.M{"metadata.keywords": uriChunks[1]}).Sort("-metadata.timestamp").Limit(defaultPageLimit).Iter()
}
var files []File
err := iter.All(&files)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -382,11 +419,11 @@ func routeKeywords(w http.ResponseWriter, r *http.Request) {
func routeMD5s(w http.ResponseWriter, r *http.Request) {
uriChunks := chunkURI(r.URL.Path)
if (r.Method != "GET") {
if r.Method != "GET" {
LogRequest(r, 404)
http.NotFound(w, r)
return
} else if (len(uriChunks) != 2) {
} else if len(uriChunks) != 2 {
// they didn't give an MD5, re-route
routeRoot(w, r)
return
@ -394,7 +431,7 @@ func routeMD5s(w http.ResponseWriter, r *http.Request) {
var files []File
err := gfs.Find(bson.M{"md5": uriChunks[1]}).Sort("-metadata.timestamp").Limit(defaultPageLimit).All(&files)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -405,7 +442,7 @@ func routeMD5s(w http.ResponseWriter, r *http.Request) {
// Show a page of file extensions, and allow paging by ext
func routeExt(w http.ResponseWriter, r *http.Request) {
if (r.Method != "GET") {
if r.Method != "GET" {
LogRequest(r, 404)
http.NotFound(w, r)
return
@ -416,7 +453,7 @@ func routeExt(w http.ResponseWriter, r *http.Request) {
// Show a page of all the uploader's IPs, and the images
func routeIPs(w http.ResponseWriter, r *http.Request) {
if (r.Method != "GET") {
if r.Method != "GET" {
LogRequest(r, 404)
http.NotFound(w, r)
return
@ -430,7 +467,7 @@ func routeIPs(w http.ResponseWriter, r *http.Request) {
POST /urlie
*/
func routeGetFromUrl(w http.ResponseWriter, r *http.Request) {
if (r.Method == "POST") {
if r.Method == "POST" {
info := Info{
Ip: r.RemoteAddr,
Random: Rand64(),
@ -439,21 +476,21 @@ func routeGetFromUrl(w http.ResponseWriter, r *http.Request) {
log.Println(info)
err := r.ParseMultipartForm(1024 * 5)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
log.Printf("%q", r.MultipartForm.Value)
var local_filename string
for k, v := range r.MultipartForm.Value {
if (k == "keywords") {
if k == "keywords" {
info.Keywords = append(info.Keywords, strings.Split(v[0], ",")...)
} else if (k == "url") {
} else if k == "url" {
local_filename, err = FetchFileFromURL(v[0])
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
} else if (len(local_filename) == 0) {
} else if len(local_filename) == 0 {
LogRequest(r, 404)
http.NotFound(w, r)
return
@ -464,17 +501,17 @@ func routeGetFromUrl(w http.ResponseWriter, r *http.Request) {
}
}
exists, err := HasFileByFilename(local_filename)
if (err == nil && !exists) {
if err == nil && !exists {
file, err := gfs.Create(filepath.Base(local_filename))
defer file.Close()
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
local_fh, err := os.Open(local_filename)
defer local_fh.Close()
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -483,7 +520,7 @@ func routeGetFromUrl(w http.ResponseWriter, r *http.Request) {
// copy the request body into the gfs file
n, err := io.Copy(file, local_fh)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -494,7 +531,7 @@ func routeGetFromUrl(w http.ResponseWriter, r *http.Request) {
serverErr(w, r, err)
return
}
} else if (r.Method == "GET") {
} else if r.Method == "GET" {
UrliePage(w)
} else {
LogRequest(r, 404)
@ -509,7 +546,7 @@ func routeGetFromUrl(w http.ResponseWriter, r *http.Request) {
POST /upload
*/
func routeUpload(w http.ResponseWriter, r *http.Request) {
if (r.Method == "POST") {
if r.Method == "POST" {
info := Info{
Ip: r.RemoteAddr,
Random: Rand64(),
@ -518,13 +555,13 @@ func routeUpload(w http.ResponseWriter, r *http.Request) {
// handle the form posting to this route
err := r.ParseMultipartForm(1024 * 5)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
log.Printf("%q", r.MultipartForm.Value)
for k, v := range r.MultipartForm.Value {
if (k == "keywords") {
if k == "keywords" {
info.Keywords = append(info.Keywords, strings.Split(v[0], ",")...)
} else {
log.Printf("WARN: not sure what to do with param [%s = %s]", k, v)
@ -533,29 +570,29 @@ func routeUpload(w http.ResponseWriter, r *http.Request) {
filehdr := r.MultipartForm.File["filename"][0]
exists, err := HasFileByFilename(filehdr.Filename)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
} else if (err == nil && !exists) {
} else if err == nil && !exists {
file, err := gfs.Create(filehdr.Filename)
defer file.Close()
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
file.SetMeta(&info)
multiFile, err := filehdr.Open()
if (err != nil) {
if err != nil {
log.Println(err)
return
}
n, err := io.Copy(file, multiFile)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
if (n != r.ContentLength) {
if n != r.ContentLength {
log.Printf("WARNING: [%s] content-length (%d), content written (%d)",
filehdr.Filename,
r.ContentLength,
@ -563,13 +600,13 @@ func routeUpload(w http.ResponseWriter, r *http.Request) {
}
http.Redirect(w, r, fmt.Sprintf("/f/%s", filehdr.Filename), 302)
} else if (exists) {
} else if exists {
// print some message about the file already existing
} else {
serverErr(w, r, err)
return
}
} else if (r.Method == "GET") {
} else if r.Method == "GET" {
// Show the upload form
UploadPage(w)
} else {
@ -582,7 +619,7 @@ func routeUpload(w http.ResponseWriter, r *http.Request) {
func routeAssets(w http.ResponseWriter, r *http.Request) {
path, err := filepath.Rel("/assets", r.URL.Path)
if (err != nil) {
if err != nil {
serverErr(w, r, err)
return
}
@ -593,41 +630,3 @@ func routeAssets(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/css")
}
}
func initMongo() {
mongo_session, err := mgo.Dial(MongoHost)
if err != nil {
log.Panic(err)
}
images_db = mongo_session.DB(MongoDB)
if (len(MongoUsername) > 0 && len(MongoPassword) > 0) {
err = images_db.Login(MongoUsername, MongoPassword)
if (err != nil) {
log.Panic(err)
}
}
gfs = images_db.GridFS("fs")
}
/* Run as the image server */
func runServer(ip, port string) {
var addr = fmt.Sprintf("%s:%s", ip, port)
initMongo()
defer mongo_session.Close()
http.HandleFunc("/", routeRoot)
http.HandleFunc("/assets/", routeAssets)
http.HandleFunc("/upload", routeUpload)
http.HandleFunc("/urlie", routeGetFromUrl)
http.HandleFunc("/all", routeAll)
http.HandleFunc("/f/", routeFiles)
http.HandleFunc("/k/", routeKeywords)
http.HandleFunc("/ip/", routeIPs)
http.HandleFunc("/ext/", routeExt)
http.HandleFunc("/md5/", routeMD5s)
log.Printf("Serving on %s ...", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}