Restructure project similar to hello and graph
This commit is contained in:
@@ -1,15 +0,0 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// init defined the default options for viper.
|
||||
func init() {
|
||||
viper.SetDefault("debug.addr", "0.0.0.0:8190")
|
||||
viper.SetDefault("debug.token", "")
|
||||
viper.SetDefault("debug.pprof", false)
|
||||
|
||||
viper.SetDefault("http.addr", "0.0.0.0:8180")
|
||||
viper.SetDefault("http.root", "/")
|
||||
}
|
||||
+19
-24
@@ -3,52 +3,47 @@ package command
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"github.com/micro/cli"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
"github.com/owncloud/ocis-webdav/pkg/flagset"
|
||||
)
|
||||
|
||||
// Health is the entrypoint for the health command.
|
||||
func Health() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "health",
|
||||
Short: "Check health status",
|
||||
Long: "",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
func Health(cfg *config.Config) cli.Command {
|
||||
return cli.Command{
|
||||
Name: "health",
|
||||
Usage: "Check health status",
|
||||
Flags: flagset.HealthWithConfig(cfg),
|
||||
Action: func(c *cli.Context) error {
|
||||
logger := NewLogger(cfg)
|
||||
|
||||
resp, err := http.Get(
|
||||
fmt.Sprintf(
|
||||
"http://%s/healthz",
|
||||
viper.GetString("debug.addr"),
|
||||
cfg.Debug.Addr,
|
||||
),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Error().
|
||||
logger.Fatal().
|
||||
Err(err).
|
||||
Msg("Failed to request health check")
|
||||
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Error().
|
||||
logger.Fatal().
|
||||
Int("code", resp.StatusCode).
|
||||
Msg("Health seems to be in bad state")
|
||||
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
os.Exit(0)
|
||||
logger.Debug().
|
||||
Int("code", resp.StatusCode).
|
||||
Msg("Health got a good state")
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().String("debug-addr", "", "Address to debug endpoint")
|
||||
viper.BindPFlag("debug.addr", cmd.Flags().Lookup("debug-addr"))
|
||||
viper.BindEnv("debug.addr", "WEBDAV_DEBUG_ADDR")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
+84
-85
@@ -4,101 +4,100 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/micro/cli"
|
||||
"github.com/owncloud/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
"github.com/owncloud/ocis-webdav/pkg/flagset"
|
||||
"github.com/owncloud/ocis-webdav/pkg/version"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// Root is the entry point for the ocis-webdav command.
|
||||
func Root() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "ocis-webdav",
|
||||
Short: "Reva service for webdav",
|
||||
Long: ``,
|
||||
Version: version.String,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
setupLogger()
|
||||
setupConfig()
|
||||
// Execute is the entry point for the ocis-webdav command.
|
||||
func Execute() error {
|
||||
cfg := config.New()
|
||||
|
||||
app := &cli.App{
|
||||
Name: "ocis-webdav",
|
||||
Version: version.String,
|
||||
Usage: "Serve WebDAV API for oCIS",
|
||||
Compiled: version.Compiled(),
|
||||
|
||||
Authors: []cli.Author{
|
||||
{
|
||||
Name: "ownCloud GmbH",
|
||||
Email: "support@owncloud.com",
|
||||
},
|
||||
},
|
||||
|
||||
Flags: flagset.RootWithConfig(cfg),
|
||||
|
||||
Before: func(c *cli.Context) error {
|
||||
logger := NewLogger(cfg)
|
||||
|
||||
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
viper.SetEnvPrefix("WEBDAV")
|
||||
viper.AutomaticEnv()
|
||||
|
||||
if c.IsSet("config-file") {
|
||||
viper.SetConfigFile(c.String("config-file"))
|
||||
} else {
|
||||
viper.SetConfigName("webdav")
|
||||
|
||||
viper.AddConfigPath("/etc/ocis")
|
||||
viper.AddConfigPath("$HOME/.ocis")
|
||||
viper.AddConfigPath("./config")
|
||||
}
|
||||
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
switch err.(type) {
|
||||
case viper.ConfigFileNotFoundError:
|
||||
logger.Info().
|
||||
Msg("Continue without config")
|
||||
case viper.UnsupportedConfigError:
|
||||
logger.Fatal().
|
||||
Err(err).
|
||||
Msg("Unsupported config type")
|
||||
default:
|
||||
logger.Fatal().
|
||||
Err(err).
|
||||
Msg("Failed to read config")
|
||||
}
|
||||
}
|
||||
|
||||
if err := viper.Unmarshal(&cfg); err != nil {
|
||||
logger.Fatal().
|
||||
Err(err).
|
||||
Msg("Failed to parse config")
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
|
||||
Commands: []cli.Command{
|
||||
Server(cfg),
|
||||
Health(cfg),
|
||||
},
|
||||
}
|
||||
|
||||
cmd.PersistentFlags().String("log-level", "", "Set logging level")
|
||||
viper.BindPFlag("log.level", cmd.PersistentFlags().Lookup("log-level"))
|
||||
viper.SetDefault("log.level", "info")
|
||||
viper.BindEnv("log.level", "WEBDAV_LOG_LEVEL")
|
||||
|
||||
cmd.PersistentFlags().Bool("log-pretty", false, "Enable pretty logging")
|
||||
viper.BindPFlag("log.pretty", cmd.PersistentFlags().Lookup("log-pretty"))
|
||||
viper.SetDefault("log.pretty", true)
|
||||
viper.BindEnv("log.pretty", "WEBDAV_LOG_PRETTY")
|
||||
|
||||
cmd.PersistentFlags().Bool("log-color", false, "Enable colored logging")
|
||||
viper.BindPFlag("log.color", cmd.PersistentFlags().Lookup("log-color"))
|
||||
viper.SetDefault("log.color", true)
|
||||
viper.BindEnv("log.color", "WEBDAV_LOG_COLOR")
|
||||
|
||||
cmd.AddCommand(Server())
|
||||
cmd.AddCommand(Health())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// setupLogger prepares the logger.
|
||||
func setupLogger() {
|
||||
switch strings.ToLower(viper.GetString("log.level")) {
|
||||
case "panic":
|
||||
zerolog.SetGlobalLevel(zerolog.PanicLevel)
|
||||
case "fatal":
|
||||
zerolog.SetGlobalLevel(zerolog.FatalLevel)
|
||||
case "error":
|
||||
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
|
||||
case "warn":
|
||||
zerolog.SetGlobalLevel(zerolog.WarnLevel)
|
||||
case "info":
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
case "debug":
|
||||
zerolog.SetGlobalLevel(zerolog.DebugLevel)
|
||||
default:
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
cli.HelpFlag = &cli.BoolFlag{
|
||||
Name: "help,h",
|
||||
Usage: "Show the help",
|
||||
}
|
||||
|
||||
if viper.GetBool("log.pretty") {
|
||||
log.Logger = log.Output(
|
||||
zerolog.ConsoleWriter{
|
||||
Out: os.Stderr,
|
||||
NoColor: !viper.GetBool("log.color"),
|
||||
},
|
||||
)
|
||||
cli.VersionFlag = &cli.BoolFlag{
|
||||
Name: "version,v",
|
||||
Usage: "Print the version",
|
||||
}
|
||||
|
||||
return app.Run(os.Args)
|
||||
}
|
||||
|
||||
// setupConfig prepares the config.
|
||||
func setupConfig() {
|
||||
viper.SetConfigName("webdav")
|
||||
|
||||
viper.AddConfigPath("/etc/ocis")
|
||||
viper.AddConfigPath("$HOME/.ocis")
|
||||
viper.AddConfigPath("./config")
|
||||
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
switch err.(type) {
|
||||
case viper.ConfigFileNotFoundError:
|
||||
log.Debug().
|
||||
Msg("Continue without config")
|
||||
case viper.UnsupportedConfigError:
|
||||
log.Fatal().
|
||||
Msg("Unsupported config type")
|
||||
default:
|
||||
if e := log.Debug(); e.Enabled() {
|
||||
log.Fatal().
|
||||
Err(err).
|
||||
Msg("Failed to read config")
|
||||
} else {
|
||||
log.Fatal().
|
||||
Msg("Failed to read config")
|
||||
}
|
||||
}
|
||||
}
|
||||
// NewLogger initializes a service-specific logger instance.
|
||||
func NewLogger(cfg *config.Config) log.Logger {
|
||||
return log.NewLogger(
|
||||
log.Name("webdav"),
|
||||
log.Level(cfg.Log.Level),
|
||||
log.Pretty(cfg.Log.Pretty),
|
||||
log.Color(cfg.Log.Color),
|
||||
)
|
||||
}
|
||||
|
||||
+157
-185
@@ -2,196 +2,189 @@ package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"contrib.go.opencensus.io/exporter/jaeger"
|
||||
"contrib.go.opencensus.io/exporter/ocagent"
|
||||
"contrib.go.opencensus.io/exporter/zipkin"
|
||||
"github.com/micro/cli"
|
||||
"github.com/oklog/run"
|
||||
"github.com/owncloud/ocis-webdav/pkg/router/debug"
|
||||
"github.com/owncloud/ocis-webdav/pkg/router/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
openzipkin "github.com/openzipkin/zipkin-go"
|
||||
zipkinhttp "github.com/openzipkin/zipkin-go/reporter/http"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
"github.com/owncloud/ocis-webdav/pkg/flagset"
|
||||
"github.com/owncloud/ocis-webdav/pkg/metrics"
|
||||
"github.com/owncloud/ocis-webdav/pkg/server/debug"
|
||||
"github.com/owncloud/ocis-webdav/pkg/server/http"
|
||||
"go.opencensus.io/stats/view"
|
||||
"go.opencensus.io/trace"
|
||||
)
|
||||
|
||||
// Server is the entrypoint for the server command.
|
||||
func Server() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "server",
|
||||
Short: "Start integrated server",
|
||||
Long: "",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
var gr run.Group
|
||||
func Server(cfg *config.Config) cli.Command {
|
||||
return cli.Command{
|
||||
Name: "server",
|
||||
Usage: "Start integrated server",
|
||||
Flags: flagset.ServerWithConfig(cfg),
|
||||
Action: func(c *cli.Context) error {
|
||||
logger := NewLogger(cfg)
|
||||
|
||||
if cfg.Tracing.Enabled {
|
||||
switch t := cfg.Tracing.Type; t {
|
||||
case "agent":
|
||||
exporter, err := ocagent.NewExporter(
|
||||
ocagent.WithReconnectionPeriod(5*time.Second),
|
||||
ocagent.WithAddress(cfg.Tracing.Endpoint),
|
||||
ocagent.WithServiceName(cfg.Tracing.Service),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logger.Error().
|
||||
Err(err).
|
||||
Str("endpoint", cfg.Tracing.Endpoint).
|
||||
Str("collector", cfg.Tracing.Collector).
|
||||
Msg("Failed to create agent tracing")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
trace.RegisterExporter(exporter)
|
||||
view.RegisterExporter(exporter)
|
||||
|
||||
case "jaeger":
|
||||
exporter, err := jaeger.NewExporter(
|
||||
jaeger.Options{
|
||||
AgentEndpoint: cfg.Tracing.Endpoint,
|
||||
CollectorEndpoint: cfg.Tracing.Collector,
|
||||
ServiceName: cfg.Tracing.Service,
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logger.Error().
|
||||
Err(err).
|
||||
Str("endpoint", cfg.Tracing.Endpoint).
|
||||
Str("collector", cfg.Tracing.Collector).
|
||||
Msg("Failed to create jaeger tracing")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
trace.RegisterExporter(exporter)
|
||||
|
||||
case "zipkin":
|
||||
endpoint, err := openzipkin.NewEndpoint(
|
||||
cfg.Tracing.Service,
|
||||
cfg.Tracing.Endpoint,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logger.Error().
|
||||
Err(err).
|
||||
Str("endpoint", cfg.Tracing.Endpoint).
|
||||
Str("collector", cfg.Tracing.Collector).
|
||||
Msg("Failed to create zipkin tracing")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
exporter := zipkin.NewExporter(
|
||||
zipkinhttp.NewReporter(
|
||||
cfg.Tracing.Collector,
|
||||
),
|
||||
endpoint,
|
||||
)
|
||||
|
||||
trace.RegisterExporter(exporter)
|
||||
|
||||
default:
|
||||
logger.Warn().
|
||||
Str("type", t).
|
||||
Msg("Unknown tracing backend")
|
||||
}
|
||||
|
||||
trace.ApplyConfig(
|
||||
trace.Config{
|
||||
DefaultSampler: trace.AlwaysSample(),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
logger.Debug().
|
||||
Msg("Tracing is not enabled")
|
||||
}
|
||||
|
||||
var (
|
||||
gr = run.Group{}
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
metrics = metrics.New()
|
||||
)
|
||||
|
||||
defer cancel()
|
||||
|
||||
{
|
||||
server := &http.Server{
|
||||
Addr: viper.GetString("debug.addr"),
|
||||
Handler: debug.Router(
|
||||
debug.WithToken(viper.GetString("debug.token")),
|
||||
debug.WithPprof(viper.GetBool("debug.pprof")),
|
||||
),
|
||||
ReadTimeout: 5 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
server, err := http.Server(
|
||||
http.Logger(logger),
|
||||
http.Context(ctx),
|
||||
http.Config(cfg),
|
||||
http.Metrics(metrics),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logger.Info().
|
||||
Err(err).
|
||||
Str("transport", "http").
|
||||
Msg("Failed to initialize server")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
gr.Add(func() error {
|
||||
log.Info().
|
||||
Str("addr", viper.GetString("debug.addr")).
|
||||
Msg("Starting debug server")
|
||||
return server.Run()
|
||||
}, func(_ error) {
|
||||
logger.Info().
|
||||
Str("transport", "http").
|
||||
Msg("Shutting down server")
|
||||
|
||||
if strings.HasPrefix(viper.GetString("debug.addr"), "unix://") {
|
||||
socket := strings.TrimPrefix(viper.GetString("debug.addr"), "unix://")
|
||||
|
||||
if err := os.Remove(socket); err != nil && !os.IsNotExist(err) {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("socket", socket).
|
||||
Msg("Failed to remove existing debug socket")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
listener, err := net.ListenUnix(
|
||||
"unix",
|
||||
&net.UnixAddr{
|
||||
Name: socket,
|
||||
Net: "unix",
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Msg("Failed to initialize debug unix socket")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if err = os.Chmod(socket, os.FileMode(0666)); err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Msg("Failed to change debug socket permissions")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Serve(listener)
|
||||
}
|
||||
|
||||
return server.ListenAndServe()
|
||||
}, func(reason error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := server.Shutdown(ctx); err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Msg("Failed to shutdown debug server gracefully")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if strings.HasPrefix(viper.GetString("debug.addr"), "unix://") {
|
||||
socket := strings.TrimPrefix(viper.GetString("debug.addr"), "unix://")
|
||||
|
||||
if err := os.Remove(socket); err != nil && !os.IsNotExist(err) {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("socket", socket).
|
||||
Msg("Failed to remove debug server socket")
|
||||
}
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Err(reason).
|
||||
Msg("Shutdown debug server gracefully")
|
||||
cancel()
|
||||
})
|
||||
}
|
||||
|
||||
{
|
||||
server := &http.Server{
|
||||
Addr: viper.GetString("http.addr"),
|
||||
Handler: server.Router(
|
||||
server.WithRoot(viper.GetString("http.root")),
|
||||
),
|
||||
ReadTimeout: 5 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
server, err := debug.Server(
|
||||
debug.Logger(logger),
|
||||
debug.Context(ctx),
|
||||
debug.Config(cfg),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logger.Info().
|
||||
Err(err).
|
||||
Str("transport", "debug").
|
||||
Msg("Failed to initialize server")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
gr.Add(func() error {
|
||||
log.Info().
|
||||
Str("addr", viper.GetString("http.addr")).
|
||||
Msg("Starting http server")
|
||||
|
||||
if strings.HasPrefix(viper.GetString("http.addr"), "unix://") {
|
||||
socket := strings.TrimPrefix(viper.GetString("http.addr"), "unix://")
|
||||
|
||||
if err := os.Remove(socket); err != nil && !os.IsNotExist(err) {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("socket", socket).
|
||||
Msg("Failed to remove existing http socket")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
listener, err := net.ListenUnix(
|
||||
"unix",
|
||||
&net.UnixAddr{
|
||||
Name: socket,
|
||||
Net: "unix",
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Msg("Failed to initialize http unix socket")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if err = os.Chmod(socket, os.FileMode(0666)); err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Msg("Failed to change http socket permissions")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Serve(listener)
|
||||
}
|
||||
|
||||
return server.ListenAndServe()
|
||||
}, func(reason error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
}, func(_ error) {
|
||||
ctx, timeout := context.WithTimeout(ctx, 5*time.Second)
|
||||
|
||||
defer timeout()
|
||||
defer cancel()
|
||||
|
||||
if err := server.Shutdown(ctx); err != nil {
|
||||
log.Error().
|
||||
logger.Info().
|
||||
Err(err).
|
||||
Msg("Failed to shutdown http server gracefully")
|
||||
|
||||
return
|
||||
Str("transport", "debug").
|
||||
Msg("Failed to shutdown server")
|
||||
} else {
|
||||
logger.Info().
|
||||
Str("transport", "debug").
|
||||
Msg("Shutting down server")
|
||||
}
|
||||
|
||||
if strings.HasPrefix(viper.GetString("http.addr"), "unix://") {
|
||||
socket := strings.TrimPrefix(viper.GetString("http.addr"), "unix://")
|
||||
|
||||
if err := os.Remove(socket); err != nil && !os.IsNotExist(err) {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("socket", socket).
|
||||
Msg("Failed to remove http server socket")
|
||||
}
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Err(reason).
|
||||
Msg("Shutdown http server gracefully")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -206,32 +199,11 @@ func Server() *cobra.Command {
|
||||
return nil
|
||||
}, func(err error) {
|
||||
close(stop)
|
||||
cancel()
|
||||
})
|
||||
}
|
||||
|
||||
return gr.Run()
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().String("debug-addr", "", "Address to bind debug server")
|
||||
viper.BindPFlag("debug.addr", cmd.Flags().Lookup("debug-addr"))
|
||||
viper.BindEnv("debug.addr", "WEBDAV_DEBUG_ADDR")
|
||||
|
||||
cmd.Flags().String("debug-token", "", "Token to grant metrics access")
|
||||
viper.BindPFlag("debug.token", cmd.Flags().Lookup("debug-token"))
|
||||
viper.BindEnv("debug.token", "WEBDAV_DEBUG_TOKEN")
|
||||
|
||||
cmd.Flags().Bool("debug-pprof", false, "Enable pprof debugging")
|
||||
viper.BindPFlag("debug.pprof", cmd.Flags().Lookup("debug-pprof"))
|
||||
viper.BindEnv("debug.pprof", "WEBDAV_DEBUG_PPROF")
|
||||
|
||||
cmd.Flags().String("http-addr", "", "Address to bind http server")
|
||||
viper.BindPFlag("http.addr", cmd.Flags().Lookup("http-addr"))
|
||||
viper.BindEnv("http.addr", "WEBDAV_HTTP_ADDR")
|
||||
|
||||
cmd.Flags().String("http-root", "", "Root path for http endpoint")
|
||||
viper.BindPFlag("http.root", cmd.Flags().Lookup("http-root"))
|
||||
viper.BindEnv("http.root", "WEBDAV_HTTP_ROOT")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package config
|
||||
|
||||
// Log defines the available logging configuration.
|
||||
type Log struct {
|
||||
Level string
|
||||
Pretty bool
|
||||
Color bool
|
||||
}
|
||||
|
||||
// Debug defines the available debug configuration.
|
||||
type Debug struct {
|
||||
Addr string
|
||||
Token string
|
||||
Pprof bool
|
||||
Zpages bool
|
||||
}
|
||||
|
||||
// HTTP defines the available http configuration.
|
||||
type HTTP struct {
|
||||
Addr string
|
||||
}
|
||||
|
||||
// Tracing defines the available tracing configuration.
|
||||
type Tracing struct {
|
||||
Enabled bool
|
||||
Type string
|
||||
Endpoint string
|
||||
Collector string
|
||||
Service string
|
||||
}
|
||||
|
||||
// Config combines all available configuration parts.
|
||||
type Config struct {
|
||||
File string
|
||||
Log Log
|
||||
Debug Debug
|
||||
HTTP HTTP
|
||||
Tracing Tracing
|
||||
}
|
||||
|
||||
// New initializes a new configuration with or without defaults.
|
||||
func New() *Config {
|
||||
return &Config{}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package flagset
|
||||
|
||||
import (
|
||||
"github.com/micro/cli"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
)
|
||||
|
||||
// RootWithConfig applies cfg to the root flagset
|
||||
func RootWithConfig(cfg *config.Config) []cli.Flag {
|
||||
return []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "config-file",
|
||||
Value: "",
|
||||
Usage: "Path to config file",
|
||||
EnvVar: "WEBDAV_CONFIG_FILE",
|
||||
Destination: &cfg.File,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "log-level",
|
||||
Value: "info",
|
||||
Usage: "Set logging level",
|
||||
EnvVar: "WEBDAV_LOG_LEVEL",
|
||||
Destination: &cfg.Log.Level,
|
||||
},
|
||||
&cli.BoolTFlag{
|
||||
Name: "log-pretty",
|
||||
Usage: "Enable pretty logging",
|
||||
EnvVar: "WEBDAV_LOG_PRETTY",
|
||||
Destination: &cfg.Log.Pretty,
|
||||
},
|
||||
&cli.BoolTFlag{
|
||||
Name: "log-color",
|
||||
Usage: "Enable colored logging",
|
||||
EnvVar: "WEBDAV_LOG_COLOR",
|
||||
Destination: &cfg.Log.Color,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// HealthWithConfig applies cfg to the root flagset
|
||||
func HealthWithConfig(cfg *config.Config) []cli.Flag {
|
||||
return []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "debug-addr",
|
||||
Value: "0.0.0.0:9119",
|
||||
Usage: "Address to debug endpoint",
|
||||
EnvVar: "WEBDAV_DEBUG_ADDR",
|
||||
Destination: &cfg.Debug.Addr,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ServerWithConfig applies cfg to the root flagset
|
||||
func ServerWithConfig(cfg *config.Config) []cli.Flag {
|
||||
return []cli.Flag{
|
||||
&cli.BoolFlag{
|
||||
Name: "tracing-enabled",
|
||||
Usage: "Enable sending traces",
|
||||
EnvVar: "WEBDAV_TRACING_ENABLED",
|
||||
Destination: &cfg.Tracing.Enabled,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "tracing-type",
|
||||
Value: "jaeger",
|
||||
Usage: "Tracing backend type",
|
||||
EnvVar: "WEBDAV_TRACING_TYPE",
|
||||
Destination: &cfg.Tracing.Type,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "tracing-endpoint",
|
||||
Value: "",
|
||||
Usage: "Endpoint for the agent",
|
||||
EnvVar: "WEBDAV_TRACING_ENDPOINT",
|
||||
Destination: &cfg.Tracing.Endpoint,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "tracing-collector",
|
||||
Value: "",
|
||||
Usage: "Endpoint for the collector",
|
||||
EnvVar: "WEBDAV_TRACING_COLLECTOR",
|
||||
Destination: &cfg.Tracing.Collector,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "tracing-service",
|
||||
Value: "webdav",
|
||||
Usage: "Service name for tracing",
|
||||
EnvVar: "WEBDAV_TRACING_SERVICE",
|
||||
Destination: &cfg.Tracing.Service,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "debug-addr",
|
||||
Value: "0.0.0.0:9119",
|
||||
Usage: "Address to bind debug server",
|
||||
EnvVar: "WEBDAV_DEBUG_ADDR",
|
||||
Destination: &cfg.Debug.Addr,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "debug-token",
|
||||
Value: "",
|
||||
Usage: "Token to grant metrics access",
|
||||
EnvVar: "WEBDAV_DEBUG_TOKEN",
|
||||
Destination: &cfg.Debug.Token,
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "debug-pprof",
|
||||
Usage: "Enable pprof debugging",
|
||||
EnvVar: "WEBDAV_DEBUG_PPROF",
|
||||
Destination: &cfg.Debug.Pprof,
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "debug-zpages",
|
||||
Usage: "Enable zpages debugging",
|
||||
EnvVar: "WEBDAV_DEBUG_ZPAGES",
|
||||
Destination: &cfg.Debug.Zpages,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "http-addr",
|
||||
Value: "0.0.0.0:9115",
|
||||
Usage: "Address to bind http server",
|
||||
EnvVar: "WEBDAV_HTTP_ADDR",
|
||||
Destination: &cfg.HTTP.Addr,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidToken is returned when the request token is invalid.
|
||||
ErrInvalidToken = `Invalid or missing token`
|
||||
)
|
||||
|
||||
// metrics gets initialized by New and provides the handler.
|
||||
type metrics struct {
|
||||
token string
|
||||
}
|
||||
|
||||
// ServeHTTP just implements the http.Handler interface.
|
||||
func (m metrics) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if m.token == "" {
|
||||
promhttp.Handler().ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
header := r.Header.Get("Authorization")
|
||||
|
||||
if header == "" {
|
||||
log.Debug().
|
||||
Msg("Missing auth header")
|
||||
|
||||
http.Error(w, ErrInvalidToken, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if header != fmt.Sprintf("Bearer %s", m.token) {
|
||||
log.Debug().
|
||||
Msg("Invalid token provided")
|
||||
|
||||
http.Error(w, ErrInvalidToken, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
promhttp.Handler().ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Handler returns the handler for metrics endpoint.
|
||||
func Handler(opts ...Option) http.Handler {
|
||||
m := new(metrics)
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(m)
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package metrics
|
||||
|
||||
// Option configures an assets option.
|
||||
type Option func(*metrics)
|
||||
|
||||
// WithToken returns an option to set a token.
|
||||
func WithToken(val string) Option {
|
||||
return func(m *metrics) {
|
||||
m.token = val
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package metrics
|
||||
|
||||
var (
|
||||
// Namespace defines the namespace for the defines metrics.
|
||||
Namespace = "ocis"
|
||||
|
||||
// Subsystem defines the subsystem for the defines metrics.
|
||||
Subsystem = "webdav"
|
||||
)
|
||||
|
||||
// Metrics defines the available metrics of this service.
|
||||
type Metrics struct {
|
||||
// Counter *prometheus.CounterVec
|
||||
}
|
||||
|
||||
// New initializes the available metrics.
|
||||
func New() *Metrics {
|
||||
m := &Metrics{
|
||||
// Counter: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
// Namespace: Namespace,
|
||||
// Subsystem: Subsystem,
|
||||
// Name: "greet_total",
|
||||
// Help: "How many greeting requests processed",
|
||||
// }, []string{}),
|
||||
}
|
||||
|
||||
// prometheus.Register(
|
||||
// m.Counter,
|
||||
// )
|
||||
|
||||
return m
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package header
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/ocis-webdav/pkg/version"
|
||||
)
|
||||
|
||||
// Cache writes required cache headers to all requests.
|
||||
func Cache(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
|
||||
w.Header().Set("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Options writes required option headers to all requests.
|
||||
func Options(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "OPTIONS" {
|
||||
next.ServeHTTP(w, r)
|
||||
} else {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
|
||||
w.Header().Set("Allow", "HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Secure writes required access headers to all requests.
|
||||
func Secure(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("X-XSS-Protection", "1; mode=block")
|
||||
|
||||
if r.TLS != nil {
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=31536000")
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Version writes the current version to the headers.
|
||||
func Version(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-WEBDAV-VERSION", version.String)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package debug
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"github.com/owncloud/ocis-webdav/pkg/handler/metrics"
|
||||
"github.com/owncloud/ocis-webdav/pkg/middleware/header"
|
||||
"github.com/rs/zerolog/hlog"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// debug gets initialized by Router and configures the router.
|
||||
type debug struct {
|
||||
token string
|
||||
pprof bool
|
||||
}
|
||||
|
||||
// Router initializes a router for the debug server.
|
||||
func Router(opts ...Option) *chi.Mux {
|
||||
d := new(debug)
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(d)
|
||||
}
|
||||
|
||||
mux := chi.NewRouter()
|
||||
|
||||
mux.Use(hlog.NewHandler(log.Logger))
|
||||
mux.Use(hlog.RemoteAddrHandler("ip"))
|
||||
mux.Use(hlog.URLHandler("path"))
|
||||
mux.Use(hlog.MethodHandler("method"))
|
||||
mux.Use(hlog.RequestIDHandler("request_id", "Request-Id"))
|
||||
|
||||
mux.Use(middleware.RealIP)
|
||||
mux.Use(header.Version)
|
||||
mux.Use(header.Cache)
|
||||
mux.Use(header.Secure)
|
||||
mux.Use(header.Options)
|
||||
|
||||
mux.Route("/", func(root chi.Router) {
|
||||
if d.pprof {
|
||||
root.Mount(
|
||||
"/debug",
|
||||
middleware.Profiler(),
|
||||
)
|
||||
}
|
||||
|
||||
root.Mount(
|
||||
"/metrics",
|
||||
metrics.Handler(
|
||||
metrics.WithToken(d.token),
|
||||
),
|
||||
)
|
||||
|
||||
root.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
io.WriteString(w, http.StatusText(http.StatusOK))
|
||||
})
|
||||
|
||||
root.Get("/readyz", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
io.WriteString(w, http.StatusText(http.StatusOK))
|
||||
})
|
||||
})
|
||||
|
||||
return mux
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package debug
|
||||
|
||||
// Option configures an assets option.
|
||||
type Option func(*debug)
|
||||
|
||||
// WithToken returns an option to set a token.
|
||||
func WithToken(val string) Option {
|
||||
return func(d *debug) {
|
||||
d.token = val
|
||||
}
|
||||
}
|
||||
|
||||
// WithPprof returns an option to enable pprof.
|
||||
func WithPprof(val bool) Option {
|
||||
return func(d *debug) {
|
||||
d.pprof = val
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package server
|
||||
|
||||
// Option configures an assets option.
|
||||
type Option func(*server)
|
||||
|
||||
// WithRoot returns an option to set root.
|
||||
func WithRoot(val string) Option {
|
||||
return func(s *server) {
|
||||
s.root = val
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"github.com/owncloud/ocis-webdav/pkg/middleware/header"
|
||||
"github.com/rs/zerolog/hlog"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// server gets initialized by Router and configures the router.
|
||||
type server struct {
|
||||
root string
|
||||
}
|
||||
|
||||
// Router initializes a router for the http server.
|
||||
func Router(opts ...Option) *chi.Mux {
|
||||
s := new(server)
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(s)
|
||||
}
|
||||
|
||||
mux := chi.NewRouter()
|
||||
|
||||
mux.Use(hlog.NewHandler(log.Logger))
|
||||
mux.Use(hlog.RemoteAddrHandler("ip"))
|
||||
mux.Use(hlog.URLHandler("path"))
|
||||
mux.Use(hlog.MethodHandler("method"))
|
||||
mux.Use(hlog.RequestIDHandler("request_id", "Request-Id"))
|
||||
|
||||
mux.Use(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
|
||||
hlog.FromRequest(r).Debug().
|
||||
Str("method", r.Method).
|
||||
Str("url", r.URL.String()).
|
||||
Int("status", status).
|
||||
Int("size", size).
|
||||
Dur("duration", duration).
|
||||
Msg("")
|
||||
}))
|
||||
|
||||
mux.Use(middleware.RealIP)
|
||||
mux.Use(header.Version)
|
||||
mux.Use(header.Cache)
|
||||
mux.Use(header.Secure)
|
||||
mux.Use(header.Options)
|
||||
|
||||
mux.Route(s.root, func(root chi.Router) {
|
||||
root.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
|
||||
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||
})
|
||||
})
|
||||
|
||||
return mux
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package debug
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/owncloud/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
)
|
||||
|
||||
// Option defines a single option function.
|
||||
type Option func(o *Options)
|
||||
|
||||
// Options defines the available options for this package.
|
||||
type Options struct {
|
||||
Logger log.Logger
|
||||
Context context.Context
|
||||
Config *config.Config
|
||||
}
|
||||
|
||||
// newOptions initializes the available default options.
|
||||
func newOptions(opts ...Option) Options {
|
||||
opt := Options{}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&opt)
|
||||
}
|
||||
|
||||
return opt
|
||||
}
|
||||
|
||||
// Logger provides a function to set the logger option.
|
||||
func Logger(val log.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = val
|
||||
}
|
||||
}
|
||||
|
||||
// Context provides a function to set the context option.
|
||||
func Context(val context.Context) Option {
|
||||
return func(o *Options) {
|
||||
o.Context = val
|
||||
}
|
||||
}
|
||||
|
||||
// Config provides a function to set the config option.
|
||||
func Config(val *config.Config) Option {
|
||||
return func(o *Options) {
|
||||
o.Config = val
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package debug
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/owncloud/ocis-pkg/service/debug"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
"github.com/owncloud/ocis-webdav/pkg/version"
|
||||
)
|
||||
|
||||
// Server initializes the debug service and server.
|
||||
func Server(opts ...Option) (*http.Server, error) {
|
||||
options := newOptions(opts...)
|
||||
|
||||
return debug.NewService(
|
||||
debug.Logger(options.Logger),
|
||||
debug.Name("webdav"),
|
||||
debug.Version(version.String),
|
||||
debug.Address(options.Config.Debug.Addr),
|
||||
debug.Token(options.Config.Debug.Token),
|
||||
debug.Pprof(options.Config.Debug.Pprof),
|
||||
debug.Zpages(options.Config.Debug.Zpages),
|
||||
debug.Health(health(options.Config)),
|
||||
debug.Ready(ready(options.Config)),
|
||||
), nil
|
||||
}
|
||||
|
||||
// health implements the health check.
|
||||
func health(cfg *config.Config) func(http.ResponseWriter, *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
// TODO(tboerger): check if services are up and running
|
||||
|
||||
io.WriteString(w, http.StatusText(http.StatusOK))
|
||||
}
|
||||
}
|
||||
|
||||
// ready implements the ready check.
|
||||
func ready(cfg *config.Config) func(http.ResponseWriter, *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
// TODO(tboerger): check if services are up and running
|
||||
|
||||
io.WriteString(w, http.StatusText(http.StatusOK))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/owncloud/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
"github.com/owncloud/ocis-webdav/pkg/metrics"
|
||||
)
|
||||
|
||||
// Option defines a single option function.
|
||||
type Option func(o *Options)
|
||||
|
||||
// Options defines the available options for this package.
|
||||
type Options struct {
|
||||
Logger log.Logger
|
||||
Context context.Context
|
||||
Config *config.Config
|
||||
Metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
// newOptions initializes the available default options.
|
||||
func newOptions(opts ...Option) Options {
|
||||
opt := Options{}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&opt)
|
||||
}
|
||||
|
||||
return opt
|
||||
}
|
||||
|
||||
// Logger provides a function to set the logger option.
|
||||
func Logger(val log.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = val
|
||||
}
|
||||
}
|
||||
|
||||
// Context provides a function to set the context option.
|
||||
func Context(val context.Context) Option {
|
||||
return func(o *Options) {
|
||||
o.Context = val
|
||||
}
|
||||
}
|
||||
|
||||
// Config provides a function to set the config option.
|
||||
func Config(val *config.Config) Option {
|
||||
return func(o *Options) {
|
||||
o.Config = val
|
||||
}
|
||||
}
|
||||
|
||||
// Metrics provides a function to set the metrics option.
|
||||
func Metrics(val *metrics.Metrics) Option {
|
||||
return func(o *Options) {
|
||||
o.Metrics = val
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"github.com/owncloud/ocis-pkg/middleware"
|
||||
"github.com/owncloud/ocis-pkg/service/http"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
"github.com/owncloud/ocis-webdav/pkg/flagset"
|
||||
"github.com/owncloud/ocis-webdav/pkg/service/v0"
|
||||
"github.com/owncloud/ocis-webdav/pkg/version"
|
||||
)
|
||||
|
||||
// Server initializes the http service and server.
|
||||
func Server(opts ...Option) (http.Service, error) {
|
||||
options := newOptions(opts...)
|
||||
|
||||
service := http.NewService(
|
||||
http.Logger(options.Logger),
|
||||
http.Namespace("go.micro.web"),
|
||||
http.Name("webdav"),
|
||||
http.Version(version.String),
|
||||
http.Address(options.Config.HTTP.Addr),
|
||||
http.Context(options.Context),
|
||||
http.Flags(flagset.RootWithConfig(config.New())...),
|
||||
http.Flags(flagset.ServerWithConfig(config.New())...),
|
||||
)
|
||||
|
||||
handle := svc.NewService(
|
||||
svc.Logger(options.Logger),
|
||||
svc.Config(options.Config),
|
||||
svc.Middleware(
|
||||
middleware.RealIP,
|
||||
middleware.RequestID,
|
||||
middleware.Cache,
|
||||
middleware.Cors,
|
||||
middleware.Secure,
|
||||
middleware.Version(
|
||||
"webdav",
|
||||
version.String,
|
||||
),
|
||||
middleware.Logger(
|
||||
options.Logger,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
{
|
||||
handle = svc.NewInstrument(handle, options.Metrics)
|
||||
handle = svc.NewLogging(handle, options.Logger)
|
||||
handle = svc.NewTracing(handle)
|
||||
}
|
||||
|
||||
service.Handle(
|
||||
"/",
|
||||
handle,
|
||||
)
|
||||
|
||||
service.Init()
|
||||
return service, nil
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/owncloud/ocis-webdav/pkg/metrics"
|
||||
)
|
||||
|
||||
// NewInstrument returns a service that instruments metrics.
|
||||
func NewInstrument(next Service, metrics *metrics.Metrics) Service {
|
||||
return instrument{
|
||||
next: next,
|
||||
metrics: metrics,
|
||||
}
|
||||
}
|
||||
|
||||
type instrument struct {
|
||||
next Service
|
||||
metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
// ServeHTTP implements the Service interface.
|
||||
func (i instrument) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
i.next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Dummy implements the Service interface.
|
||||
func (i instrument) Dummy(w http.ResponseWriter, r *http.Request) {
|
||||
i.next.Dummy(w, r)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/owncloud/ocis-pkg/log"
|
||||
)
|
||||
|
||||
// NewLogging returns a service that logs messages.
|
||||
func NewLogging(next Service, logger log.Logger) Service {
|
||||
return logging{
|
||||
next: next,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
type logging struct {
|
||||
next Service
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
// ServeHTTP implements the Service interface.
|
||||
func (l logging) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
l.next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Dummy implements the Service interface.
|
||||
func (l logging) Dummy(w http.ResponseWriter, r *http.Request) {
|
||||
l.next.Dummy(w, r)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/owncloud/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
)
|
||||
|
||||
// Option defines a single option function.
|
||||
type Option func(o *Options)
|
||||
|
||||
// Options defines the available options for this package.
|
||||
type Options struct {
|
||||
Logger log.Logger
|
||||
Config *config.Config
|
||||
Middleware []func(http.Handler) http.Handler
|
||||
}
|
||||
|
||||
// newOptions initializes the available default options.
|
||||
func newOptions(opts ...Option) Options {
|
||||
opt := Options{}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&opt)
|
||||
}
|
||||
|
||||
return opt
|
||||
}
|
||||
|
||||
// Logger provides a function to set the logger option.
|
||||
func Logger(val log.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = val
|
||||
}
|
||||
}
|
||||
|
||||
// Config provides a function to set the config option.
|
||||
func Config(val *config.Config) Option {
|
||||
return func(o *Options) {
|
||||
o.Config = val
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware provides a function to set the middleware option.
|
||||
func Middleware(val ...func(http.Handler) http.Handler) Option {
|
||||
return func(o *Options) {
|
||||
o.Middleware = val
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/owncloud/ocis-webdav/pkg/config"
|
||||
)
|
||||
|
||||
// Service defines the extension handlers.
|
||||
type Service interface {
|
||||
ServeHTTP(http.ResponseWriter, *http.Request)
|
||||
Dummy(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
// NewService returns a service implementation for Service.
|
||||
func NewService(opts ...Option) Service {
|
||||
options := newOptions(opts...)
|
||||
|
||||
m := chi.NewMux()
|
||||
m.Use(options.Middleware...)
|
||||
|
||||
svc := Webdav{
|
||||
config: options.Config,
|
||||
mux: m,
|
||||
}
|
||||
|
||||
m.HandleFunc("/", svc.Dummy)
|
||||
|
||||
return svc
|
||||
}
|
||||
|
||||
// Webdav defines implements the business logic for Service.
|
||||
type Webdav struct {
|
||||
config *config.Config
|
||||
mux *chi.Mux
|
||||
}
|
||||
|
||||
// ServeHTTP implements the Service interface.
|
||||
func (g Webdav) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
g.mux.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Dummy implements the Service interface.
|
||||
func (g Webdav) Dummy(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// NewTracing returns a service that instruments traces.
|
||||
func NewTracing(next Service) Service {
|
||||
return tracing{
|
||||
next: next,
|
||||
}
|
||||
}
|
||||
|
||||
type tracing struct {
|
||||
next Service
|
||||
}
|
||||
|
||||
// ServeHTTP implements the Service interface.
|
||||
func (t tracing) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
t.next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Dummy implements the Service interface.
|
||||
func (t tracing) Dummy(w http.ResponseWriter, r *http.Request) {
|
||||
t.next.Dummy(w, r)
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// String gets defined by the build system.
|
||||
String = "0.0.0"
|
||||
@@ -7,3 +11,9 @@ var (
|
||||
// Date indicates the build date.
|
||||
Date = "00000000"
|
||||
)
|
||||
|
||||
// Compiled returns the compile time of this service.
|
||||
func Compiled() time.Time {
|
||||
t, _ := time.Parse("20060102", Date)
|
||||
return t
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user