configui/util.go

131 lines
2.4 KiB
Go
Raw Normal View History

2021-10-18 10:59:09 +00:00
package main
import (
"archive/tar"
2021-10-18 18:38:28 +00:00
"bytes"
2021-10-18 10:59:09 +00:00
"compress/gzip"
"io"
"log"
2021-10-18 18:38:28 +00:00
"net"
2021-10-18 10:59:09 +00:00
"net/http"
"os"
2021-10-18 15:53:49 +00:00
"strings"
2021-10-18 10:59:09 +00:00
)
2021-10-18 18:38:28 +00:00
func Middleware(next http.Handler) http.Handler {
2021-10-18 10:59:09 +00:00
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
2021-10-18 15:53:49 +00:00
defer func() {
r := recover()
if r != nil {
log.Println("panic", r)
w.WriteHeader(500)
}
}()
2021-10-18 18:38:28 +00:00
abort := false
if flagAllow != "" {
if GetIP(r) != flagAllow {
HttpWriter(w, 403, "permission denyed")
abort = true
}
}
if !abort {
next.ServeHTTP(w, r)
}
log.Printf("%s %s %s %s\n", GetIP(r), r.Method, r.URL, r.Header.Get("User-Agent"))
2021-10-18 10:59:09 +00:00
},
)
}
func bundle(buf io.Writer, paths []string, flat bool) error {
gw := gzip.NewWriter(buf)
defer gw.Close()
tw := tar.NewWriter(gw)
defer tw.Close()
for _, file := range paths {
if err := func(file string) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return err
}
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
// Use full path as name (FileInfoHeader only takes the basename)
// If we don't do this the directory strucuture would
// not be preserved
// https://golang.org/src/archive/tar/common.go?#L626
if !flat {
2021-10-18 15:53:49 +00:00
if !strings.HasPrefix(file, "/") {
file = "configui/" + file
} else {
file = "configui" + file
}
2021-10-18 10:59:09 +00:00
header.Name = file
}
// Write file header to the tar archive
err = tw.WriteHeader(header)
if err != nil {
return err
}
// Copy file content to tar archive
_, err = io.Copy(tw, f)
if err != nil {
return err
}
return nil
}(file); err != nil {
return err
}
}
return nil
}
2021-10-18 15:53:49 +00:00
func HttpWriter(w http.ResponseWriter, status int, errStr string) {
w.WriteHeader(status)
w.Write([]byte(errStr))
}
2021-10-18 18:38:28 +00:00
func GetIP(r *http.Request) string {
ip := r.Header.Get("X-Real-Ip")
if ip == "" {
ips := r.Header.Get("X-Forwarded-For")
ipArr := strings.Split(ips, ",")
ip = strings.Trim(ipArr[len(ipArr)-1], " ")
}
if ip == "" {
var err error
ip, _, err = net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
}
return ip
}
func serve(w http.ResponseWriter, name string, data interface{}) error {
buf := &bytes.Buffer{}
err := tmpl.ExecuteTemplate(buf, "home", data)
if err != nil {
HttpWriter(w, 500, err.Error())
return err
}
_, err = w.Write(buf.Bytes())
return err
}