93 lines
2.4 KiB
Go
93 lines
2.4 KiB
Go
// 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/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")
|
|
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)
|
|
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,
|
|
}
|
|
|
|
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")
|
|
go func() {
|
|
<-ctx.Done()
|
|
stop()
|
|
ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
|
|
defer cancel()
|
|
s.Shutdown(ctx)
|
|
}()
|
|
s.ListenAndServe()
|
|
},
|
|
}
|
|
|
|
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", "well-known path, used by LetsEncrypt")
|
|
}
|