Random URL generation(Close #17)

This commit is contained in:
Shoji Ihara 2015-08-19 20:35:04 +09:00
parent 2aaa155a3e
commit b15227c696
2 changed files with 35 additions and 11 deletions

View file

@ -1,11 +1,14 @@
package app
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"log"
"math/big"
"net/http"
"os/exec"
"strconv"
"strings"
"syscall"
"unsafe"
@ -20,16 +23,18 @@ type App struct {
Address string
Port string
PermitWrite bool
RandomUrl bool
Credential string
Command []string
}
func New(address string, port string, permitWrite bool, cred string, command []string) *App {
func New(address string, port string, permitWrite bool, cred string, randomUrl bool, command []string) *App {
return &App{
Address: address,
Port: port,
PermitWrite: permitWrite,
Credential: cred,
RandomUrl: randomUrl,
Command: command,
}
}
@ -65,21 +70,24 @@ func basicAuthHandler(h http.Handler, cred string) http.Handler {
}
func (app *App) Run() error {
http.Handle("/",
http.FileServer(
&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "bindata"},
),
)
http.HandleFunc("/ws", app.generateHandler())
path := "/"
if app.RandomUrl {
randomPath := generateRandomString(8)
path = "/" + randomPath + "/"
}
url := app.Address + ":" + app.Port
log.Printf("Server is running at %s, command: %s", url, strings.Join(app.Command, " "))
fs := http.StripPrefix(path, http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "bindata"}))
http.Handle(path, fs)
http.HandleFunc(path+"ws", app.generateHandler())
endpoint := app.Address + ":" + app.Port
log.Printf("Server is running at %s, command: %s", endpoint+path, strings.Join(app.Command, " "))
handler := http.Handler(http.DefaultServeMux)
handler = loggerHandler(handler)
if app.Credential != "" {
handler = basicAuthHandler(handler, app.Credential)
}
err := http.ListenAndServe(url, handler)
err := http.ListenAndServe(endpoint, handler)
if err != nil {
return err
}
@ -227,3 +235,14 @@ type command struct {
Name string `json:"name"`
Arguments map[string]interface{} `json:"arguments"`
}
func generateRandomString(length int) string {
const base = 36
size := big.NewInt(base)
n := make([]byte, length)
for i, _ := range n {
c, _ := rand.Int(rand.Reader, size)
n[i] = strconv.FormatInt(c.Int64(), base)[0]
}
return string(n)
}