Skip to content
This repository has been archived by the owner on Mar 23, 2020. It is now read-only.

Commit

Permalink
WIP: feature #1
Browse files Browse the repository at this point in the history
  • Loading branch information
m2nlight committed Dec 29, 2019
1 parent 87191d9 commit ea6e248
Showing 1 changed file with 97 additions and 38 deletions.
135 changes: 97 additions & 38 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (

const (
// Version information
Version = "SimpleHttpServer v1.2-beta.1"
Version = "SimpleHttpServer v1.3-beta.1"
// HTTPProxy returns HTTP_PROXY
HTTPProxy = "HTTP_PROXY"
// HTTPSProxy returns HTTPS_PROXY
Expand All @@ -29,46 +29,50 @@ const (
)

var (
version = flag.Bool("version", false, "Output version only")
addr = flag.String("addr", "", "TCP address to listen. e.g.:0.0.0.0:8080")
addrTLS = flag.String("addrtls", "", "TCP address to listen to TLS (aka SSL or HTTPS) requests. Leave empty for disabling TLS")
certFile = flag.String("certfile", "", "Path to TLS certificate file")
keyFile = flag.String("keyfile", "", "Path to TLS key file")
compress = flag.String("compress", "", "Whether to enable transparent response compression. e.g.: true")
username = flag.String("username", "", "Username for basic authentication")
password = flag.String("password", "", "Password for basic authentication")
path = flag.String("path", "", "Local path to map to webroot. e.g.: ./")
indexNames = flag.String("indexnames", "", "List of index file names. e.g.: index.html,index.htm")
configFile = flag.String("config", "", "The config file path.")
verbose = flag.String("verbose", "", "Print verbose log. e.g.: false")
logFile = flag.String("logfile", "", "Output to logfile")
fallback = flag.String("fallback", "", "Fallback to some file. e.g.: If you serve a angular project, you can set it ./index.html")
enableColor = flag.String("enablecolor", "", "Enable color output by http status code. e.g.: false")
makeconfig = flag.String("makeconfig", "", "Make a config file. e.g.: config.yaml")
config = &Config{}
fsMap = make(map[string]fasthttp.RequestHandler)
enableBasicAuth = false
logMutex sync.Mutex
version = flag.Bool("version", false, "Output version only")
addr = flag.String("addr", "", "TCP address to listen. e.g.:0.0.0.0:8080")
addrTLS = flag.String("addrtls", "", "TCP address to listen to TLS (aka SSL or HTTPS) requests. Leave empty for disabling TLS")
certFile = flag.String("certfile", "", "Path to TLS certificate file")
keyFile = flag.String("keyfile", "", "Path to TLS key file")
compress = flag.String("compress", "", "Whether to enable transparent response compression. e.g.: true")
username = flag.String("username", "", "Username for basic authentication")
password = flag.String("password", "", "Password for basic authentication")
path = flag.String("path", "", "Local path to map to webroot. e.g.: ./")
indexNames = flag.String("indexnames", "", "List of index file names. e.g.: index.html,index.htm")
configFile = flag.String("config", "", "The config file path.")
verbose = flag.String("verbose", "", "Print verbose log. e.g.: false")
logFile = flag.String("logfile", "", "Output to logfile")
fallback = flag.String("fallback", "", "Fallback to some file. e.g.: If you serve a angular project, you can set it ./index.html")
enableColor = flag.String("enablecolor", "", "Enable color output by http status code. e.g.: false")
enableUpload = flag.String("enableupload", "", "Enable upload files")
maxRequestBodySize = flag.Int("maxrequestbodysize", 4*1024*1024*1024, "Max request body size for upload big file")
makeconfig = flag.String("makeconfig", "", "Make a config file. e.g.: config.yaml")
config = &Config{}
fsMap = make(map[string]fasthttp.RequestHandler)
enableBasicAuth = false
logMutex sync.Mutex
)

// Config from config.yaml
type Config struct {
Addr string
AddrTLS string
CertFile string
KeyFile string
Username string
Password string
Compress bool
Paths map[string]string
IndexNames []string
Verbose bool
LogFile string
Fallback string
EnableColor bool
HTTPProxy string `yaml:"HTTP_PROXY,omitempty"`
HTTPSProxy string `yaml:"HTTPS_PROXY,omitempty"`
NoProxy string `yaml:"NO_PROXY,omitempty"`
Addr string
AddrTLS string
CertFile string
KeyFile string
Username string
Password string
Compress bool
Paths map[string]string
IndexNames []string
Verbose bool
LogFile string
Fallback string
EnableColor bool
EnableUpload bool
MaxRequestBodySize int
HTTPProxy string `yaml:"HTTP_PROXY,omitempty"`
HTTPSProxy string `yaml:"HTTPS_PROXY,omitempty"`
NoProxy string `yaml:"NO_PROXY,omitempty"`
}

func main() {
Expand Down Expand Up @@ -173,6 +177,17 @@ func main() {
default:
log.Fatalf("error: %v", fmt.Errorf("argument enablecolor error"))
}
switch strings.ToLower(*enableUpload) {
case "":
fallthrough
case "true":
config.EnableUpload = true
case "false":
config.EnableUpload = false
default:
log.Fatalf("error: %v", fmt.Errorf("argument enableupload error"))
}
config.MaxRequestBodySize = *maxRequestBodySize
// config proxy
if len(config.HTTPProxy) > 0 {
_ = os.Setenv(HTTPProxy, config.HTTPProxy)
Expand Down Expand Up @@ -220,6 +235,8 @@ func main() {
log.Println("Fallback:", config.Fallback)
}
log.Println("EnableColor:", config.EnableColor)
log.Println("EnableUpload:", config.EnableUpload)
log.Println("MaxRequestBodySize", config.MaxRequestBodySize)
indexNamesLen := len(config.IndexNames)
if indexNamesLen > 0 {
log.Printf("Have %d index name(s):\n", indexNamesLen)
Expand All @@ -245,10 +262,16 @@ func main() {
}
}

// s := &fasthttp.Server{
// Handler: requestHandler,
// Name: Version,
// MaxRequestBodySize: config.MaxRequestBodySize,
// }

fs := &fasthttp.FS{
Root: v,
IndexNames: config.IndexNames,
GenerateIndexPages: true,
GenerateIndexPages: false,
AcceptByteRange: true,
}
if len(config.Fallback) > 0 {
Expand Down Expand Up @@ -346,6 +369,41 @@ func fsHandler(ctx *fasthttp.RequestCtx) {
return
}

// if path is a directory
dir, err := os.Stat(path)
if err != nil {
fmt.Fprintln(ctx, err)
} else if dir.IsDir() {
for _, v := range config.IndexNames {
indexfile := filepath.Join(path, v)
if fi, err := os.Stat(indexfile); err != nil {
if !fi.IsDir() {
ctx.SendFile(indexfile)
return
}
}
}

dirname := dir.Name()
fmt.Fprintf(ctx, "<html><head><title>%s</title></head><body><h1>%s</h1>", dirname, dirname)
err = filepath.Walk(filepath.Join(path, dirname), func(subpath string, f os.FileInfo, err error) error {
if err != nil {
return err
}
filename := f.Name()
if f.IsDir() {
fmt.Fprintf(ctx, "<a href=\"%s\"><b>%s</b></a>, dir, %s, last modified %s<br/>", path+"/"+filename, filename, f.Mode().String(), f.ModTime())
} else {
fmt.Fprintf(ctx, "<a href=\"%s\">%s</a>, file, %s, %d bytes, last modified %s<br/>", path+"/"+filename, filename, f.Mode().String(), f.Size(), f.ModTime())
}
return nil
})

fmt.Fprintf(ctx, "</body></html>")
ctx.SetContentType("text/html; charset=utf8")
return
}

for k, handler := range fsMap {
if strings.HasPrefix(path, k) {
handler(ctx)
Expand Down Expand Up @@ -483,6 +541,7 @@ indexnames:
- index.htm
verbose: true
enablecolor: true
enableupload: true
#logfile: ./simplehttpserver.log
#fallback: ./index.html
#HTTP_PROXY:
Expand Down

0 comments on commit ea6e248

Please sign in to comment.