|
|
package httpserver
|
|
|
|
|
|
import (
|
|
|
"b612.me/starlog"
|
|
|
"b612.me/staros"
|
|
|
"context"
|
|
|
"github.com/spf13/cobra"
|
|
|
"os"
|
|
|
"os/signal"
|
|
|
"strings"
|
|
|
)
|
|
|
|
|
|
var s HttpServer
|
|
|
|
|
|
var daemon bool
|
|
|
|
|
|
func init() {
|
|
|
Cmd.Flags().StringVarP(&s.port, "port", "p", "80", "监听端口")
|
|
|
Cmd.Flags().StringVarP(&s.addr, "ip", "i", "0.0.0.0", "监听ip")
|
|
|
Cmd.Flags().StringVarP(&s.envPath, "folder", "f", "./", "本地文件地址")
|
|
|
Cmd.Flags().StringVarP(&s.uploadFolder, "upload", "u", "", "文件上传文件夹路径")
|
|
|
Cmd.Flags().BoolVarP(&daemon, "daemon", "d", false, "以后台进程运行")
|
|
|
Cmd.Flags().StringVarP(&s.basicAuthUser, "auth", "a", "", "HTTP BASIC AUTH认证(用户名:密码)")
|
|
|
Cmd.Flags().StringVarP(&s.indexFile, "index", "n", "", "Index文件名,如index.html")
|
|
|
Cmd.Flags().StringVarP(&s.logpath, "log", "l", "", "log地址")
|
|
|
Cmd.Flags().StringVarP(&s.cert, "ssl-cert", "c", "", "TLS证书路径")
|
|
|
Cmd.Flags().StringVarP(&s.key, "ssl-key", "k", "", "TLS密钥路径")
|
|
|
Cmd.Flags().BoolVarP(&s.disableMIME, "disablemime", "m", false, "停止解析MIME,全部按下载文件处理")
|
|
|
Cmd.Flags().StringSliceVarP(&s.protectAuthPage, "protect-page", "P", []string{}, "Basic Auth 开启白名单")
|
|
|
Cmd.Flags().Bool("daeapplied", false, "")
|
|
|
Cmd.Flags().MarkHidden("daeapplied")
|
|
|
}
|
|
|
|
|
|
var Cmd = &cobra.Command{
|
|
|
Use: "http",
|
|
|
Short: "HTTP文件服务器(HTTP File Browser Server)",
|
|
|
Long: `HTTP文件服务器(HTTP File Browser Server)`,
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
apply, _ := cmd.Flags().GetBool("daeapplied")
|
|
|
if daemon && !apply {
|
|
|
nArgs := append(os.Args[1:], "--daeapplied")
|
|
|
pid, err := staros.Daemon(os.Args[0], nArgs...)
|
|
|
if err != nil {
|
|
|
starlog.Criticalln("Daemon Error:", err)
|
|
|
os.Exit(1)
|
|
|
}
|
|
|
starlog.StdPrintf([]starlog.Attr{starlog.FgGreen}, "Success,PID=%v\n", pid)
|
|
|
return
|
|
|
}
|
|
|
sig := make(chan os.Signal)
|
|
|
signal.Notify(sig, os.Kill, os.Interrupt)
|
|
|
ctx, fn := context.WithCancel(context.Background())
|
|
|
go func() {
|
|
|
starlog.Infoln("Recv Signal", <-sig)
|
|
|
fn()
|
|
|
}()
|
|
|
if s.basicAuthUser != "" {
|
|
|
tmp := strings.SplitN(s.basicAuthUser, ":", 2)
|
|
|
if len(tmp) != 2 {
|
|
|
starlog.Errorln("basic Auth should have user and password")
|
|
|
os.Exit(2)
|
|
|
}
|
|
|
s.basicAuthUser = strings.TrimSpace(tmp[0])
|
|
|
s.basicAuthPwd = tmp[1]
|
|
|
}
|
|
|
err := s.Run(ctx)
|
|
|
if err != nil {
|
|
|
starlog.Errorln("Http Server Closed by Errors", err)
|
|
|
os.Exit(1)
|
|
|
}
|
|
|
starlog.Infoln("Http Server Closed Normally")
|
|
|
},
|
|
|
}
|