Skip to content

Commit

Permalink
Refactor: code layout
Browse files Browse the repository at this point in the history
  • Loading branch information
mgumz committed Nov 19, 2023
1 parent 33c56d2 commit b9bedef
Show file tree
Hide file tree
Showing 18 changed files with 95 additions and 90 deletions.
58 changes: 30 additions & 28 deletions cmd/knut/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ import (
"net/url"
"os"
"strings"

"github.com/mgumz/knut/internal/pkg/knut"
)

var (
Version = "1.5.0"
Version = "dev-build"
GitHash = ""
BuildDate = ""
)
Expand Down Expand Up @@ -114,22 +116,22 @@ func main() {
var h = http.Handler(tree)

if opts.addServerID != "" {
h = addServerIDHandler(h, opts.addServerID)
h = knut.AddServerIDHandler(h, opts.addServerID)
}
h = noCacheHandler(h)
h = knut.NoCacheHandler(h)
if opts.doCompress {
h = compressHandler(h)
h = knut.CompressHandler(h)
}
if opts.doAuth != "" {
parts := strings.SplitN(opts.doAuth, ":", 2)
if len(parts) == 0 {
fmt.Fprintf(os.Stderr, "error: missing separator for argument to -auth")
os.Exit(1)
}
h = basicAuthHandler(h, parts[0], parts[1])
h = knut.BasicAuthHandler(h, parts[0], parts[1])
}
if opts.doLog {
h = logRequestHandler(h, os.Stdout)
h = knut.LogRequestHandler(h, os.Stdout)
}

//
Expand All @@ -138,12 +140,12 @@ func main() {
var run func() error
switch {
case opts.tlsOnetime:
onetime := &onetimeTLS{}
onetime := &knut.OnetimeTLS{}
if err := onetime.Create(opts.bindAddr); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
run = func() error { return http.Serve(onetime.listener, h) }
run = func() error { return http.Serve(onetime.Listener, h) }
case opts.tlsCert != "" && opts.tlsKey != "":
run = func() error { return http.ListenAndServeTLS(opts.bindAddr, opts.tlsCert, opts.tlsKey, h) }
default:
Expand Down Expand Up @@ -175,7 +177,7 @@ func prepareTrees(muxer *http.ServeMux, mappings []string) (*http.ServeMux, int)

for i := range mappings {

window, tree, err = getWindowAndTree(mappings[i])
window, tree, err = knut.GetWindowAndTree(mappings[i])
if err != nil {
fmt.Fprintf(os.Stderr, "warning: parsing %q (pos %d): %v\n", mappings[i], i+1, err)
continue
Expand All @@ -192,62 +194,62 @@ func prepareTrees(muxer *http.ServeMux, mappings []string) (*http.ServeMux, int)
fmt.Fprintf(os.Stderr, "warning: existing %q is not a directory\n", tree)
continue
}
handler, verb = uploadHandler(tree), "catches"
handler, verb = knut.UploadHandler(tree), "catches"
case strings.HasPrefix(window, "30x"):
if window = window[3:]; window == "" {
fmt.Fprintf(os.Stderr, "warning: post uri in pair %d is empty\n", i)
continue
}
handler, verb = redirectHandler(window, tree), "points at"
handler, verb = knut.RedirectHandler(window, tree), "points at"
case tree[0] == STRING_HANDLER:
handler = serveStringHandler(tree[1:])
handler = knut.ServeStringHandler(tree[1:])
default:
if treeURL, err := url.Parse(tree); err == nil {
query := treeURL.Query()
switch treeURL.Scheme {
case "http", "https":
handler = httputil.NewSingleHostReverseProxy(treeURL)
case "file":
handler = fileOrDirHandler(localFilename(treeURL), window)
handler = knut.FileOrDirHandler(knut.LocalFilename(treeURL), window)
case "myip":
handler = myIPHandler()
handler = knut.MyIPHandler()
case "qr":
qrContent := treeURL.Path
if len(qrContent) <= 1 {
fmt.Fprintf(os.Stderr, "warning: qr:// needs content, %q\n", qrContent)
continue
}
qrContent = qrContent[1:] // cut away the leading /
handler = qrHandler(qrContent)
handler = setContentType(handler, "image/png")
handler = knut.QrHandler(qrContent)
handler = knut.SetContentType(handler, "image/png")
case "git":
handler = gitHandler(localFilename(treeURL), window)
handler = knut.GitHandler(knut.LocalFilename(treeURL), window)
case "cgit":
handler = cgitHandler(localFilename(treeURL), window)
handler = knut.CgitHandler(knut.LocalFilename(treeURL), window)
case "tar":
prefix := query.Get("prefix")
handler = tarHandler(localFilename(treeURL), prefix)
handler = setContentType(handler, "application/x-tar")
handler = knut.TarHandler(knut.LocalFilename(treeURL), prefix)
handler = knut.SetContentType(handler, "application/x-tar")
case "tar+gz", "tar.gz", "tgz":
prefix := query.Get("prefix")
clevel := query.Get("level")
handler = tarHandler(localFilename(treeURL), prefix)
handler = gzHandler(handler, clevel)
handler = setContentType(handler, "application/x-gtar")
handler = knut.TarHandler(knut.LocalFilename(treeURL), prefix)
handler = knut.GzHandler(handler, clevel)
handler = knut.SetContentType(handler, "application/x-gtar")
case "zip":
prefix := query.Get("prefix")
store := hasQueryParam("store", query)
handler = zipHandler(localFilename(treeURL), prefix, store)
handler = setContentType(handler, "application/zip")
store := knut.HasQueryParam("store", query)
handler = knut.ZipHandler(knut.LocalFilename(treeURL), prefix, store)
handler = knut.SetContentType(handler, "application/zip")
case "zipfs":
prefix := query.Get("prefix")
index := query.Get("index")
handler = zipFSHandler(localFilename(treeURL), prefix, index)
handler = knut.ZipFSHandler(knut.LocalFilename(treeURL), prefix, index)
}
}

if handler == nil {
handler = fileOrDirHandler(tree, window)
handler = knut.FileOrDirHandler(tree, window)
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2016 Mathias Gumz. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

package main
package knut

import (
"compress/flate"
Expand Down
11 changes: 6 additions & 5 deletions cmd/knut/git.go → internal/pkg/knut/git.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2015 Mathias Gumz. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

package main
package knut

import (
"net/http"
Expand All @@ -15,7 +15,7 @@ import (
// offering a git repository (opposite to the dumb http-protocol also possible)
//
// see https://git-scm.com/docs/git-http-backend
func gitHandler(path, uri string) http.Handler {
func GitHandler(path, uri string) http.Handler {

gitBinary, _ := exec.LookPath("git")
gitHandler := new(cgi.Handler)
Expand All @@ -37,11 +37,12 @@ func gitHandler(path, uri string) http.Handler {
// scan-path directive to "." which makes cgit scan the directory given via
// the uri. if the user places a "cgitrc" file into the .git folder of a
// scanned git-repo, the "repo.*" options are applied there. eg,
// knut.git/.git/cgitrc
// desc=knut - throws trees out of windows
//
// knut.git/.git/cgitrc
// desc=knut - throws trees out of windows
//
// will make that directory be listed with that description.
func cgitHandler(path, uri string) http.Handler {
func CgitHandler(path, uri string) http.Handler {
cgitBinary, _ := exec.LookPath("cgit")
cgitHandler := new(cgi.Handler)
cgitHandler.Dir = path
Expand Down
4 changes: 2 additions & 2 deletions cmd/knut/gzip.go → internal/pkg/knut/gzip.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2015 Mathias Gumz. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

package main
package knut

import (
"compress/gzip"
Expand All @@ -11,7 +11,7 @@ import (
"strconv"
)

func gzHandler(next http.Handler, clevel string) http.Handler {
func GzHandler(next http.Handler, clevel string) http.Handler {

level, err := atoiInRange(clevel, -1, gzip.BestCompression, gzip.DefaultCompression)
if err != nil {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2015 Mathias Gumz. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

package main
package knut

import (
"compress/flate"
Expand All @@ -12,7 +12,7 @@ import (

// compressHandler requests having Accept-Encoding 'deflate' or 'gzip'
// taken from https://github.com/gorilla/handlers/blob/master/compress.go
func compressHandler(handler http.Handler) http.Handler {
func CompressHandler(handler http.Handler) http.Handler {

gzPool := newGzPool(gzip.DefaultCompression)
flatePool := newFlatePool(flate.DefaultCompression)
Expand Down
20 changes: 10 additions & 10 deletions cmd/knut/handlers.go → internal/pkg/knut/handlers.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2015 Mathias Gumz. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

package main
package knut

import (
"bytes"
Expand All @@ -13,21 +13,21 @@ import (
)

// serveFileHandler serves the file given by 'name'
func serveFileHandler(name string) http.Handler {
func ServeFileHandler(name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, name)
})
}

// serveStringHandler writes given 'str' to the response
func serveStringHandler(str string) http.Handler {
func ServeStringHandler(str string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(str))
})
}

func redirectHandler(path, location string) http.Handler {
func RedirectHandler(path, location string) http.Handler {

type uriHostPort struct {
url.URL
Expand All @@ -51,10 +51,10 @@ func redirectHandler(path, location string) http.Handler {
})
}

func fileOrDirHandler(path, uri string) http.Handler {
func FileOrDirHandler(path, uri string) http.Handler {

if fi, err := os.Stat(path); err == nil && !fi.IsDir() {
return serveFileHandler(path)
return ServeFileHandler(path)
}

handler := http.FileServer(http.Dir(path))
Expand All @@ -64,15 +64,15 @@ func fileOrDirHandler(path, uri string) http.Handler {

// addServerIDHandler adds "Server: <serverID>" to the response
// header
func addServerIDHandler(next http.Handler, serverID string) http.Handler {
func AddServerIDHandler(next http.Handler, serverID string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", serverID)
next.ServeHTTP(w, r)
})
}

// noCacheHandler adds a 'nocaching, please' hint to the response header
func noCacheHandler(next http.Handler) http.Handler {
func NoCacheHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "private, max-age=0, no-cache")
next.ServeHTTP(w, r)
Expand All @@ -81,7 +81,7 @@ func noCacheHandler(next http.Handler) http.Handler {

// basicAuthHandler checks the submited username and password against predefined
// values.
func basicAuthHandler(next http.Handler, username, password string) http.Handler {
func BasicAuthHandler(next http.Handler, username, password string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="knut"`)
rUser, rPassword, ok := r.BasicAuth()
Expand All @@ -95,7 +95,7 @@ func basicAuthHandler(next http.Handler, username, password string) http.Handler

// setContentType sets the "Content-Type" to "contentType", if not already
// set
func setContentType(next http.Handler, contentType string) http.Handler {
func SetContentType(next http.Handler, contentType string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, exists := w.Header()["Content-Type"]; !exists {
w.Header().Set("Content-Type", contentType)
Expand Down
8 changes: 4 additions & 4 deletions cmd/knut/helper.go → internal/pkg/knut/helper.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2015 Mathias Gumz. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

package main
package knut

import (
"fmt"
Expand All @@ -21,7 +21,7 @@ var (
// of *knut* the first part is called "window" (it is the url-endpoint,
// essentially), the part after the first ':' is called "the tree", it's
// the content that will be delivered.
func getWindowAndTree(arg string) (window, tree string, err error) {
func GetWindowAndTree(arg string) (window, tree string, err error) {

// if the user just feeds in a list of (existing) filenames
// we assume the user just wants to expose the given filenames
Expand All @@ -44,7 +44,7 @@ func getWindowAndTree(arg string) (window, tree string, err error) {
return window, tree, nil
}

func localFilename(fileURL *url.URL) string {
func LocalFilename(fileURL *url.URL) string {
return filepath.Join(fileURL.Host, fileURL.Path)
}

Expand All @@ -55,7 +55,7 @@ func writeStatus(w http.ResponseWriter, code int) {
fmt.Fprintf(w, "%d: %s", code, http.StatusText(code))
}

func hasQueryParam(key string, vals url.Values) bool {
func HasQueryParam(key string, vals url.Values) bool {
_, exists := vals[key]
return exists
}
6 changes: 3 additions & 3 deletions cmd/knut/knut_test.go → internal/pkg/knut/knut_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2015 Mathias Gumz. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

package main
package knut

import (
"net/url"
Expand Down Expand Up @@ -48,7 +48,7 @@ func TestGetWindowAndTree(t *testing.T) {
}

for i, test := range tests {
win, tree, err := getWindowAndTree(test.in)
win, tree, err := GetWindowAndTree(test.in)
t.Logf("case %d: %q => %q,%q,%v", i, test.in, win, tree, err)
if win != test.window || tree != test.tree || err != test.err {
t.Errorf("case %d: %q,%q,%v (%q) does not match %v",
Expand All @@ -69,7 +69,7 @@ func TestLocalFilename(t *testing.T) {
if err != nil {
t.Errorf("case %d: parsing test.in %q: %v", i, test.in, err)
}
out := filepath.ToSlash(localFilename(u))
out := filepath.ToSlash(LocalFilename(u))
t.Logf("case %d: localFilename(%q): %q", i, u.String(), out)
if out != test.out {
t.Errorf("case %d: localFilename(%q): expected %q, got %q",
Expand Down
4 changes: 2 additions & 2 deletions cmd/knut/logging.go → internal/pkg/knut/logging.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2015 Mathias Gumz. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

package main
package knut

import (
"fmt"
Expand All @@ -13,7 +13,7 @@ import (

// logRequestHandler returns a handler which logs all requests to 'writer'. it also captures
// the status-code
func logRequestHandler(handler http.Handler, logWriter io.Writer) http.Handler {
func LogRequestHandler(handler http.Handler, logWriter io.Writer) http.Handler {

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var sc = statusCodeCapture{w: w}
Expand Down
Loading

0 comments on commit b9bedef

Please sign in to comment.