Skip to content

Instantly share code, notes, and snippets.

@dwburke
Last active September 2, 2018 15:39
Show Gist options
  • Save dwburke/e4bbbc8beb8c1316802f340e9068ab18 to your computer and use it in GitHub Desktop.
Save dwburke/e4bbbc8beb8c1316802f340e9068ab18 to your computer and use it in GitHub Desktop.
golang cobra command to generate self-signed cert for dev use
package api
import (
"github.com/gin-gonic/gin"
endpoint_player "github.com/dwburke/addict-service/api/player"
)
func SetupRoutes(r *gin.Engine) {
endpoint_player.SetupRoutes(r)
}
package cmd
import (
"fmt"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/dwburke/addict-service/api"
)
func init() {
rootCmd.AddCommand(apiCmd)
apiCmd.Flags().Int("port", 4444, "Port to run server on")
viper.BindPFlag("api.port", apiCmd.Flags().Lookup("port"))
apiCmd.Flags().String("ssl-key", "key.pem", "SSL certificate key")
viper.BindPFlag("api.ssl-key", apiCmd.Flags().Lookup("ssl-key"))
apiCmd.Flags().String("ssl-cert", "cert.pem", "SSL certificate")
viper.BindPFlag("api.ssl-cert", apiCmd.Flags().Lookup("ssl-cert"))
apiCmd.Flags().Bool("https", false, "Use HTTPS")
viper.BindPFlag("api.https", apiCmd.Flags().Lookup("https"))
}
var apiCmd = &cobra.Command{
Use: "api",
Short: "Start the REST api",
Long: `Start the REST api`,
Run: func(cmd *cobra.Command, args []string) {
r := gin.Default()
r.Use(cors.Default())
api.SetupRoutes(r)
listen := fmt.Sprintf(":%d", viper.GetInt("api.port"))
if viper.GetBool("api.https") == true {
r.RunTLS(listen, viper.GetString("api.ssl-cert"), viper.GetString("api.ssl-key"))
} else {
r.Run(listen)
}
},
}
package cmd
import (
"fmt"
"log"
"github.com/kabukky/httpscerts"
"github.com/spf13/cobra"
)
func init() {
rootCmd.AddCommand(generateCertCmd)
}
var generateCertCmd = &cobra.Command{
Use: "generatecert",
Short: "Generate self-signed certificate",
Run: func(cmd *cobra.Command, args []string) {
err := httpscerts.Check("cert.pem", "key.pem")
// If they are not available, generate new ones.
if err != nil {
err = httpscerts.Generate("cert.pem", "key.pem", "127.0.0.1:8081")
if err != nil {
log.Fatal("Error: Couldn't create https certs.")
}
} else {
fmt.Println("Cert already exists.")
}
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment