aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: 29eed8301fda2074c498cc074a13fba2addc23d8 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*

	This file is part of StaticWeb (https://github.com/Pacien/StaticWeb).

	StaticWeb is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	StaticWeb is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with StaticWeb. If not, see <http://www.gnu.org/licenses/>.

*/

package main

import (
	"flag"
	"log"
	"net/http"
	"os"
	"strings"
)

var params struct {
	addr, port, dir, log string
}

func defaultHandler(w http.ResponseWriter, r *http.Request) {
	host := strings.Split(*&r.Host, ":")
	if host[0] == "" {
		log.Println("No host")
		http.Error(w, "404 page not found", http.StatusNotFound)
		return
	}
	request := r.URL.Path[1:]
	requestedFile := *&params.dir + "/" + *&host[0] + "/" + *&request
	log.Println(requestedFile)
	file, err := os.Stat(requestedFile)
	if err != nil {
		log.Println(err)
		http.Error(w, "404 page not found", http.StatusNotFound)
		return
	}
	if file.IsDir() && !strings.HasSuffix(requestedFile, "/") {
		http.Redirect(w, r, r.URL.Path+"/", http.StatusFound)
		return
	}
	http.ServeFile(w, r, *&requestedFile)
}

func init() {
	flag.StringVar(&params.addr, "addr", "127.0.0.1", "Address to listen.")
	flag.StringVar(&params.port, "port", "8080", "Port to listen.")
	flag.StringVar(&params.dir, "dir", ".", "Absolute or relative path to the root directory to serve.")
	flag.StringVar(&params.log, "log", "", "Absolute or relative path to the log file. Leave empty for stdout.")
	flag.Parse()
}

func main() {
	if params.log != "" {
		logFile, err := os.OpenFile(*&params.log, os.O_WRONLY, 0666)
		if os.IsNotExist(*&err) {
			log.Println("Log file not found, creating a new log file:", *&err)
			logFile, err = os.Create(*&params.log)
			if err != nil {
				log.Println("Cannot create log file:", *&err)
				return
			}
		} else if *&err != nil {
			log.Println("Cannot open log file:", *&err)
			return
		}
		defer logFile.Close()
		log.SetOutput(*&logFile)
	}

	log.Println("Starting StaticWeb on " + *&params.addr + ":" + *&params.port)

	http.HandleFunc("/", defaultHandler)
	err := http.ListenAndServe(*&params.addr+":"+*&params.port, nil)
	if err != nil {
		log.Println(*&err)
		return
	}
}