Ejemplo n.º 1
0
Archivo: main.go Proyecto: woodygoal/cm
func run() {
	logFile, logErr := os.OpenFile(*logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if logErr != nil {
		fmt.Println("Fail to find", *logFile, "cServer start Failed")
		os.Exit(1)
	}
	log.SetOutput(logFile)
	log.Printf("CM Server Start")
	CACHE = NewCache(PATH + "cache")
	defer CACHE.Close()
	CACHE.All()
	gin.SetMode(gin.ReleaseMode)
	//g := gin.Default()
	g := gin.New()
	g.Use(gin.Recovery())
	g.Use(gin.LoggerWithWriter(logFile))
	g.Use(gzip.Gzip(gzip.DefaultCompression))
	g.POST("/cm/settings", postSettings)
	g.GET("/cm/settings", getSettings)
	g.GET("/cm/menus", func(c *gin.Context) {
		c.JSON(http.StatusOK, CACHE.menus)
	})
	g.NoRoute(func(c *gin.Context) {
		c.String(http.StatusNotFound, "404")
	})
	g.Run(":8011")
}
Ejemplo n.º 2
0
func NewRouter() *gin.Engine {

	gin.SetMode(gin.ReleaseMode)

	router := gin.Default()
	router.RedirectTrailingSlash = true
	router.RedirectFixedPath = true

	router.Use(gzip.Gzip(gzip.DefaultCompression))
	router.Use(middleware.ContentTypeCheckerMiddleware())
	router.Use(middleware.RequestIdMiddleware())
	router.Use(middleware.RevisionMiddleware())

	router.Use(cors.Middleware(cors.Config{
		Origins:         "*",
		Methods:         "GET, PUT, POST, DELETE, PATCH, OPTIONS",
		RequestHeaders:  "Origin, Authorization, Content-Type",
		ExposedHeaders:  "",
		MaxAge:          1728000,
		Credentials:     true,
		ValidateHeaders: false,
	}))

	return router
}
Ejemplo n.º 3
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	role := config.mustGetString("postgres", "role")
	database := config.mustGetString("postgres", "database")
	ip := config.mustGetString("postgres", "ip")
	password := config.mustGetString("postgres", "password")
	services.InitDBConnection(role, password, database, ip)

	api_key := config.mustGetString("parsemap", "api_key")
	r := gin.New()
	r.Use(gzip.Gzip(gzip.DefaultCompression))
	r.Use(gin.Logger())
	r.Use(gin.Recovery())
	r.Use(gin.ErrorLogger())

	v2 := r.Group("/v2")
	services.GetHandlersV2(v2, api_key)

	var wg sync.WaitGroup
	wg.Add(2)
	go startServer(r, &wg)
	go startTLSServer(r, &wg)
	wg.Wait()
}
Ejemplo n.º 4
0
func main() {
	r := gin.Default()
	r.Use(gzip.Gzip(gzip.DefaultCompression))
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
	})

	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}
Ejemplo n.º 5
0
// Run runs the setup server which is used to configure the application on the
// first run or when the -i/--initial option is used.
func Run() {
	gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.Use(gin.Recovery())
	r.Use(gzip.Gzip(gzip.DefaultCompression))
	r.LoadHTMLGlob("templates/*")
	r.Static("/static", "./assets")
	r.Static("/favicon.ico", "./assets/favicon.ico")
	r.GET("/", index)
	r.POST("/", configure)
	fmt.Println("Please go to http://127.0.0.1:8008 to setup goploader.")
	r.Run(":8008")
}
Ejemplo n.º 6
0
func main() {
	r := gin.Default()
	r.Use(gzip.Gzip(gzip.DefaultCompression))
	r.GET("/bson", func(c *gin.Context) {
		//data, err := bson.Marshal(&Image{Name: "people_top_hair_000"})
		data, err := bson.Marshal(gin.H{"name": "people_top_hair_000", "path": "assect/images/hair"})
		if err != nil {
			panic(err)
		}
		c.Data(http.StatusOK, "application/bson", data)
	})

	r.GET("/json", func(c *gin.Context) {
		c.JSON(http.StatusOK, &Image{Name: "people_top_hair_000"})
	})

	r.Static("/html", "./html")
	r.Run(":8080") // listen and serve on 0.0.0.0:8080
}
Ejemplo n.º 7
0
func main() {
	r := gin.Default()
	r.Use(gzip.Gzip(gzip.DefaultCompression))

	// Group using gin.BasicAuth() middleware
	authorized := r.Group("/")

	if len(config.Accounts) > 0 {
		authorized.Use(gin.BasicAuth(config.Accounts))
	}
	for _, f := range config.StaticFS {
		authorized.StaticFS("/"+f, http.Dir(f))
	}

	authorized.GET(config.HomeUrl, func(c *gin.Context) {
		c.JSON(http.StatusOK, "home!")
	})

	r.Run(config.ListenAddress)
}
Ejemplo n.º 8
0
func main() {
	flag.Parse()

	session, err := mgo.Dial(*uri)
	if err != nil {
		log.Fatal(err)
	}

	service := namesearch.New(namesearch.Session(session))

	router := gin.Default()

	router.Use(gzip.Gzip(gzip.DefaultCompression))
	router.Use(static.Serve("/", static.LocalFile("static", true)))

	router.GET("/v1/namesearch/", service.NameSearch)
	router.GET("/v1/namesearch/:query", service.NameSearch)

	router.Run(*listen)
}
Ejemplo n.º 9
0
func Init(db *bolt.DB, _port ...string) {
	DB = db

	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()
	router.Use(gzip.Gzip(gzip.DefaultCompression))
	router.GET("/", bucketList)
	router.GET("/rest/:bucket/:action", restGetHandler)
	router.POST("/rest", restPostHandler)
	router.GET("/bucket/:name/*nested", bucketContent)

	port := "3333"
	if len(_port) > 0 && _port[0] != "" {
		port = _port[0]
	}
	err := http.ListenAndServe(":"+port, router)
	if err != nil {
		panic(err)
	}
}
Ejemplo n.º 10
0
func main() {
	flag.Parse()

	// Pass variables to packages
	model.SessionLength = *SESSION_LENGTH
	model.DbUser = *DB_USER
	model.DbPass = *DB_PASS
	model.DbName = *DB_NAME
	model.DbHost = *DB_HOST

	log.Print("Initializing database backend")
	model.DbMap = model.InitDb()

	log.Print("Initializing session backend")
	common.ActiveSession = &common.SessionConnector{
		Address:    *REDIS_HOST,
		Password:   *REDIS_PASSWORD,
		DatabaseId: int64(*REDIS_DBID),
	}
	err := common.ActiveSession.Connect()
	if err != nil {
		panic(err)
	}

	log.Print("Initializing web services")
	m := gin.New()
	m.Use(gin.Logger())
	m.Use(gin.Recovery())

	// Enable gzip compression
	m.Use(gzip.Gzip(gzip.DefaultCompression))

	// Serve up the static UI...
	m.Static("/ui", "./ui")
	m.StaticFile("/favicon.ico", "./ui/favicon.ico")

	// ... with a redirection for the root page
	m.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "./ui/index.html")
	})

	// All authorized pieces live in /api
	a := m.Group("/api")

	// JWT pieces
	auth := m.Group("/auth")
	auth.POST("/login", getAuthMiddleware().LoginHandler)
	auth.GET("/refresh_token", getAuthMiddleware().RefreshHandler)
	auth.DELETE("/logout", authMiddlewareLogout)
	auth.GET("/logout", authMiddlewareLogout) // for compatibility -- really shouldn't use this

	// Iterate through initializing API maps
	for k, v := range common.ApiMap {
		f := make([]string, 0)
		if v.Authenticated {
			f = append(f, "AUTH")
		}

		log.Printf("Adding handler /api/%s [%s]", k, strings.Join(f, ","))
		g := a.Group("/" + k)
		if v.Authenticated {
			g.Use(getAuthMiddleware().MiddlewareFunc())
		}
		v.RouterFunction(g)
	}

	if *HTTPS_KEY != "" && *HTTPS_CERT != "" {
		log.Printf("Launching https on port :%d", *HTTPS_PORT)
		go func() {
			log.Fatal(manners.ListenAndServeTLS(fmt.Sprintf(":%d", *HTTP_PORT), *HTTPS_CERT, *HTTPS_KEY, m))
		}()
	}

	// HTTP
	log.Printf("Launching http on port :%d", *HTTP_PORT)
	log.Fatal(manners.ListenAndServe(fmt.Sprintf(":%d", *HTTP_PORT), m))
}
Ejemplo n.º 11
0
func main() {
	flag.Parse()

	os.Chdir(*basePath)

	if *dbfile == "" {
		fmt.Println(errors.New("Err: dbfile can't be blank"))
		flag.Usage()
		return
	}

	dbf, err := os.OpenFile(*dbfile, os.O_RDWR|os.O_CREATE, 0700)
	if err != nil {
		panic(err.Error())
	}
	defer dbf.Close()

	dbh := newDbfileHandler(dbf)

	r := gin.Default()
	r.Use(gzip.Gzip(gzip.DefaultCompression))

	apiHeader := func(ctx *gin.Context) {
		ctx.Header("Content-Type", "application/json")
		ctx.Header("Access-Control-Allow-Headers", "Content-Type")
		ctx.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE")
		ctx.Header("Access-Control-Allow-Credentials", "true")
		ctx.Header("Access-Control-Allow-Origin", "*")
	}

	// Dump data data output
	r.GET("/db", apiHeader, func(ctx *gin.Context) {
		ctx.JSON(200, dbh.collection)
	})

	// Retrun th given language translation
	r.GET("/translation/:lang", apiHeader, func(ctx *gin.Context) {
		lang := ctx.Param("lang")
		secArr := make([]Section, 0, 10)

		for _, trans := range dbh.collection {
			secArr = append(secArr, toSectionStruct(&trans, lang))
		}

		ctx.JSON(200, gin.H{
			"result": true,
			"data":   secArr,
		})
	})

	r.GET("/translation/:lang/:section", apiHeader, func(ctx *gin.Context) {
		lang := ctx.Param("lang")
		sectionName := ctx.Param("section")

		trans := newTranslation()
		err := dbh.Section(sectionName, trans)
		if err != nil {
			ctx.JSON(404, gin.H{
				"result": false,
				"err":    err.Error(),
			})
			return
		}

		ctx.JSON(200, gin.H{
			"result": true,
			"data":   toSectionStruct(trans, lang),
		})
	})

	// Create/Update section translation in given language
	r.POST("/translation/:to_lang/:section", apiHeader, func(ctx *gin.Context) {
		var err error
		section := ctx.Param("section")
		toLang := ctx.Param("to_lang")
		sec := new(Section)
		err = ctx.BindJSON(sec)

		if err != nil {
			ctx.JSON(400, gin.H{
				"result": false,
				"err":    err.Error(),
			})

			return
		}

		trans := newTranslation()
		err = dbh.Section(section, trans)
		isNewSection := err != nil

		//new section name
		if sec.RenameTo != "" {
			trans.Section = sec.RenameTo
		}

		//check any removed item
		for o, _ := range trans.Items {
			if _, ok := sec.Items[o]; !ok {
				delete(trans.Items, o)
			}
		}

		//check any new item or translated language
		for o, it := range sec.Items {
			newOriginalItem := true
			for o2, _ := range trans.Items {
				if o == o2 {
					//rename its key
					if it.RenameTo != "" && it.RenameTo != o {
						trans.Items[it.RenameTo] = trans.Items[o]
						delete(trans.Items, o)
						trans.Items[it.RenameTo][toLang] = it.TranslateTo
					} else {
						trans.Items[o][toLang] = it.TranslateTo
					}

					newOriginalItem = false
					break
				}
			}

			if newOriginalItem {
				if _, ok := trans.Items[o]; !ok {
					trans.Items[o] = make(TranslationItem)
				}

				trans.Items[o][toLang] = it.TranslateTo
			}
		}

		if isNewSection {
			trans.Section = section
			err = dbh.Append(*trans)
		} else {
			err = dbh.Update(section, *trans)
		}

		if err != nil {
			ctx.JSON(500, gin.H{
				"result": false,
				"err":    err.Error(),
			})
		}

		ctx.JSON(200, gin.H{
			"result": true,
		})
	})

	r.OPTIONS("*path", apiHeader, func(ctx *gin.Context) {
		//nothing
	})

	if *debug {
		r.StaticFile("/", "static/src/index.html")

		r.Static("/js", "static/src/js")
		r.Static("/img", "static/src/img")
		r.Static("/css", "static/src/css")
		r.Static("/bower_components", "static/src/bower_components")
		r.Static("/tpl", "static/src/tpl")
	} else {
		r.GET("/static/*path", getAsset)
		r.GET("/", getHome)
	}

	r.Run(*host)
}
Ejemplo n.º 12
0
func main() {
	app := gin.New()
	// Initialize config file
	conf := config.LoadConfig()

	// Version
	version := client.Version{Build: BuildTime, Hash: GitHash}
	// Use Logger, Cross-Origin Ressource and GZIP compression middleware
	app.Use(client.LoggerMiddleware())
	app.Use(client.CORSMiddleware())
	app.Use(gzip.Gzip(gzip.DefaultCompression))

	rootusers, emergencyusers, OAuth2Endpoint, err := config.LoadAuthConf(conf)
	if err != nil {
		glog.Errorf("Could not load configuration. Reason: %s", err.Message)
		panic("Could not load configuration for Baboon. Exiting.")
	}
	glog.Infof("%+v", rootusers)
	app.GET("/api/version", version.BaboonVersion)
	if *gtmenabled {

		publicGTM := app.Group("/api/gtms/:trafficmanager")
		{
			publicGTM.GET("/pools", client.GTMPoolList)
			publicGTM.GET("/pools/:pool", client.GTMPoolNameList)
			publicGTM.GET("/pools/:pool/members", client.GTMPoolMemberList)
			publicGTM.GET("/wideips", client.GTMWipList)
			publicGTM.GET("/wideips/:wideip", client.GTMWipNameList)
			publicGTM.GET("/irules", client.GTMIRuleList)
			publicGTM.GET("/irules/:irule", client.GTMIRuleNameList)
		}
		privateGTM := app.Group("/api/gtms/:trafficmanager")
		privateGTM.Use(ginoauth2.Auth(ginoauth2.UidCheck, *OAuth2Endpoint, rootusers))
		{
			privateGTM.POST("/pools", client.GTMPoolPost)
			privateGTM.POST("/pools/:pool/members", client.GTMPoolMemberPost)
			privateGTM.POST("/wideips", client.GTMWideipPost)
			privateGTM.DELETE("/pools/:pool", client.GTMPoolDelete)
			privateGTM.DELETE("/wideips/:wideip", client.GTMWipDelete)
			privateGTM.DELETE("/pools/:pool/members", client.GTMPoolMemberDelete)
		}
		emergencyGTM := app.Group("/api/gtms/:trafficmanager")
		emergencyGTM.Use(ginoauth2.Auth(ginoauth2.UidCheck, *OAuth2Endpoint, emergencyusers))
		{
			emergencyGTM.PUT("/pools/:pool/members", client.GTMPoolMemberStatusPut)
			emergencyGTM.PUT("/pools", client.GTMPoolStatusPut)
		}
	}
	if *ltmenabled {
		publicLTM := app.Group("/api/ltms/:lbpair")
		{
			publicLTM.GET("/pools", client.LTMPoolList)
			publicLTM.GET("/pools/:pool", client.LTMPoolNameList)
			publicLTM.GET("/pools/:pool/members", client.LTMPoolMemberList)
			publicLTM.GET("/devices", client.LTMDeviceList)
			publicLTM.GET("/devices/:devicename", client.LTMDeviceNameList)
			publicLTM.GET("/virtuals", client.LTMVirtualServerList)
			publicLTM.GET("/virtuals/:virtual", client.LTMVirtualServerNameList)
			publicLTM.GET("/virtuals/:virtual/rules", client.LTMFWRuleList)
			publicLTM.GET("/virtuals/:virtual/profiles", client.LTMProfileList)
			publicLTM.GET("/datagroups", client.LTMDataGroupList)
			publicLTM.GET("/datagroups/:datagroupname", client.LTMDataGroupNameList)
			publicLTM.GET("/blacklist", client.LTMBlackAddressList)
			publicLTM.GET("/whitelist", client.LTMWhiteAddressList)
			publicLTM.GET("/irules", client.LTMIRuleList)
			publicLTM.GET("/irules/:irule", client.LTMIRuleNameList)
		}
		privateLTM := app.Group("/api/ltms/:lbpair")
		privateLTM.Use(ginoauth2.Auth(ginoauth2.UidCheck, *OAuth2Endpoint, rootusers))
		{
			privateLTM.POST("/pools", client.LTMPoolPost)
			privateLTM.POST("/virtuals", client.LTMVirtualServerPost)
			privateLTM.POST("/pools/:pool/members", client.LTMPoolMemberPost)
			privateLTM.POST("/datagroups", client.LTMDataGroupPost)
			privateLTM.PUT("/pools", client.LTMPoolPut)
			privateLTM.PUT("/pools/:pool/members", client.LTMPoolMemberPut)
			privateLTM.DELETE("/pools/:pool", client.LTMPoolDelete)
			privateLTM.DELETE("/pools/:pool/members", client.LTMPoolMemberDelete)
			privateLTM.DELETE("/datagroups", client.LTMDataGroupDelete)
			privateLTM.PUT("/datagroups/:datagroupname", client.LTMDataGroupItemPut)
			privateLTM.PATCH("/datagroups/:datagroupname", client.LTMDataGroupItemPatch)
			//To do: privateLTM.DELETE("/datagroups/:direction/:datagroupname", client.LTMDataGroupItemDelete)
		}
		emergencyLTM := app.Group("/api/ltms/:lbpair")
		emergencyLTM.Use(ginoauth2.Auth(ginoauth2.UidCheck, *OAuth2Endpoint, emergencyusers))
		{
			emergencyLTM.PATCH("/blacklist", client.LTMBlockIPPatch)
			emergencyLTM.PATCH("/whitelist", client.LTMWhiteIPPatch)
			emergencyLTM.DELETE("/whitelist", client.LTMRemoveWhiteIPPatch)
			emergencyLTM.DELETE("/blacklist", client.LTMRemoveBlockIPPatch)
		}
	}
	switch {
	case *sslenabled:
		run := app.RunTLS(fmt.Sprintf(":%s", strconv.Itoa(*port)),
			conf.Security["certFile"],
			conf.Security["keyFile"])
		if run != nil {
			fmt.Println("Could not start web server,", run.Error())
		}
	default:
		run := app.Run(fmt.Sprintf(":%s", strconv.Itoa(*port)))
		if run != nil {
			fmt.Println("Could not start web server,", run.Error())
		}
	}
}
Ejemplo n.º 13
0
/*
GZIP compress responses
*/
func GZIP() gin.HandlerFunc {
	return gzip.Gzip(gzip.DefaultCompression)
}