summaryrefslogtreecommitdiff
path: root/main.go
blob: 3800de3fa38eaa99459855af40e77f94489b42fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"runtime/debug"

	"drop.janw.name/controller"
)

var CONFIG_FILENAME string

func registerHandler(pattern string, controller controller.Controller) {
	http.HandleFunc(pattern, func(res http.ResponseWriter, req *http.Request) {
		defer func() {
			err := recover()
			if err != nil {
				res.WriteHeader(http.StatusInternalServerError)
				fmt.Fprintln(res, "internal server error")
				fmt.Fprintln(res, err)
				fmt.Fprintln(res, string(debug.Stack()))
			}
		}()

		var methodFunc http.HandlerFunc

		switch req.Method {
		case http.MethodGet:
			methodFunc = controller.GET
		case http.MethodPost:
			methodFunc = controller.POST
		}

		log.Println(req.Method, req.RemoteAddr, req.RequestURI)

		if methodFunc != nil {
			methodFunc(res, req)
		} else {
			res.WriteHeader(http.StatusMethodNotAllowed)
			fmt.Fprintln(res, "method not allowed")
		}
	})
}

func init() {
	flag.StringVar(&CONFIG_FILENAME, "c", "config_example.json", "path to the configuration file")
	flag.Parse()
}

func main() {
	app := controller.NewApp(CONFIG_FILENAME)

	registerHandler("/", controller.Controller{
		GET:  app.Index,
		POST: app.FilePost,
	})

	registerHandler("/{file}", controller.Controller{
		GET: app.FileGet,
	})

	log.Println(fmt.Sprintf("serving on http://%s\n", "127.0.0.1:8080"))
	log.Panicln(http.ListenAndServe("127.0.0.1:8080", nil))
}