Skip to content

Instantly share code, notes, and snippets.

@maliqq
Last active August 29, 2015 14:09
Show Gist options
  • Save maliqq/c662d426080e022c74b5 to your computer and use it in GitHub Desktop.
Save maliqq/c662d426080e022c74b5 to your computer and use it in GitHub Desktop.
package main
import "bytes"
import "io"
import "os"
import "strings"
import "strconv"
import "fmt"
import "flag"
import "net/http"
import "encoding/json"
const (
TITLE = "Logs"
)
var (
N = []int{100, 500, 1000, 5000}
)
func urlFor(f string) string {
return "?file=" + f
}
func urlForTail(f string, n int) string {
return urlFor(f) + "&n=" + strconv.Itoa(n)
}
func renderListing(files map[string]string) string {
html := "<html><head><title>" + TITLE + "</title></head><body><ul>"
for file, _ := range files {
html += "<li>"
html += "<a href=\"" + urlFor(file) + "\">"
html += file
html += "</a>"
for _, i := range N {
html += " (<a href=\"" + urlForTail(file, i) + "#tail\">"
html += strconv.Itoa(i)
html += "</a>)"
}
html += "</li>"
}
html += "</ul></body></html>"
return html
}
func tail(f string, lines int, w http.ResponseWriter) {
buffer := bytes.NewBuffer(nil)
file, _ := os.Open(f)
io.Copy(buffer, file)
file.Close()
bufferString := buffer.String()
total := strings.Count(bufferString, "\n")
if total < lines {
lines = total
}
stringArray := strings.Split(bufferString, "\n")
for i := total - lines; i < total; i++ {
w.Write([]byte(stringArray[i]))
w.Write([]byte{0x0a})
}
}
func main() {
files := map[string]string{}
flag.Parse()
listingFile := flag.Arg(0)
listing, err := os.Open(listingFile)
if err != nil {
fmt.Printf(listingFile)
panic(err)
}
dec := json.NewDecoder(listing)
dec.Decode(&files)
fmt.Println(files)
http.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/html; charset=UTF-8")
file := r.FormValue("file")
if file == "" {
html := renderListing(files)
w.Write([]byte(html))
return
}
if path, found := files[file]; found {
n := r.FormValue("n")
valid := false
lines := 0
if n != "" {
lines, _ = strconv.Atoi(n)
for _, i := range N {
if i == lines {
valid = true
break
}
}
}
w.Write([]byte("<!DOCTYPE html>\n<html><head><title>" + TITLE + "</title></head><body><pre>"))
if valid {
fmt.Printf("tailing %s %d\n", path, lines)
tail(path, lines, w)
} else {
fmt.Printf("reading %s\n", path)
f, _ := os.Open(path)
io.Copy(w, f)
f.Close()
}
w.Write([]byte("</pre><a name=\"tail\"></a></body></html>"))
return
}
http.Error(w, "Not found", 404)
})
http.ListenAndServe("127.0.0.1:10090", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment