Esempio n. 1
8
func Run() {

	router := gin.Default()
	router.LoadHTMLGlob("panel/templates/*")
	router.Static("/static/", "static")
	router.Static("/assets/", "assets")

	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "main.html", gin.H{})
	})

	// get users from file
	users := make(gin.Accounts)
	file, err := os.Open("users.txt")
	checkErr(err)
	defer file.Close()
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		user := strings.Split(line, ":")
		users[user[0]] = user[1]
	}
	checkErr(err)

	mailer := router.Group("mailer", gin.BasicAuth(users))
	{
		mailer.GET("logout", func(c *gin.Context) {
			c.HTML(http.StatusUnauthorized, "logout.html", nil)
		})

		mailer.GET("group", func(c *gin.Context) {
			data := gin.H{
				"groups": getGroups(),
			}
			c.HTML(http.StatusOK, "group.html", data)
		})

		mailer.POST("group", func(c *gin.Context) {
			addGroup(c.PostForm("name"))
			data := gin.H{
				"groups": getGroups(),
			}
			c.HTML(http.StatusOK, "group.html", data)
		})

		mailer.GET("group/:id", func(c *gin.Context) {
			data := gin.H{
				"campaigns": getCampaigns(c.Param("id")),
			}
			c.HTML(http.StatusOK, "campaign.html", data)
		})

		mailer.POST("group/:id", func(c *gin.Context) {
			addCampaigns(c.Param("id"), c.PostForm("name"))
			data := gin.H{
				"campaigns": getCampaigns(c.Param("id")),
			}
			c.HTML(http.StatusOK, "campaign.html", data)
		})

		mailer.GET("campaign/edit/:id", func(c *gin.Context) {
			camp, err := getCampaignInfo(c.Param("id"))

			if err == nil {
				data := gin.H{
					"ifaces":   getIfaces(),
					"campaign": camp,
				}
				c.HTML(http.StatusOK, "campaignEdit.html", data)
			} else {
				// blank 16x16 png
				c.Header("Content-Type", "image/png")
				output, _ := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAADUExURUxpcU3H2DoAAAABdFJOUwBA5thmAAAADUlEQVQY02NgGAXIAAABEAAB7JfjegAAAABJRU5ErkJggg==iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAADUExURUxpcU3H2DoAAAABdFJOUwBA5thmAAAAEklEQVQ4y2NgGAWjYBSMAuwAAAQgAAFWu83mAAAAAElFTkSuQmCC")
				c.String(http.StatusOK, string(output))
			}
		})

		mailer.POST("campaign/edit/:id", func(c *gin.Context) {
			data := gin.H{
				"ifaces": getIfaces(),
				"campaign": updateCampaignInfo(
					campaign{
						Id:        c.Param("id"),
						IfaceId:   c.PostForm("ifaceId"),
						Name:      c.PostForm("name"),
						Subject:   c.PostForm("subject"),
						From:      c.PostForm("from"),
						FromName:  c.PostForm("fromName"),
						Message:   c.PostForm("message"),
						StartTime: c.PostForm("startTime"),
						EndTime:   c.PostForm("endTime"),
					},
				),
			}

			c.HTML(http.StatusOK, "campaignEdit.html", data)
		})

		mailer.GET("campaign/recipient/get/:id", func(c *gin.Context) {
			data := gin.H{
				"campaignId": c.Param("id"),
				"recipients": getRecipients(c.Param("id"), "0", "10"),
			}
			c.HTML(http.StatusOK, "recipient.html", data)
		})

		mailer.GET("campaign/recipient/param/:id", func(c *gin.Context) {
			data := gin.H{
				"recipient": getRecipient(c.Param("id")),
				"params":    getRecipientParam(c.Param("id")),
			}
			c.HTML(http.StatusOK, "recipientParam.html", data)
		})

		mailer.GET("recipients/:id", hRecipients)
		mailer.POST("recipients/:id", uploadRecipients)

	}

	router.GET("filemanager", func(c *gin.Context) {
		if c.Query("mode") == "download" {
			var n string
			var d []byte

			if c.Query("width") != "" && c.Query("height") != "" {
				// Download resized
				d = FilemanagerResize(c.Query("path"), c.Query("width"), c.Query("height"))
			} else {
				// Download file
				n, d = FilemanagerDownload(c.Query("path"))
				c.Header("Content-Disposition", "attachment; filename='"+n+"'")
			}
			c.Data(http.StatusOK, http.DetectContentType(d), d)

		} else {
			c.JSON(http.StatusOK, Filemanager(c.Query("mode"), c.Query("path"), c.Query("name"), c.Query("old"), c.Query("new")))
		}
	})

	router.POST("filemanager", func(c *gin.Context) {
		if c.PostForm("mode") == "add" {
			file, head, err := c.Request.FormFile("newfile")
			checkErr(err)
			c.JSON(http.StatusOK, FilemanagerAdd(c.PostForm("currentpath"), head.Filename, file))
		}
	})

	api := router.Group("api")
	{
		table := api.Group("mailer")
		{
			table.GET("recipients/:id", aRecipients)
		}
	}

	router.Run(":7777")
}
Esempio n. 2
0
func Serve(address, dbpath string) {

	DBInit(dbpath)
	AccountsInit()
	route := gin.Default()
	route.GET("/", Index)
	route.LoadHTMLGlob("templates/*.html")

	product := route.Group("/product", gin.BasicAuth(ACCOUNT))
	{
		product.GET(":id", getProduct)
		product.GET("", queryProduct)
		product.POST("", updateProduct)
		product.POST(":id", updateProduct)
		product.DELETE(":id", deleteProduct)
	}

	series := route.Group("/series", gin.BasicAuth(ACCOUNT))
	{
		series.POST("", addSeries)
	}

	validate := route.Group("/v")
	{
		validate.GET(":id", getSerie)
		validate.POST(":id", claimSerie)
	}

	route.Static("/static", "static")
	route.Static("/asset", "asset")
	route.Run(address)
}
func TestLogRequest(t *testing.T) {

	s := loadServerCtx()
	s.AllowedApps = append(s.AllowedApps, "test")
	s.AppPasswd["test"] = "pass"

	s.in = make(chan *logData)
	defer close(s.in)
	s.out = make(chan *logMetrics)
	defer close(s.out)

	go logProcess(s.in, s.out)

	r := gin.New()
	auth := r.Group("/", gin.BasicAuth(s.AppPasswd))
	auth.POST("/", s.processLogs)

	req, _ := http.NewRequest("POST", "/", bytes.NewBuffer([]byte("LINE of text\nAnother line\n")))
	req.SetBasicAuth("test", "pass")
	resp := httptest.NewRecorder()
	r.ServeHTTP(resp, req)

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Error(err)
	}
	if string(body) != "OK" {
		t.Error("resp body should match")
	}

	if resp.Code != 200 {
		t.Error("should get a 200")
	}

}
Esempio n. 4
0
func main() {
	r := gin.Default()

	// Group using gin.BasicAuth() middleware
	// gin.Accounts is a shortcut for map[string]string
	authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
		"foo":    "bar",
		"austin": "1234",
		"lena":   "hello2",
		"manu":   "4321",
	}))

	// /admin/secrets endpoint
	// hit "localhost:8080/admin/secrets
	authorized.GET("/secrets", func(c *gin.Context) {
		// get user, it was setted by the BasicAuth middleware
		user := c.MustGet(gin.AuthUserKey).(string)
		if secret, ok := secrets[user]; ok {
			c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
		} else {
			c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
		}
	})

	// Listen and server on 0.0.0.0:8080
	r.Run(":8080")
}
Esempio n. 5
0
// Listen Tells Gin API to start
func Listen(iface string, s *discordgo.Session, logger *logging.Logger) {
	// set the refs to point to main
	var v1 *gin.RouterGroup
	session = s
	c := config.Get()
	log = logger

	if c.LogLevel != "debug" {
		gin.SetMode(gin.ReleaseMode)
	}

	//r := gin.Default()
	r := gin.New()

	r.Use(loggerino())
	r.Use(gin.Recovery())

	if c.APIPassword != "" {
		log.Info("Basic Authentication enabled for API")
		v1 = r.Group("/v1", gin.BasicAuth(gin.Accounts{
			c.APIUsername: c.APIPassword,
		}))
	} else {
		log.Warning("DIGO_API_PASSWORD and DIGO_API_USERNAME are not set")
		log.Warning("The API is open to all requests")
		v1 = r.Group("/v1")
	}

	v1.GET("/version", versionV1)
	v1.GET("/channels", channelsV1)
	v1.POST("/message", messageV1)

	go r.Run(iface)
	log.Noticef("Digo API is listening on %s", c.APIInterface)
}
Esempio n. 6
0
func main() {
	flag.Parse()
	if showv {
		showVersion()
		return
	}

	appConfig, err := config.LoadAppConfig(conf)
	if err != nil {
		fmt.Printf("config load err: %s\n", err)
		os.Exit(-1)
	}

	if !debug {
		gin.SetMode(gin.ReleaseMode)
	}
	r := gin.Default()
	r.Static("/assets", "./ui/assets")
	r.LoadHTMLGlob("ui/templates/*")
	r.Use(appConfigMiddleware(appConfig))

	if appConfig.Basic_auth.On {
		r.Use(gin.BasicAuth(gin.Accounts{appConfig.Basic_auth.Username: appConfig.Basic_auth.Password}))
	}

	r.GET("/", controller.Home)
	r.GET("/node", controller.Node)
	r.GET("/cluster", controller.Cluster)
	r.POST("/do", controller.Do)

	r.Run(listen)
}
func main() {
	gin.SetMode(gin.ReleaseMode)

	s := loadServerCtx()
	if s.Debug {
		log.SetLevel(log.DebugLevel)
		gin.SetMode(gin.DebugMode)
	}

	c, err := statsdClient(s.StatsdUrl)
	if err != nil {
		log.WithField("statsdUrl", s.StatsdUrl).Fatal("Could not connect to statsd")
	}

	r := gin.Default()
	r.GET("/status", func(c *gin.Context) {
		c.String(200, "OK")
	})

	if len(s.AppPasswd) > 0 {
		auth := r.Group("/", gin.BasicAuth(s.AppPasswd))
		auth.POST("/", s.processLogs)
	}

	s.in = make(chan *logData, bufferLen)
	defer close(s.in)
	s.out = make(chan *logMetrics, bufferLen)
	defer close(s.out)
	go logProcess(s.in, s.out)
	go c.sendToStatsd(s.out)
	log.Infoln("Server ready ...")
	r.Run(":" + s.Port)

}
Esempio n. 8
0
func startHTTP() {
	log.Printf("Starting server on %s", gConfig.Host)

	router := gin.Default()
	if gConfig.HasAuth() {
		router.Use(gin.BasicAuth(gin.Accounts{gConfig.UI.Username: gConfig.UI.Password}))
	}
	router.Use(gitserverHandler())

	if gConfig.EnableCORS {
		router.Use(corsHandler())
	}

	if !gConfig.UI.DisableUI {
		router.StaticFS(gConfig.Repos.Path, http.Dir("./public/"))
	}
	router.GET("/", handler)

	api.SetupRouter(router)

	if einhorn.IsRunning() {
		einhorn.Start(router, 0)
	} else {
		router.Run(gConfig.Host)
	}
}
Esempio n. 9
0
func (s schedule) Monitor(e *gin.Engine, path, username, password string) schedule {
	r := e.RouterGroup
	m := gin.Accounts{
		username: password,
	}
	r.Use(gin.BasicAuth(m))
	r.GET(path, JobHtml)
	return s
}
Esempio n. 10
0
func (s *Service) Run() error {
	eng := gin.Default()
	eng.LoadHTMLGlob(s.Config.App.TemplatesPath + "/*")
	eng.Static("/assets", s.Config.App.AssetPath)

	prefix := "/"
	if s.Config.App.Prefix != "" {
		prefix = s.Config.App.Prefix
	}

	g := eng.Group(prefix, gin.BasicAuth(gin.Accounts{
		s.Config.Admin.Login: s.Config.Admin.Password,
	}))

	g.GET("/", func(c *gin.Context) {
		posts, e := s.Store.GetSlice(10, 0)
		res := gin.H{}
		if e != nil {
			fmt.Println(e)
			res["error"] = e
		}
		res["posts"] = posts
		c.HTML(200, "index.html", res)
	})

	g.Any("/create", func(c *gin.Context) {
		rm := gin.H{}
		if c.Request.Method == "POST" {
			rm["message"] = "posted"

			title := c.PostForm("title")
			content := c.PostForm("content")

			p := new(Post)
			p.Title = title
			p.Body = content

			e := s.Store.Save(p)
			if e != nil {
				fmt.Println(e)
				rm["error"] = e
			}
		}
		c.HTML(200, "edit.html", rm)
	})

	g.GET("/p/:id", func(c *gin.Context) {
		id := c.Param("id")
		c.HTML(200, "show.html", gin.H{"da": id})
	})

	g.POST("/p/:id", func(c *gin.Context) {

	})

	return http.ListenAndServe(fmt.Sprintf(":%d", s.Config.App.Port), eng)
}
Esempio n. 11
0
func (s *Server) Start() {
	r := gin.Default()

	r.StaticFS("/data", http.Dir(filepath.Join(s.FpRoot, "data")))
	r.StaticFS("/assets", http.Dir("./assets"))

	var api, ui gin.IRoutes
	if s.AdminUser != "" {
		accounts := gin.Accounts{s.AdminUser: s.AdminPass}
		api = r.Group("/api", gin.BasicAuth(accounts))
		ui = r.Group("/ui", gin.BasicAuth(accounts))
	} else {
		api = r.Group("/api")
		ui = r.Group("/ui")
	}

	{
		api.POST("/upload/:hash", s.upload)
		api.POST("/nonexists", s.nonexists)
		api.GET("/stat", s.stat)
		api.GET("/tags", s.indexTags)
		api.GET("/tags/:id", s.getTags)
		api.POST("/tags/:id", s.postTags)
		api.GET("/tags/:id/files/*path", s.getTagsFile)
		api.GET("/tags/:id/versions", s.indexTagsVersions)
	}

	ui.GET("/*dummy", func(c *gin.Context) {
		file, err := ioutil.ReadFile("./assets/index.html")
		if err != nil {
			c.AbortWithError(500, err)
			return
		}
		c.Data(200, "text/html", file)
	})

	// redirect _admin/* to api/*
	r.Any("/_admin/*path", func(c *gin.Context) {
		c.Request.URL.Path = "/api" + c.Param("path")
		r.ServeHTTP(c.Writer, c.Request)
	})

	r.Run(fmt.Sprintf(":%d", s.Port))
}
Esempio n. 12
0
func startServer() {
	router := gin.Default()

	// Enable HTTP basic authentication only if both user and password are set
	if options.AuthUser != "" && options.AuthPass != "" {
		auth := map[string]string{options.AuthUser: options.AuthPass}
		router.Use(gin.BasicAuth(auth))
	}

	router.GET("/", APIHome)
	router.POST("/connect", APIConnect)
	router.DELETE("/disconnect", APIClose)
	router.GET("/databases", APIGetDatabases)
	router.GET("/databases/:database/tables", APIGetDatabaseTables)
	router.GET("/databases/:database/tables/:table/column", APIGetColumnOfTable)
	router.GET("/databases/:database/views", APIGetDatabaseViews)
	router.GET("/databases/:database/procedures", APIGetDatabaseProcedures)
	router.GET("/databases/:database/functions", APIGetDatabaseFunctions)
	router.POST("/databases/:database/actions/default", APISetDefaultDatabase)
	router.GET("/info", APIInfo)
	router.GET("/tables/:table/info", APIGetTableInfo)
	router.GET("/tables/:table/indexes", APITableIndexes)
	router.GET("/query", APIRunQuery)
	router.POST("/query", APIRunQuery)
	router.GET("/explain", APIExplainQuery)
	router.POST("/explain", APIExplainQuery)
	router.GET("/history", APIHistory)
	router.GET("/static/:type/:name", APIServeAsset)
	router.GET("/procedures/:procedure/parameters", APIProcedureParameters)
	router.GET("/collation", APIGetCollationCharSet)
	router.POST("/databases/:database/actions/alter", APIAlterDatabase)
	router.DELETE("/databases/:database/actions/drop", APIDropDatabase)
	router.DELETE("/databases/:database/tables/:table/actions/drop", APIDropTable)
	router.DELETE("/databases/:database/tables/:table/actions/truncate", APITruncateTable)
	router.GET("/databases/:database/procedures/:procedure", APIProcedureDefinition)
	router.GET("/databases/:database/functions/:function", APIFunctionDefinition)
	router.POST("/databases/:database/procedures/:procedure", APICreateProcedure)
	router.POST("/databases/:database/functions/:function", APICreateFunction)
	router.DELETE("/databases/:database/procedures/:procedure/actions/drop", APIDropProcedure)
	router.GET("/databases/:database/views/:view", APIViewDefinition)
	router.GET("/search/:query", apiSearch)
	router.GET("/bookmarks", APIGetBookmarks)
	router.POST("/bookmarks/:name", APISaveBookmark)
	router.DELETE("/bookmarks/:name", APIDeleteBookmark)
	router.GET("/updates", getUpdate)

	fmt.Println("Starting server...")
	go router.Run(fmt.Sprintf("%v:%v", options.HttpHost, options.HttpPort))
}
Esempio n. 13
0
func main() {
	r := gin.Default()

	// Ping test
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})

	// Get user value
	r.GET("/user/:name", func(c *gin.Context) {
		user := c.Params.ByName("name")
		value, ok := DB[user]
		if ok {
			c.JSON(200, gin.H{"user": user, "value": value})
		} else {
			c.JSON(200, gin.H{"user": user, "status": "no value"})
		}
	})

	// Authorized group (uses gin.BasicAuth() middleware)
	// Same than:
	// authorized := r.Group("/")
	// authorized.Use(gin.BasicAuth(gin.Credentials{
	//	  "foo":  "bar",
	//	  "manu": "123",
	//}))
	authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
		"foo":  "bar", // user:foo password:bar
		"manu": "123", // user:manu password:123
	}))

	authorized.POST("admin", func(c *gin.Context) {
		user := c.MustGet(gin.AuthUserKey).(string)

		// Parse JSON
		var json struct {
			Value string `json:"value" binding:"required"`
		}

		if c.Bind(&json) {
			DB[user] = json.Value
			c.JSON(200, gin.H{"status": "ok"})
		}
	})

	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}
Esempio n. 14
0
// RegistrarRotas realiza o registro de todas as rotas da aplicação.
func RegistrarRotas(r *gin.Engine, usuario, senha string) {

	// Habilitando esquema de autorização simples
	auth := r.Group("/", gin.BasicAuth(gin.Accounts{usuario: senha}))

	auth.GET("/", Raiz)

	auth.GET("/pagina/:pag", Pagina)

	auth.GET("/formulario", Formulario)

	auth.POST("/salvar", Salvar)

	auth.GET("/remover/:id", Remover)

	auth.GET("/editar/:id", Editar)
}
Esempio n. 15
0
func (s *TwitterService) Run(cfg Config) error {
	s.Migrate(cfg)
	db, err := s.getDb(cfg)
	if err != nil {
		return err
	}
	db.SingularTable(true)

	twitterResource := &TwitterResource{db: db}

	r := gin.Default()
	//gin.SetMode(gin.ReleaseMode)
	r.Use(cors.Middleware(cors.Options{}))

	ba := r.Group("/", gin.BasicAuth(gin.Accounts{
		"paul": "1234",
		"ming": "1234",
	}))

	ba.GET("/twitter", twitterResource.GetAllTwitters)
	ba.GET("/twitter/:id", twitterResource.GetTwitter)
	ba.POST("/twitter", twitterResource.CreateTwitter)
	ba.PUT("/twitter/:id", twitterResource.UpdateTwitter)
	ba.PATCH("/twitter/:id", twitterResource.PatchTwitter)
	ba.DELETE("/twitter/:id", twitterResource.DeleteTwitter)

	//for user
	ba.GET("/user", twitterResource.GetAllUsers)
	ba.GET("/user/:id", twitterResource.GetUser)
	ba.POST("/user", twitterResource.CreateUser)
	ba.PUT("/user/:id", twitterResource.UpdateUser)
	ba.PATCH("/user/:id", twitterResource.PatchUser)
	ba.DELETE("/user/:id", twitterResource.DeleteUser)

	//user+twitter
	ba.POST("/twitter/user/:id", twitterResource.CreateTwitterByUserId)
	ba.GET("/user/:id/twitter", twitterResource.GetTwittersByUserId)

	r.Run(cfg.SvcHost)

	return nil
}
Esempio n. 16
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)
}
Esempio n. 17
0
func startServer() {
	router := gin.Default()

	// Enable HTTP basic authentication only if both user and password are set
	if options.AuthUser != "" && options.AuthPass != "" {
		auth := map[string]string{options.AuthUser: options.AuthPass}
		router.Use(gin.BasicAuth(auth))
	}

	api.SetupRoutes(router)

	fmt.Println("Starting server...")
	go func() {
		err := router.Run(fmt.Sprintf("%v:%v", options.HttpHost, options.HttpPort))
		if err != nil {
			fmt.Println("Cant start server:", err)
			os.Exit(1)
		}
	}()
}
Esempio n. 18
0
File: main.go Progetto: serkas/knots
func main() {
	r := gin.Default()
	authorized := r.Group("", gin.BasicAuth(gin.Accounts{
		"admin": "admin",
	}))

	env := handlers.InitEnv()
	defer env.Destroy()

	r.Static("/assets", "./assets")
	r.GET("/", handlers.Index)

	// Knots handlers
	r.GET("/knots", env.AllKnot)
	r.GET("/knots/:id", env.OneKnot)
	authorized.POST("/knots", env.NewKnot)
	authorized.PUT("/knots/:id", env.UpdateKnot)
	authorized.DELETE("/knots/:id", env.DeleteKnot)

	r.Run(":8001")
}
Esempio n. 19
0
func startServer(port uint, adminPassword string) {
	router := gin.Default()
	router.Static("/assets", "./assets")

	router.GET("/", func(c *gin.Context) {
		showProjects(c)
	})

	authorized := router.Group("/add", gin.BasicAuth(gin.Accounts{
		"admin": adminPassword,
	}))

	authorized.GET("", func(c *gin.Context) {
		render.New(c).HTML(http.StatusOK, "add.tmpl", nil)
	})

	authorized.POST("", func(c *gin.Context) {
		addNewProject(c)
	})

	router.Run(fmt.Sprintf(":%v", port))
}
Esempio n. 20
0
func main() {
	r := gin.Default()
	r.Static("/assets", "./assets")
	r.LoadHTMLGlob("templates/*")

	/*Arduino 接入路由*/
	r.POST("/device/locate", D_Locate)

	/*AJAX 请求路由*/
	r.GET("/ajax/location", GetLocation)
	r.GET("/ajax/location/all", GetAllLocation)

	/*控制台路由*/
	authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
		"admin": "123456",
	}))

	authorized.GET("/", Index)
	authorized.GET("/location/list", List)
	authorized.GET("/location/delete/:id", Delete)

	r.Run(":8080")
}
Esempio n. 21
0
func main() {
	appConfig, err := config.LoadAppConfig(APP_CONFIG_PATH)
	if err != nil {
		fmt.Println("发生错误:", err.Error())
		os.Exit(-1)
	}

	r := gin.Default()
	r.Static("/assets", "./ui/assets")
	r.LoadHTMLGlob("ui/templates/*")
	r.Use(appConfigMiddleware(appConfig))

	if appConfig.Basic_auth.On == "yes" {
		r.Use(gin.BasicAuth(gin.Accounts{appConfig.Basic_auth.Username: appConfig.Basic_auth.Password}))
	}

	r.GET("/", controller.Home)
	r.POST("/do", controller.Do)

	var port string
	flag.StringVar(&port, "listen", ":8080", "listen address")
	flag.Parse()
	r.Run(port)
}
Esempio n. 22
0
func main() {
	defer glog.Flush()

	flag.StringVar(&kubeclient.KubeConfigFile, "kubeconfig", "kubeconfig.json", "Specify the target API server")
	flag.Set("logtostderr", "true")
	flag.Parse()

	kubeclient.Init()
	portMapping = regexp.MustCompile(`PortMapping\((.*)\)`)

	r := gin.Default()
	r.Static("/js", "js")
	r.Static("/css", "css")
	r.Static("/fonts", "fonts")
	r.Static("/img", "img")
	r.LoadHTMLGlob("pages/*.html")

	a := r.Group("/", gin.BasicAuth(gin.Accounts{
		"admin":    "secretsigma",
		"bamboo":   "oobmab",
		"default":  "test123",
		"rds":      "rrddss",
		"rds-test": "rrddsstt",
	}))

	a.GET("/", overview)
	a.GET("/namespaces/:ns", listOthersInNamespace)
	a.GET("/namespaces/:ns/pods", listPodsInNamespace)
	a.GET("/namespaces/:ns/pods/:po", describePod)
	a.GET("/namespaces/:ns/pods/:po/log", readPodLog)
	a.GET("/namespaces/:ns/pods/:po/containers/:ct/log", readContainerLog)
	a.GET("/namespaces/:ns/pods/:po/edit", editPod)
	a.GET("/namespaces/:ns/replicationcontrollers/:rc/edit", editReplicationController)
	a.GET("/namespaces/:ns/services/:svc/edit", editService)
	a.GET("/namespaces/:ns/endpoints/:ep/edit", editEndpoints)
	a.GET("/nodes/:no/edit", editNode)
	a.GET("/namespaces/:ns/events", listEventsInNamespace)
	a.GET("/nodes", listNodes)
	a.GET("/nodes/:no", describeNode)
	a.GET("/help", help)
	a.GET("/config", config)

	a.GET("/namespaces/:ns/replicationcontrollers.form", showReplicationControllerForm)
	a.POST("/namespaces/:ns/replicationcontrollers", createReplicationController)

	a.GET("/namespaces/:ns/services.form", showServiceForm)
	a.POST("/namespaces/:ns/services", createService)

	a.POST("/namespaces/:ns/pods.form", showPodsForm)
	a.POST("/namespaces/:ns/pods", performPodsAction)

	a.POST("/config/update", updateConfig)
	a.POST("/namespaces/:ns/pods/:po/update", updatePod)
	a.POST("/namespaces/:ns/pods/:po/export", updateReplicationControllerWithPod)
	a.POST("/namespaces/:ns/pods/:po/import", updatePodWithReplicationController)
	a.POST("/namespaces/:ns/services/:svc/update", updateService)
	a.POST("/namespaces/:ns/services/:svc/delete", deleteService)
	a.POST("/namespaces/:ns/endpoints/:ep/update", updateEndpoints)
	a.POST("/namespaces/:ns/endpoints/:ep/delete", deleteEndpoints)
	a.POST("/namespaces/:ns/replicationcontrollers/:rc/update", updateReplicationController)
	a.POST("/namespaces/:ns/replicationcontrollers/:rc/delete", deleteReplicationController)
	a.POST("/nodes/:no/update", updateNode)
	a.POST("/nodes/:no/delete", deleteNode)

	certFile := "kubecon.crt"
	keyFile := "kubecon.key"
	alternateIPs := []net.IP{net.ParseIP("61.160.36.122")}
	alternateDNS := []string{"kubecon"}
	if err := util.GenerateSelfSignedCert("61.160.36.122", certFile, keyFile, alternateIPs, alternateDNS); err != nil {
		glog.Errorf("Unable to generate self signed cert: %v", err)
	} else {
		glog.Infof("Using self-signed cert (%s, %s)", certFile, keyFile)
	}
	r.RunTLS(":8080", certFile, keyFile)
}
Esempio n. 23
0
func main() {

	model.InitTool()

	r := gin.Default()
	authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
		"admin": "123456",
	}))
	r.Use(middleware.Cookie())
	r.LoadHTMLGlob("templates/*")
	r.Static("/assets", "./assets")
	r.GET("/", ShowIndex)
	r.GET("/user/register", UserRegisterHandler)
	r.GET("/user/logout", UserLogout)
	r.POST("/user/register", UserRegisterHandler)
	r.GET("/user/login", UserLogin)
	r.POST("/user/login", UserLogin)
	r.POST("address/new", NewAddress)
	r.POST("address/del", DelAddress)
	/* Admin */
	authorized.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "admin_index.html", nil)
	})
	authorized.GET("/goods", func(c *gin.Context) {
		cate := model.Category{Top: 0}
		cates := cate.GetTopListNot()
		goods := model.Goods{}
		goods_list := goods.GetAll()
		obj := make(map[string]interface{})
		obj["cates"] = cates
		obj["goods_list"] = goods_list
		c.HTML(http.StatusOK, "admin_goods.html", obj)
	})
	authorized.POST("/goods/add", func(c *gin.Context) {
		file, _, err := c.Request.FormFile("photo")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		timestamp := fmt.Sprintf("%d", time.Now().Unix())
		saveFilePath := "./assets/data/goods/" + timestamp + ".png"
		photo, err := os.OpenFile(saveFilePath, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer photo.Close()
		io.Copy(photo, file)
		name := c.PostForm("name")
		price, _ := strconv.ParseFloat(c.PostForm("price"), 64)
		cate_id, _ := strconv.Atoi(c.PostForm("cate"))
		desc := c.PostForm("description")
		cate := model.Category{}
		cate.Get(cate_id)
		fmt.Println(cate)
		goods := model.Goods{Name: name, Price: price, Description: desc, Cate: cate, Photo: timestamp + ".png"}
		fmt.Println(goods)
		if goods.InsertToDB() {
			c.Redirect(http.StatusMovedPermanently, "/admin/goods")
		}
	})
	authorized.POST("/goods/modify", func(c *gin.Context) {

		m_id, _ := strconv.Atoi(c.PostForm("m-id"))
		g := model.Goods{}
		g.Get(m_id)
		name := c.PostForm("m-name")
		price, _ := strconv.ParseFloat(c.PostForm("m-price"), 64)
		cate_id, _ := strconv.Atoi(c.PostForm("m-cate"))
		desc := c.PostForm("m-description")
		cate := model.Category{}
		cate.Get(cate_id)
		g.Name = name
		g.Price = price
		g.Cate = cate
		g.Description = desc

		file, _, err := c.Request.FormFile("m-photo")
		if file != nil {
			defer file.Close()
			rm_err := os.Remove("./assets/data/goods/" + g.Photo)
			if rm_err != nil {
				fmt.Println(err)
			}
			timestamp := fmt.Sprintf("%d", time.Now().Unix())
			saveFilePath := "./assets/data/goods/" + timestamp + ".png"
			photo, err := os.OpenFile(saveFilePath, os.O_WRONLY|os.O_CREATE, 0666)
			if err != nil {
				fmt.Println(err)
				return
			}
			defer photo.Close()
			io.Copy(photo, file)
			g.Photo = timestamp + ".png"
		}

		g.Update()

		c.Redirect(http.StatusMovedPermanently, "/admin/goods")

	})

	authorized.POST("/goods/delete/", func(c *gin.Context) {
		id, _ := strconv.Atoi(c.PostForm("id"))
		goods := model.Goods{}
		goods.Get(id)
		goods.Delete()
		c.JSON(http.StatusOK, gin.H{"message": "ok"})
	})

	authorized.GET("/goods/:id", func(c *gin.Context) {
		goods_id, _ := strconv.Atoi(c.Param("id"))
		goods := model.Goods{}
		goods.Get(goods_id)
		c.JSON(http.StatusOK, goods)
	})

	authorized.GET("/order", func(c *gin.Context) {
		c.HTML(http.StatusOK, "admin_order.html", nil)
	})

	authorized.GET("/category", func(c *gin.Context) {
		cate := model.Category{Top: 0}
		top_cates := cate.GetTopList()
		cates := cate.GetAll()
		obj := make(map[string]interface{})
		obj["top_cates"] = top_cates
		obj["cates"] = cates
		c.HTML(http.StatusOK, "admin_category.html", obj)
	})
	authorized.POST("/category/add", func(c *gin.Context) {
		top, _ := strconv.Atoi(c.PostForm("top"))
		name := c.PostForm("name")
		cate := model.Category{Name: name, Top: top}
		if cate.InsertToDB() {
			c.Redirect(http.StatusMovedPermanently, "/admin/category")
		}

	})
	authorized.POST("/category/modify", func(c *gin.Context) {
		top, _ := strconv.Atoi(c.PostForm("top"))
		name := c.PostForm("name")
		cate := model.Category{Name: name, Top: top}
		id, _ := strconv.Atoi(c.PostForm("id"))
		cate.Update(id)
		c.Redirect(http.StatusMovedPermanently, "/admin/category")

	})
	authorized.POST("/category/delete", func(c *gin.Context) {
		id, _ := strconv.Atoi(c.PostForm("id"))
		cate := model.Category{}
		cate.Delete(id)
		c.JSON(http.StatusOK, gin.H{"message": "ok"})

	})
	authorized.GET("/category/:id", func(c *gin.Context) {
		cate_id, _ := strconv.Atoi(c.Param("id"))
		cate := model.Category{}
		cate.Get(cate_id)
		c.JSON(http.StatusOK, cate)
	})

	r.Run(":8080")
}
Esempio n. 24
0
func main() {
	// Setup the Radio instance
	Radio = radioman.NewRadio("RadioMan")

	if err := Radio.Init(); err != nil {
		logrus.Fatalf("Failed to initialize the radio: %v", err)
	}
	if err := Radio.StdPopulate(); err != nil {
		logrus.Fatalf("Failed to populate the radio: %v", err)
	}

	// Setup the web server
	router := gin.Default()
	public := router.Group("/")
	admin := router.Group("/")
	liquidsoap := router.Group("/")
	// Admin auth
	// FIXME: make accounts dynamic
	accounts := gin.Accounts{"admin": "admin"}
	admin.Use(gin.BasicAuth(accounts))
	// FIXME: add authentication on liquidsoap next handler

	public.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})

	staticPrefix := "./radioman/web"
	if os.Getenv("WEBDIR") != "" {
		staticPrefix = os.Getenv("WEBDIR")
	}

	public.StaticFile("/", path.Join(staticPrefix, "static/index.html"))
	public.Static("/static", path.Join(staticPrefix, "static"))
	public.Static("/bower_components", path.Join(staticPrefix, "bower_components"))

	admin.StaticFile("/admin/", path.Join(staticPrefix, "static/admin/index.html"))

	admin.GET("/api/playlists", playlistsEndpoint)
	admin.GET("/api/playlists/:name", playlistDetailEndpoint)
	admin.PATCH("/api/playlists/:name", playlistUpdateEndpoint)
	admin.GET("/api/playlists/:name/tracks", playlistTracksEndpoint)

	admin.GET("/api/radios/default", defaultRadioEndpoint)
	public.GET("/api/radios/default/endpoints", radioEndpointsEndpoint)
	admin.POST("/api/radios/default/skip-song", radioSkipSongEndpoint)
	admin.POST("/api/radios/default/play-track", radioPlayTrackEndpoint)
	admin.POST("/api/radios/default/set-next-track", radioSetNextTrackEndpoint)

	admin.GET("/api/tracks/:hash", trackDetailEndpoint)

	liquidsoap.GET("/api/liquidsoap/getNextSong", getNextSongEndpoint)

	public.GET("/playlist.m3u", m3uPlaylistEndpoint)

	// Launch routines
	go Radio.UpdatePlaylistsRoutine()

	// Start web server mainloop
	port := os.Getenv("PORT")
	if port == "" {
		port = "8000"
	}
	router.Run(fmt.Sprintf(":%s", port))
}
Esempio n. 25
0
func basicAuthorizer() gin.HandlerFunc {
	accounts := gin.Accounts{}
	accounts[utils.Cfg.ApiAuthSettings.User] = utils.Cfg.ApiAuthSettings.Password

	return gin.BasicAuth(accounts)
}
func TestFull(t *testing.T) {

	s := loadServerCtx()
	s.AllowedApps = append(s.AllowedApps, "test")
	s.AppPasswd["test"] = "pass"

	s.in = make(chan *logData)
	defer close(s.in)
	s.out = make(chan *logMetrics)
	defer close(s.out)

	addr := "localhost:1201"
	udpAddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		t.Fatal(err)
	}

	server, err := net.ListenUDP("udp", udpAddr)
	if err != nil {
		t.Fatal(err)
	}
	defer server.Close()

	c, err := statsdClient(addr)
	if err != nil {
		t.Fatal(err)
	}

	go logProcess(s.in, s.out)
	go c.sendToStatsd(s.out)

	r := gin.New()
	auth := r.Group("/", gin.BasicAuth(s.AppPasswd))
	auth.POST("/", s.processLogs)

	data := make([]byte, 1024)
	for _, tt := range fullTests {
		req, _ := http.NewRequest("POST", "/", bytes.NewBuffer([]byte(tt.Req)))
		req.SetBasicAuth("test", "pass")
		resp := httptest.NewRecorder()
		r.ServeHTTP(resp, req)

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			t.Error(err)
		}
		if string(body) != "OK" {
			t.Error("resp body should match")
		}
		if resp.Code != 200 {
			t.Error("should get a 200")
		}
		if tt.cnt != len(tt.Expected) {
			t.Error("Count of expected results isn't equal to inputs")
		}
		for i := 0; i < tt.cnt; i++ {
			n, err := server.Read(data)
			if err != nil {
				t.Fatal(err)
			}
			message := data[:n]
			findEqual := false

			for j := 0; j < len(tt.Expected); j++ {
				if string(message) == tt.Expected[j] {
					findEqual = true
				}
			}
			if findEqual == false {
				t.Errorf("Expected: %s. Actual: %s", tt.Expected[i], string(message))
			}
		}
	}

	time.Sleep(1 * time.Second)
}