main.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "os"
  7. "github.com/spf13/cobra"
  8. "github.com/spf13/pflag"
  9. )
  10. type Opts struct {
  11. Port uint16
  12. KeyFile string
  13. CertFile string
  14. }
  15. func handler(writer http.ResponseWriter, request *http.Request) {
  16. res := "pong.my"
  17. writer.Header().Set("Content-Type", "text/plain")
  18. writer.WriteHeader(http.StatusOK)
  19. _, _ = writer.Write([]byte(res))
  20. }
  21. func runServer(opts *Opts) error {
  22. mainMux := http.NewServeMux()
  23. mainMux.Handle("/ping", http.HandlerFunc(handler))
  24. server := &http.Server{
  25. Addr: fmt.Sprintf("localhost:%d", opts.Port),
  26. Handler: mainMux,
  27. ErrorLog: log.New(os.Stdout, "", log.LstdFlags),
  28. }
  29. return server.ListenAndServeTLS(opts.CertFile, opts.KeyFile)
  30. }
  31. func markFlagRequired(flags *pflag.FlagSet, names ...string) {
  32. for _, n := range names {
  33. name := n
  34. if err := cobra.MarkFlagRequired(flags, name); err != nil {
  35. panic(err)
  36. }
  37. }
  38. }
  39. func main() {
  40. opts := Opts{}
  41. cmd := cobra.Command{
  42. RunE: func(cmd *cobra.Command, args []string) error {
  43. return runServer(&opts)
  44. },
  45. }
  46. flags := cmd.Flags()
  47. flags.Uint16Var(&opts.Port, "port", 0, "")
  48. flags.StringVar(&opts.KeyFile, "keyfile", "", "path to key file")
  49. flags.StringVar(&opts.CertFile, "certfile", "", "path to cert file")
  50. markFlagRequired(flags, "port", "keyfile", "certfile")
  51. if err := cmd.Execute(); err != nil {
  52. _, _ = fmt.Fprintf(os.Stderr, "Exit with err: %s", err)
  53. os.Exit(1)
  54. }
  55. }