Пример #1
0
func JSONResponse(ctx *gin.Context, statusCode int, obj ...interface{}) {
	if len(obj) == 1 {
		if gin.Mode() == "debug" {
			ctx.IndentedJSON(statusCode, obj[0])
		} else {
			ctx.JSON(statusCode, obj[0])
		}
	} else {
		if gin.Mode() == "debug" {
			ctx.IndentedJSON(statusCode, obj)
		} else {
			ctx.JSON(statusCode, obj)
		}
	}
}
Пример #2
0
//setLogger initializes logrus logger with some defaults
func setLogger() {
	logrus.SetFormatter(&logrus.TextFormatter{})
	logrus.SetOutput(os.Stderr)
	if gin.Mode() == gin.DebugMode {
		logrus.SetLevel(logrus.InfoLevel)
	}
}
Пример #3
0
func (s *CabifyService) Run(cfg config.Config) error {

	cabifyResource := resources.CabifyResource{}

	log.Info("Starting Cabify Store service")

	cabifyResource.Cfg = cfg

	r := gin.Default()

	// Admin config route
	routes := r.Group("/store")
	{
		routes.POST("/totalprice", (&cabifyResource).OrderSum)
	}

	//GIN release mode, either debug, test or release (DebugMode, TestMode, ReleaseMode)
	//by default, runs in releasemode
	gin.SetMode(gin.DebugMode)
	log.Info("Cabify Store service run in", "mode", gin.Mode())

	r.Run(cfg.SvcHost)

	return nil
}
Пример #4
0
func main() {

	router := gin.Default()

	if gin.Mode() == gin.DebugMode {
		// For Dev Mode
		router.Static("/js", "frontend/app/js")
		router.Static("/css", "frontend/app/css")
		router.Static("/bower_components", "frontend/app/bower_components")
		router.LoadHTMLGlob("frontend/app/index.html")
	} else if gin.Mode() == gin.ReleaseMode {
		// For Prod Mode
		router.Use(static.Serve("/index", BinaryFileSystem("frontend/dist/index.html")))
		router.Use(static.Serve("/css", BinaryFileSystem("frontend/dist/css")))
		router.Use(static.Serve("/js", BinaryFileSystem("frontend/dist/js")))
	}

	// For SPA Router
	router.NoRoute(index)

	api := router.Group("/api")

	xhr := api.Group("/xhr")

	xhr.Group("/admin").
		GET("/host", hostInfo)

	sse := api.Group("/sse")
	sse.GET("/stream", stream)

	server := &http.Server{
		Addr:    ":8080",
		Handler: router,
		//Comment timeouts if you use SSE streams
		//ReadTimeout: 10 * time.Second,
		//WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	server.ListenAndServe()
}
Пример #5
0
func startHttpServer() {
	router := gin.New() // don't need to use Logger, if we use apache/nginx.
	router.Use(gin.Recovery())
	routes.Use(router)

	if gin.Mode() == gin.ReleaseMode {
		logger.Infof("GIN Listening and serving HTTP on %s", listenPort)
		endless.ListenAndServe(listenPort, router) // use endless for graceful restart/stop.
	} else {
		router.Run(listenPort)
	}
}
Пример #6
0
func index(ctx *gin.Context) {

	if gin.Mode() == gin.DebugMode {

		ctx.HTML(http.StatusOK, "index.html", gin.H{
			"title": "appName",
		})

	} else if gin.Mode() == gin.ReleaseMode {

		fmt.Println(buildstamp, mode)
		templateString, err := Asset("frontend/dist/index.html")
		if err != nil {
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}

		t, err := template.New("index").Parse(string(templateString))
		if err != nil {
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}

		var index bytes.Buffer
		err = t.Execute(&index, gin.H{
			"title": "appName",
		})

		if err != nil {
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}

		ctx.Data(http.StatusOK, "text/html; charset=utf-8", index.Bytes())

	}

}
Пример #7
0
//LoadConfig unmarshals config for current GIN_MODE
func LoadConfig(data []byte) {
	configs := &Configs{}
	err := json.Unmarshal(data, configs)
	if err != nil {
		panic(err)
	}
	switch gin.Mode() {
	case gin.DebugMode:
		config = &configs.Debug
	case gin.ReleaseMode:
		config = &configs.Release
	case gin.TestMode:
		config = &configs.Test
	default:
		panic(fmt.Sprintf("Unknown gin mode %s", gin.Mode()))
	}
	if !path.IsAbs(config.Public) {
		workingDir, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		config.Public = path.Join(workingDir, config.Public)
	}
}
Пример #8
0
func (this *RespondWith) Error(httpStatus int, err api.Error) {
	response := gin.H{
		"error_code": httpStatus,
	}

	if err.Any() {
		if err.IsUserError() {
			response["message"] = err.Text()

		} else if gin.Mode() != gin.ReleaseMode {
			response["debug_message"] = err.Text()
			delete(response, "message")
		}
	}

	this.GinContext.JSON(httpStatus, response)
}
Пример #9
0
// Instance should return a new Pongo2Render struct per request and prepare
// the template by either loading it from disk or using pongo2's cache.
func (p Pongo2Render) Instance(name string, data interface{}) render.Render {
	var template *pongo2.Template
	filename := path.Join(p.Options.TemplateDir, name)

	// always read template files from disk if in debug mode, use cache otherwise.
	if gin.Mode() == "debug" {
		template = pongo2.Must(pongo2.FromFile(filename))
	} else {
		template = pongo2.Must(pongo2.FromCache(filename))
	}

	return Pongo2Render{
		Template: template,
		Context:  data.(pongo2.Context),
		Options:  p.Options,
	}
}
Пример #10
0
// Prepares the application to use the AirbrakeService. The function will:
//
// 1. Add a recovery handler to gin
// 2. Replace app.OnException with a version that writes the airbrak in addition
//    to logging
// 3. Sets the Notifier object that will be used to push notices to Airbrake
func (s *AirbrakeService) Build(r *gin.Engine) error {
	if !s.Config.Enabled {
		log.Info("AirbrakeService is disabled")
		return nil
	}

	s.Notifier = gobrake.NewNotifier(s.Config.ProjectID, s.Config.ProjectKey)
	s.Notifier.SetHost(s.Config.Host)
	s.Notifier.AddFilter(func(notice *gobrake.Notice) *gobrake.Notice {
		notice.Context["environment"] = gin.Mode()
		return notice
	})

	r.Use(s.RecoveryMiddleware())

	return nil
}
Пример #11
0
func init() {
	flag.BoolVar(&InteractiveSetup, "setup", false, "perform interactive setup")
	flag.BoolVar(&Migration, "migrate", false, "execute migrations")
	flag.BoolVar(&Upgrade, "upgrade", false, "upgrade semaphore")
	path := flag.String("config", "", "config path")

	var pwd string
	flag.StringVar(&pwd, "hash", "", "generate hash of given password")

	var printConfig bool
	flag.BoolVar(&printConfig, "printConfig", false, "print example configuration")

	flag.Parse()

	if printConfig {
		cfg := &configType{
			MySQL: mySQLConfig{
				Hostname: "127.0.0.1:3306",
				Username: "******",
				DbName:   "semaphore",
			},
			Port:    ":3000",
			TmpPath: "/tmp/semaphore",
		}
		cfg.GenerateCookieSecrets()

		b, _ := json.MarshalIndent(cfg, "", "\t")
		fmt.Println(string(b))

		os.Exit(0)
	}

	if len(pwd) > 0 {
		password, _ := bcrypt.GenerateFromPassword([]byte(pwd), 11)
		fmt.Println("Generated password: "******"Could not decode configuration!")
			panic(err)
		}
	} else {
		configFile, err := Asset("config.json")
		if err != nil {
			fmt.Println("Cannot Find configuration! Use -c parameter to point to a JSON file generated by -setup.\n\n Hint: have you run `-setup` ?")
			os.Exit(1)
		}

		if err := json.Unmarshal(configFile, &Config); err != nil {
			fmt.Println("Could not decode configuration!")
			panic(err)
		}
	}

	if len(os.Getenv("PORT")) > 0 {
		Config.Port = ":" + os.Getenv("PORT")
	}
	if len(Config.Port) == 0 {
		Config.Port = ":3000"
	}

	if len(Config.TmpPath) == 0 {
		Config.TmpPath = "/tmp/semaphore"
	}

	var encryption []byte
	encryption = nil

	hash, _ := base64.StdEncoding.DecodeString(Config.CookieHash)
	if len(Config.CookieEncryption) > 0 {
		encryption, _ = base64.StdEncoding.DecodeString(Config.CookieEncryption)
	}

	Cookie = securecookie.New(hash, encryption)

	stage := ""
	if gin.Mode() == "release" {
		stage = "production"
	} else {
		stage = "development"
	}
	bugsnag.Configure(bugsnag.Configuration{
		APIKey:              Config.BugsnagKey,
		ReleaseStage:        stage,
		NotifyReleaseStages: []string{"production"},
		AppVersion:          Version,
		ProjectPackages:     []string{"github.com/ansible-semaphore/semaphore/**"},
	})
}
Пример #12
0
func TryMe() string {
	return gin.Mode()
}