// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. package cmd import ( "context" "fmt" "net/url" "os" "os/signal" "syscall" "time" "git.ronmi.tw/ronmi/forgejo-pages/lib" "github.com/raohwork/task" "github.com/raohwork/task/httptask" "github.com/spf13/cobra" "github.com/spf13/viper" ) // serveCmd represents the serve command var serveCmd = &cobra.Command{ Use: "serve", Short: "Start the static page server.", Long: `Start the static page server. Serve mode will start a HTTP server to serve static pages. It just forward requests to Forgejo server. This is useful when there is not much viewers, or you have other cache/protection layer like Cloudflare in front of the server. `, Run: func(cmd *cobra.Command, args []string) { viper.BindPFlags(cmd.Flags()) // check flags bind := viper.GetString("bind") server := viper.GetString("server") token := viper.GetString("token") branch := viper.GetString("branch") notFound := viper.GetString("notfound") files := viper.GetString("files") if bind == "" || server == "" || token == "" || branch == "" { fmt.Println("bind, server token and branch are required") fmt.Println("dumping flags:") fmt.Println(" bind: ", bind) fmt.Println(" server: ", server) fmt.Println(" token: ", token) fmt.Println(" branch: ", branch) fmt.Println(" notfound: ", notFound) fmt.Println(" files: ", files) return } serverUrl, err := url.Parse(server) if err != nil { fmt.Println("invalid server url: ", err) return } f := &lib.Forgejo{ Server: *serverUrl, Token: token, Branch: branch, NotFound: notFound, Files: files, } s, err := lib.UseAPI(bind, viper.GetString("well-known"), f) if err != nil { fmt.Println("cannot create server: ", err) return } ctx, stop := signal.NotifyContext( context.TODO(), os.Interrupt, syscall.SIGTERM, os.Kill, ) defer stop() fmt.Println("starting server") httptask.Server(s, task.Timeout(10*time.Second)).Run(ctx) }, } func init() { rootCmd.AddCommand(serveCmd) f := serveCmd.Flags() f.StringP("bind", "a", ":8080", "bind address") f.StringP("server", "s", "", "Forgejo server address") f.StringP("token", "k", "", "Forgejo api token") f.StringP("branch", "b", "static-pages", "branch to use") f.StringP("well-known", "w", "", "well-known path, used by LetsEncrypt") f.StringP("notfound", "n", "", "path to custom 404.html file") f.StringP("files", "f", "", "path for files to be served ") }