feat/prism
Evan Chen 2021-10-19 02:38:28 +08:00
parent 8432135f3d
commit f654cd347c
8 changed files with 165 additions and 39 deletions

16
api.go
View File

@ -107,15 +107,19 @@ func LoadConfig(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok")) w.Write([]byte("ok"))
} }
func GetConfig(w http.ResponseWriter, r *http.Request) { func getConfigHandler(w http.ResponseWriter, r *http.Request) {
config := []configui.File{} data, err := GetConfig()
for _, f := range files {
config = append(config, *f)
}
data, err := json.Marshal(config)
if err != nil { if err != nil {
HttpWriter(w, 500, err.Error()) HttpWriter(w, 500, err.Error())
return return
} }
w.Write(data) w.Write(data)
} }
func GetConfig() ([]byte, error) {
config := []configui.File{}
for _, f := range files {
config = append(config, *f)
}
return json.Marshal(config)
}

25
main.go
View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"bytes"
"embed" "embed"
"flag" "flag"
"fmt" "fmt"
@ -13,6 +12,7 @@ import (
"time" "time"
"kumoly.io/tools/configui/configui" "kumoly.io/tools/configui/configui"
"kumoly.io/tools/configui/public"
) )
//go:embed templates //go:embed templates
@ -27,6 +27,7 @@ var (
flagBind string flagBind string
flagLogFile string flagLogFile string
flagAllow string
flagVer bool flagVer bool
) )
@ -42,6 +43,7 @@ func init() {
flag.StringVar(&flagAlias, "n", "", "alias of file") flag.StringVar(&flagAlias, "n", "", "alias of file")
flag.StringVar(&flagAction, "c", "", "cmd to apply") flag.StringVar(&flagAction, "c", "", "cmd to apply")
flag.StringVar(&flagLogFile, "log", "", "log to file") flag.StringVar(&flagLogFile, "log", "", "log to file")
flag.StringVar(&flagAllow, "allow", "", "IPs to allow, blank to allow all")
flag.StringVar(&flagBind, "bind", "localhost:8000", "address to bind") flag.StringVar(&flagBind, "bind", "localhost:8000", "address to bind")
flag.BoolVar(&flagVer, "v", false, "show version") flag.BoolVar(&flagVer, "v", false, "show version")
flag.Usage = func() { flag.Usage = func() {
@ -96,7 +98,7 @@ func main() {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/api/conf", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/api/conf", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" { if r.Method == "GET" {
GetConfig(w, r) getConfigHandler(w, r)
} else if r.Method == "POST" { } else if r.Method == "POST" {
LoadConfig(w, r) LoadConfig(w, r)
} else { } else {
@ -133,28 +135,15 @@ func main() {
w.WriteHeader(404) w.WriteHeader(404)
} }
}) })
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
buf := &bytes.Buffer{}
err := tmpl.ExecuteTemplate(buf, "home", nil)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
} else {
w.Write(buf.Bytes())
}
})
mux.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.FS(public.FS))))
tmpl = template.Must(template.New("").ParseFS(tmplFS, "templates/*.tmpl", "templates/**/*.tmpl")) tmpl = template.Must(template.New("").ParseFS(tmplFS, "templates/*.tmpl", "templates/**/*.tmpl"))
setRoutes(mux)
server := &http.Server{ server := &http.Server{
Addr: flagBind, Addr: flagBind,
WriteTimeout: time.Second * 3, WriteTimeout: time.Second * 3,
ReadTimeout: time.Second * 30, ReadTimeout: time.Second * 30,
Handler: LogMiddleware(mux), Handler: Middleware(mux),
} }
// start server // start server

6
public/embed.go Normal file
View File

@ -0,0 +1,6 @@
package public
import "embed"
//go:embed js css
var FS embed.FS

42
route.go Normal file
View File

@ -0,0 +1,42 @@
package main
import (
"net/http"
)
func setRoutes(mux *http.ServeMux) {
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
Files := []string{}
for file := range files {
Files = append(Files, files[file].Alias)
}
contentB, err := GetConfig()
content := ""
if err != nil {
content = err.Error()
} else {
content = string(contentB)
}
data := struct {
Active string
Files []string
Content string
Lang string
}{
Files: Files,
Active: "ConfigUI",
Content: content,
Lang: "json",
}
serve(w, "home", data)
})
}

View File

@ -1,6 +1,9 @@
{{define "base/footer"}} {{define "base/footer"}}
<script src="/public/js/main.js"></script> <script src="/public/js/main.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <!-- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> -->
<script src="public/js/prism1.23.0.min.js"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/prism.min.js"></script> -->
</body> </body>
</html> </html>
{{end}} {{end}}

View File

@ -4,8 +4,10 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Serviced</title> <title>ConfigUI</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css"> <link rel="stylesheet" href="/public/css/bulma0.9.3.min.css">
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css"> -->
<link rel="stylesheet" href="/public/css/main.css">
</head> </head>
<body> <body>
{{end}} {{end}}

View File

@ -1,14 +1,54 @@
{{define "home"}} {{define "home"}}
{{template "base/header" .}} {{template "base/header" .}}
<div class="columns is-mobile is-centered">
<div class="column is-half">
<section class="section"> <section class="section">
<div class="container"> <container class="container is-max-desktop">
<h1 class="title"> <h1 class="title">ConfigUI</h1>
Hello World </container>
</h1>
<p class="subtitle">
My first website with <strong>Bulma</strong>!
</p>
</div>
</section> </section>
</div>
</div>
<div class="tile is-ancestor mx-2">
<div class="tile is-3 is-vertical is-parent">
<div class="tile is-child box">
<section class="is-large">
<aside class="menu">
<p class="menu-label">
Files
</p>
<ul class="menu-list">
{{ range .Files }}
<li><a>{{ . }}</a></li>
{{ end }}
</ul>
<p class="menu-label">
ConfigUI
</p>
<ul class="menu-list">
<li><a{{if eq .Active "ConfigUI"}} class="is-active"{{end}}>config.json</a></li>
</ul>
</aside>
</section>
</div>
<div class="tile is-child box">
<p class="title">Two</p>
</div>
</div>
<div class="tile is-parent">
<div class="tile is-child box">
<p class="title">Three</p>
<textarea class="content" placeholder="Enter HTML Source Code" id="editing" spellcheck="false" oninput="update(this.value); sync_scroll(this);" onscroll="sync_scroll(this);" onkeydown="check_tab(this, event);"></textarea>
<pre id="highlighting" aria-hidden="true">
<code class="language-html" id="highlighting-content">{{.Content}}</code>
</pre>
<!-- <code-input class="content" id="edit" lang="{{.Lang}}" name="config">{{.Content}}</code-input> -->
</div>
</div>
</div>
{{template "base/footer" .}} {{template "base/footer" .}}
{{end}} {{end}}

44
util.go
View File

@ -2,15 +2,17 @@ package main
import ( import (
"archive/tar" "archive/tar"
"bytes"
"compress/gzip" "compress/gzip"
"io" "io"
"log" "log"
"net"
"net/http" "net/http"
"os" "os"
"strings" "strings"
) )
func LogMiddleware(next http.Handler) http.Handler { func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc( return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) { func(w http.ResponseWriter, r *http.Request) {
defer func() { defer func() {
@ -20,8 +22,18 @@ func LogMiddleware(next http.Handler) http.Handler {
w.WriteHeader(500) w.WriteHeader(500)
} }
}() }()
abort := false
if flagAllow != "" {
if GetIP(r) != flagAllow {
HttpWriter(w, 403, "permission denyed")
abort = true
}
}
if !abort {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
log.Printf("%s %s %s %s\n", r.RemoteAddr, r.Method, r.URL, r.Header.Get("User-Agent")) }
log.Printf("%s %s %s %s\n", GetIP(r), r.Method, r.URL, r.Header.Get("User-Agent"))
}, },
) )
} }
@ -88,3 +100,31 @@ func HttpWriter(w http.ResponseWriter, status int, errStr string) {
w.WriteHeader(status) w.WriteHeader(status)
w.Write([]byte(errStr)) w.Write([]byte(errStr))
} }
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
}