Example #1
1
func main() {
	r := gin.Default()

	// if Allow DirectoryIndex
	r.Use(static.Serve("/request/", static.LocalFile("./app", true)))
	r.Use(static.Serve("/todo/", static.LocalFile("./todo", true)))

	// set prefix
	r.Use(static.Serve("/static", static.LocalFile("./app", true)))
	r.Use(static.Serve("/static", static.LocalFile("./todo", true)))

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

	// Setup Socket.io server and related activity fetching
	socketServer, err := SetupSocketIO()
	if err != nil {
		logging.ErrorWithTags([]string{"socket.io"}, "Error on socket.io server", err.Error())

	}

	r.GET("/socket.io/", func(c *gin.Context) {
		socketServer.ServeHTTP(c.Writer, c.Request)
	})
	// redis configuration
	flag.Parse()

	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")

}
Example #2
0
func (s *Static) Install(engine *gin.Engine) error {
	var err error
	var root string

	fs, err := LoadAssetFileSystem("/dist", true)
	if err == nil {
		log.Println("Serving static content from binary")
		engine.Use(static.Serve("/", fs))

	} else {
		log.Println("warning: could not read assets from binary:", err)

		toTry := []string{
			settings.StaticAppRoot,
			"./dist",
		}
		if envRoot := os.Getenv("HTML_ROOT"); envRoot != "" {
			toTry = append([]string{envRoot}, toTry...)
		}

		for _, path := range toTry {
			if _, err = os.Stat(path); err != nil {
				log.Println("warning: could not serve from", path)
			} else {
				root = path
				break
			}
		}

		if err != nil {
			return err
		}

		log.Println("Serving static content from", root)

		prefix := "/"
		fs := static.LocalFile(root, true)
		staticHandler := static.Serve(prefix, fs)
		engine.Use(func(c *gin.Context) {
			if fs.Exists(prefix, c.Request.URL.Path) {
				if s.UserAuthenticator.BasicAuthForUser(c) {
					staticHandler(c)
				}
			}
		})
	}

	return nil
}
Example #3
0
File: main.go Project: fmr/kanban
func main() {

	flag.Parse()

	r := gin.Default()

	r.LoadHTMLGlob("templates/*")

	r.Use(static.Serve("/static", static.LocalFile("static", false)))

	dbx, err := sqlx.Connect("sqlite3", *dbName)

	if err != nil {
		log.Fatal(err)
	}

	api.New(r, "/api/v1", db.New(dbx))

	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{"env": *env})
	})

	if err := r.Run(":" + *port); err != nil {
		panic(err)
	}
}
Example #4
0
func main() {
	fmt.Println("Monitor Service starting...")
	r := gin.Default()

	r.Use(static.Serve("/", static.LocalFile("static", true)))

	r.GET("/api/GetServerGroups", func(c *gin.Context) {
		groups, err := ReadData()
		if err == nil {
			groups = FillPublishInfo(groups) // Get publish info
			c.JSON(200, groups)
		} else {
			c.String(500, "ReadData error: "+err.Error())
		}
	})

	r.POST("/api/SaveServer", func(c *gin.Context) {
		var s Server
		if err := c.BindJSON(&s); err == nil {
			UpdateData(s)
			c.String(200, "OK")
		} else {
			c.String(500, "BindJSON error: "+err.Error())
		}
	})

	fmt.Println("Monitor Service started!")
	r.Run(":8080")
}
Example #5
0
File: app.go Project: e0/teacherMe
func main() {
	controller.SetSession()

	router := gin.Default()

	router.Use(static.Serve("/", static.LocalFile("../front_end/", true)))

	publicAPI := router.Group("/api/public")
	privateAPI := router.Group("/api/private")
	privateAPI.Use(jwt.Auth(getDecodedSecret()))

	publicAPI.GET("/courses", func(c *gin.Context) {
		courses, err := controller.FetchAllCourses()

		if err != nil {
			fmt.Println(err)
		}

		c.JSON(200, helper.GetJSONFormat(courses))
	})

	privateAPI.POST("/course_create", func(c *gin.Context) {
		data, _ := ioutil.ReadAll(c.Request.Body)
		courseID := controller.CreateCourse(data)
		authToken := c.Request.Header.Get("Authorization")

		if controller.UpdateUser(courseID, configFile["Auth0BaseURL"], authToken) == 200 {
			c.JSON(200, gin.H{"courseID": courseID})
		} else {
			c.JSON(400, gin.H{"error": "Course creation failed."})
		}
	})

	privateAPI.POST("/course_update", func(c *gin.Context) {
		data, _ := ioutil.ReadAll(c.Request.Body)
		courseID := controller.UpdateCourse(data)

		if courseID != "" {
			c.JSON(200, gin.H{"courseID": courseID})
		} else {
			c.JSON(400, gin.H{"error": "Course update failed."})
		}
	})

	publicAPI.GET("/course/:courseID", func(c *gin.Context) {
		courseID := c.Param("courseID")
		course, err := controller.FetchCourse(courseID)

		if err != nil {
			fmt.Println(err)
		}

		c.JSON(200, helper.GetJSONFormat(course))
	})

	router.Run(":8081")
}
Example #6
0
func main() {

	r := gin.Default()
	settings := mongo.ConnectionURL{
		Address:  db.Host("ds031763.mongolab.com:31763"), // MongoDB hostname.
		Database: "dirty-chat",                           // Database name.
		User:     "******",                              // Optional user name.
		Password: "******",
	}

	var err error

	Mng, err = db.Open(mongo.Adapter, settings)
	if err != nil {
		fmt.Println(err.Error())
	}

	defer Mng.Close()

	Store = sessions.NewCookieStore([]byte("nebdr84"))
	r.Use(sessions.Middleware("my_session", Store))
	r.Use(csrf.Middleware(csrf.Options{Secret: "nebdr84", IgnoreMethods: []string{"GET"}}))
	r.Use(static.Serve("/", static.LocalFile("assets", false)))
	r.Use(AuthInspector())
	r.Use(GlobalResources())
	rnd = render.New(render.Options{
		Directory:       "templates",                 // Specify what path to load the templates from.
		Layout:          "layout",                    // Specify a layout template. Layouts can call {{ yield }} to render the current template or {{ block "css" }} to render a block from the current template
		Extensions:      []string{".tmpl", ".html"},  // Specify extensions to load for templates.
		Delims:          render.Delims{"{[{", "}]}"}, // Sets delimiters to the specified strings.
		Charset:         "UTF-8",                     // Sets encoding for json and html content-types. Default is "UTF-8".
		IndentJSON:      true,                        // Output human readable JSON.
		IndentXML:       false,
		PrefixJSON:      []byte(")]}',\n"), // Prefixes JSON responses with the given bytes.
		HTMLContentType: "text/html",       // Output XHTML content type instead of default "text/html".
		IsDevelopment:   true,              // Render will now recompile the templates on every HTML response.
		UnEscapeHTML:    true,              // Replace ensure '&<>' are output correctly (JSON only).
		StreamingJSON:   true,              // Streams the JSON response via json.Encoder.
	})

	r.LoadHTMLGlob("templates/*.html")

	r.Any("/", indexHandler)
	r.GET("/login", ShowLogin)
	r.POST("/login", Login)
	// r.GET("user/:name", controllers.ShowUser)
	//r.POST("user/:name", controllers.EditUser)

	r.GET("/sex", controllers.IndexSex)
	r.GET("/sex/:name/:edit", controllers.EditSex)
	r.DELETE("/sex/:name", controllers.DeleteSex)
	r.POST("/sex", controllers.CreateSex)
	r.POST("/sex/:name", controllers.UpdateSex)
	r.GET("/sex.json", controllers.IndexSexJson)

	r.Run(":3000")
}
Example #7
0
// Usage
// $ go-bindata data/
// $ go build && ./bindata
//
func main() {
	r := gin.Default()

	r.Use(static.Serve("/static", BinaryFileSystem("data")))
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "test")
	})
	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}
Example #8
0
func main() {
	r := gin.Default()
	r.Use(static.Serve("/", static.LocalFile("static", false)))
	r.StaticFile("/", "static/index.html")
	api := r.Group("/api")
	api.GET("/items", func(c *gin.Context) {
		c.JSON(200, &items)
	})
	r.Run(":" + os.Getenv("PORT"))
}
Example #9
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()
}
Example #10
0
func Service() helios.ServiceHandler {
	return func(h *helios.Engine) {
		publicDir := "public"

		if h.Config.IsSet("publicDir") {
			publicDir = h.Config.GetString("publicDir")
		}

		// Setup static file server on HTTPEngine
		h.HTTPEngine.Use(static.Serve("/", static.LocalFile(publicDir, true)))
	}
}
Example #11
0
File: main.go Project: AlexGx/pavo
func main() {
	flag.Parse()

	r := gin.Default()
	r.Use(CORSMiddleware())
	r.Use(static.Serve("/", static.LocalFile(*storage, false)))

	r.POST("/files", CreateAttachment)

	log.Printf("Storage place in: %s", *storage)
	log.Printf("Start server on %s", *host)
	r.Run(*host)

}
Example #12
0
func Service() helios.ServiceHandler {
	return func(h *helios.Engine) error {
		publicDir := "public"

		if len(os.Getenv("PUBLIC")) > 0 {
			publicDir = os.Getenv("PUBLIC")
		}

		// Setup static file server on HTTPEngine
		h.HTTPEngine.Use(static.Serve("/", static.LocalFile(publicDir, true)))

		return nil
	}
}
Example #13
0
func init() {
	gin.SetMode(gin.DebugMode)
	rand.Seed(time.Now().UnixNano())
	servidor = gin.Default()

	store := sessions.NewCookieStore([]byte("ef7fbfd3d599befe7a86cbf37c8f05c814dcad918b8dbefb441de846c4f62ea3"))
	servidor.Use(sessions.Sessions("mysession", store))

	cargarTemplates()
	servidor.Use(static.Serve("/", static.LocalFile("./public", false)))
	servidor.StaticFile("/login", "./public/index.html")
	servidor.NoRoute(func(c *gin.Context) {
		html.ExecuteTemplate(c.Writer, "404.html", nil)
	})
}
Example #14
0
func main() {
	r := gin.Default()

	// if Allow DirectoryIndex
	//r.Use(static.Serve("/", static.LocalFile("/tmp", true)))
	// set prefix
	//r.Use(static.Serve("/static", static.LocalFile("/tmp", true)))

	r.Use(static.Serve("/", static.LocalFile("/tmp", false)))
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "test")
	})
	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}
Example #15
0
func Start(port, templatesDir string, publicDir string) error {
	dbmap = setupDb()
	defer dbmap.Db.Close()

	// Process our templates
	TemplatesDir = templatesDir
	var err error
	Templates, err = tmpl.ParseDir(TemplatesDir)
	if err != nil {
		logging.ErrorWithTags([]string{"templates"}, "Failed to parse templates", err.Error())
		return err
	}

	// Setup Goth Authentication
	goth.UseProviders(
		github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:3000/auth/github/callback", "repo", "user:email"),
	)

	// Setup Socket.io server and related activity fetching
	socketServer, err := SetupSocketIO()
	if err != nil {
		return err
	}

	err = StartSocketPusher(socketServer, activityChan)
	if err != nil {
		return err
	}

	err = StartExistingUsers(activityChan)
	if err != nil {
		return err
	}

	// Start up gin and its friends
	r := gin.Default()
	r.Use(cors.Middleware(cors.Options{AllowCredentials: true}))

	// Serve static assets
	r.Use(static.Serve("/", static.LocalFile(publicDir, false)))

	SetupRoutes(r, socketServer)
	r.Run(fmt.Sprintf(":%s", port))

	return nil
}
Example #16
0
func main() {
	r := gin.Default()

	// We can't use router.Static method to use '/' for static files.
	// see https://github.com/gin-gonic/gin/issues/75
	// r.StaticFS("/", assetFS())
	r.Use(static.Serve("/", BinaryFileSystem("assets")))

	// add routes
	r.GET("/api/home", controllers.Home)

	port := os.Getenv("PORT")
	if len(port) == 0 {
		port = "3000"
	}
	r.Run(":" + port)
}
Example #17
0
func main() {
	gin.SetMode(gin.ReleaseMode)
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	m := gin.Default()

	m.Use(static.Serve("/", static.LocalFile("static", true)))
	m.GET(`/potresi.json`, func(c *gin.Context) {
		c.JSON(200, ARSOPotresi())
		return
	})

	m.GET(`/postaje.json`, func(c *gin.Context) {
		c.JSON(200, ARSOVreme())
		return
	})

	m.GET(`/vreme/:postaja`, func(c *gin.Context) {
		name := c.Param("postaja")
		for _, p := range ARSOVreme() {
			if name == p.ID {
				c.JSON(200, p)
				return
			}
		}
		c.JSON(404, gin.H{"Status": "Not found: " + name})
		return
	})

	m.GET(`/potresi.xml`, func(c *gin.Context) {
		c.XML(200, ARSOPotresi())
		return
	})

	m.GET(`/postaje.xml`, func(c *gin.Context) {
		c.XML(200, ARSOVreme())
		return
	})

	m.Run(":" + port)
}
func main() {

	router := gin.Default()

	router.Use(static.Serve("/", static.LocalFile("webfiles", false)))

	router.LoadHTMLGlob("webfiles/*.html")

	// set up a redirect for /
	router.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "/home")
	})

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

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

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

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

	router.POST("/login", func(c *gin.Context) {
		Username := c.PostForm("Username")
		Password := c.PostForm("Password")

		fmt.Printf("Username: %s, Password: %s is logged in",
			Username, Password)
	})

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

	router.Run(":8000")
}
Example #19
0
func realMain(c *cli.Context) {
	rand.Seed(time.Now().UnixNano())

	lvl, err := log.ParseLevel(c.String("loglevel"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Could not parse log level. Must be one of: debug, info, warning, error, panic, fatal\n")
		os.Exit(1)
	}

	formatter := &LogFormatter{}
	log.SetFormatter(formatter)
	log.SetOutput(os.Stderr)
	log.SetLevel(lvl)

	db, err = gorm.Open("sqlite3", c.String("database"))
	if err != nil {
		log.Fatalf("Could not open database from %s: %s", c.String("database"), err)
	}
	defer db.Close()

	if c.Bool("sqldebug") {
		db.LogMode(true)
	}

	db.AutoMigrate(&Paste{})
	log.Debug("Database init done")

	if pygpath, err = exec.LookPath("pygmentize"); err != nil {
		log.Fatalf("You do not appear to have Pygments installed. Please install it!")
	}
	setupPyg()

	r := gin.Default()
	r.LoadHTMLGlob(c.String("templates") + "/*")
	r.Use(static.Serve("/static", static.LocalFile(c.String("assets"), true)))
	r.GET("/", index)
	r.POST("/", storePaste)
	r.GET("/raw", index)

	log.Warningf("Priggr serving on %s:%d", c.String("bind"), c.Int("port"))
	r.Run(fmt.Sprintf("%s:%d", c.String("bind"), c.Int("port")))
}
Example #20
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)
}
Example #21
0
func main() {
	// Test Cfg
	eng := gin.Default()
	eng.POST("hook/github", func(c *gin.Context) {
		sig := c.Request.Header.Get("X-Hub-Signature")
		sig = sig[5:]
		mac := hmac.New(sha1.New, []byte(Secret))
		io.Copy(mac, c.Request.Body)
		expectedMAC := mac.Sum(nil)
		msgSig := hex.EncodeToString(expectedMAC)
		if !hmac.Equal([]byte(msgSig), []byte(sig)) {
			fmt.Println("Signature Error")
			return
		}
		githubPushUpdate()
	})
	eng.Use(static.Serve("/", static.LocalFile("site", false)))

	eng.Run("0.0.0.0:8083")
}
Example #22
0
func main() {
	appConfig := config.GetConfig()

	r := gin.Default()
	/**
	 * load in all html the templates
	 */
	r.LoadHTMLGlob(appConfig.RootPath + "/server/views/*")
	/**
	 * register all the route handlers
	 */
	routes.RegisterRoutes(r)
	/**
	 * serve static files
	 * r.Static("/s", appConfig.RootPath+"/public")
	 */
	r.Use(static.Serve("/", static.LocalFile(appConfig.RootPath+"/public", false)))

	// Listen and server on 0.0.0.0:8080
	r.Run(fmt.Sprintf(":%d", appConfig.Port))
}
Example #23
0
func router(mCtr MetricsCtr) *gin.Engine {
	gin.SetMode(gin.ReleaseMode)

	router := gin.Default()
	//router.Use(cORSMiddleware())

	// Serve static
	router.Use(static.Serve("/", static.LocalFile("views", true)))

	// Base routes
	router.GET("/version", version)
	router.GET("/api", index)
	router.GET("/favicon.ico", favicon)

	// Authentication
	router.GET("/list", mCtr.ListMetrics)
	router.GET("/metrics/:metrics", mCtr.GetMetrics)
	router.GET("/metrics/:metrics/total", mCtr.GetTotalMetrics)

	return router
}
Example #24
0
func (self *Webserver) Start() error {
	go func() {
		gin.SetMode(gin.TestMode)

		r := gin.Default()
		r.LoadHTMLFiles("gui/public/index.html")
		r.StaticFS("/storage", http.Dir("storage"))

		r.GET("/", func(c *gin.Context) {
			c.HTML(200, "index.html", nil)
		})

		r.GET("/socket", func(c *gin.Context) {
			Wshandler(c.Writer, c.Request, self.Hub)
		})

		r.Use(static.Serve("/", static.LocalFile("gui/public", false)))
		log.Infof("Webserver started at :%s", self.Port)
		r.Run(":" + self.Port)
	}()

	return nil
}
Example #25
0
/**
  Server initialization
*/
func InitHTTP() {

	// Get new router instance
	router := gin.Default()

	// Add API-like endpoint handler
	router.GET("/games", allGames)

	// Add websockets endpoint handler
	router.GET("/ws", func(c *gin.Context) {
		// Check auth headers here??
		handler := GetWsHandler()
		handler.ServeHTTP(c.Writer, c.Request)
	})

	// Serve static content
	router.Use(static.Serve("/", static.LocalFile("./res/html", true)))

	// Listen and log error if any
	if err := router.Run(":8080"); err != nil {
		log.Fatal(err.Error())
		os.Exit(2)
	}
}
Example #26
0
// main function
func main() {
	var err error
	// connect to database
	db, err = gorm.Open("mysql", os.Getenv("GO_MYSQL_URI"))
	if err != nil {
		panic(err)
	}
	//initialize it
	db.DB()

	app := cli.NewApp()
	app.Name = "Bookmarks-Gin"
	app.Usage = "Server for bookmarks-gin"
	app.Author = "Stefan Jarina"
	app.Email = "*****@*****.**"
	app.Version = "0.0.2"
	app.Action = func(clc *cli.Context) {
		// initialize gin
		r := gin.Default()

		// get current folder
		pwd, _ := filepath.Abs(filepath.Dir(os.Args[0]))

		// Serve AngularJS
		r.Use(static.Serve("/", static.LocalFile(fmt.Sprintf("%s/public", pwd), true)))

		// Handle login
		r.POST("/login", loginHandler)

		// v1 API routes
		v1 := r.Group("/api/v1", validateRequest)
		{
			v1.GET("/bookmarks", getBookmarks)
			v1.GET("/bookmarks/:id", getBookmark)
			v1.POST("/bookmarks", addBookmark)
			v1.PUT("/bookmarks/:id", updateBookmark)
			v1.DELETE("/bookmarks/:id", deleteBookmark)

			// v1 ADMIN API - Requires Authentication and Authorization - Only 'admin' allowed
			admin := v1.Group("admin", validateAdmin)
			{
				admin.GET("/users", getUsers)
				admin.GET("/users/:id", getUser)
				admin.POST("/users", addUser)
				admin.PUT("/users/:id", updateUser)
				admin.DELETE("/users/:id", deleteUser)
			}
		}

		// start up server
		if clc.Bool("socket") {
			l, err := net.Listen("unix", "/tmp/bookmarks-gin.sock")
			if err != nil {
				panic(err)
			}
			http.Serve(l, r)
		} else {
			r.Run(getAddrIP(clc))
		}
	}
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "ip",
			Usage: "Specify IP to which server should bind",
		},
		cli.StringFlag{
			Name:  "port",
			Usage: "Specify PORT application should bind to",
		},
		cli.BoolFlag{
			Name:  "socket",
			Usage: "Specify if SOCKET should be used",
		},
	}

	app.Commands = []cli.Command{
		{
			Name:  "initdb",
			Usage: "Initialize database with default admin user",
			Action: func(clc *cli.Context) {
				if clc.IsSet("password") {
					// create any new tables
					db.AutoMigrate(&User{}, &Bookmark{})
					CreateDBAdmin(clc)
				} else {
					fmt.Println("No password specified")
				}
			},
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "username",
					Value: "admin",
					Usage: "Set username for user with admin rights",
				},
				cli.StringFlag{
					Name:  "password",
					Usage: "Set password for user with admin rights",
				},
				cli.StringFlag{
					Name:  "first",
					Value: "Administrator",
					Usage: "Set first name for user with admin rights",
				},
				cli.StringFlag{
					Name:  "last",
					Value: "",
					Usage: "Set last name for user with admin rights",
				},
				cli.StringFlag{
					Name:  "email",
					Value: "*****@*****.**",
					Usage: "Set email for user with admin rights",
				},
			},
		},
	}

	app.Run(os.Args)
}
Example #27
0
func main() {
	// database setting
	user := os.Getenv("ISHOCON1_DB_USER")
	pass := os.Getenv("ISHOCON1_DB_PASSWORD")
	dbname := "ishocon1"
	db, _ = sql.Open("mysql", user+":"+pass+"@/"+dbname)
	db.SetMaxIdleConns(5)

	r := gin.Default()
	// load templates
	r.Use(static.Serve("/css", static.LocalFile("public/css", true)))
	r.Use(static.Serve("/images", static.LocalFile("public/images", true)))
	layout := "templates/layout.tmpl"

	// session store
	store := sessions.NewCookieStore([]byte("showwin_happy"))
	store.Options(sessions.Options{HttpOnly: true})
	r.Use(sessions.Sessions("mysession", store))

	// GET /login
	r.GET("/login", func(c *gin.Context) {
		session := sessions.Default(c)
		session.Clear()
		session.Save()

		tmpl, _ := template.ParseFiles("templates/login.tmpl")
		r.SetHTMLTemplate(tmpl)
		c.HTML(http.StatusOK, "login", gin.H{
			"Message": "ECサイトで爆買いしよう!!!!",
		})
	})

	// POST /login
	r.POST("/login", func(c *gin.Context) {
		email := c.PostForm("email")
		pass := c.PostForm("password")

		session := sessions.Default(c)
		user, result := authenticate(email, pass)
		if result {
			// 認証成功
			session.Set("uid", user.ID)
			session.Save()

			user.UpdateLastLogin()

			c.Redirect(http.StatusSeeOther, "/")
		} else {
			// 認証失敗
			tmpl, _ := template.ParseFiles("templates/login.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.HTML(http.StatusOK, "login", gin.H{
				"Message": "ログインに失敗しました",
			})
		}
	})

	// GET /logout
	r.GET("/logout", func(c *gin.Context) {
		session := sessions.Default(c)
		session.Clear()
		session.Save()

		tmpl, _ := template.ParseFiles("templates/login.tmpl")
		r.SetHTMLTemplate(tmpl)
		c.Redirect(http.StatusFound, "/login")
	})

	// GET /
	r.GET("/", func(c *gin.Context) {
		cUser := currentUser(sessions.Default(c))

		page, err := strconv.Atoi(c.Query("page"))
		if err != nil {
			page = 0
		}
		products := getProductsWithCommentsAt(page)
		// shorten description and comment
		var sProducts []ProductWithComments
		for _, p := range products {
			if utf8.RuneCountInString(p.Description) > 70 {
				p.Description = string([]rune(p.Description)[:70]) + "…"
			}

			var newCW []CommentWriter
			for _, c := range p.Comments {
				if utf8.RuneCountInString(c.Content) > 25 {
					c.Content = string([]rune(c.Content)[:25]) + "…"
				}
				newCW = append(newCW, c)
			}
			p.Comments = newCW
			sProducts = append(sProducts, p)
		}

		r.SetHTMLTemplate(template.Must(template.ParseFiles(layout, "templates/index.tmpl")))
		c.HTML(http.StatusOK, "base", gin.H{
			"CurrentUser": cUser,
			"Products":    sProducts,
		})
	})

	// GET /users/:userId
	r.GET("/users/:userId", func(c *gin.Context) {
		cUser := currentUser(sessions.Default(c))

		uid, _ := strconv.Atoi(c.Param("userId"))
		user := getUser(uid)

		products := user.BuyingHistory()

		var totalPay int
		for _, p := range products {
			totalPay += p.Price
		}

		// shorten description
		var sdProducts []Product
		for _, p := range products {
			if utf8.RuneCountInString(p.Description) > 70 {
				p.Description = string([]rune(p.Description)[:70]) + "…"
			}
			sdProducts = append(sdProducts, p)
		}

		r.SetHTMLTemplate(template.Must(template.ParseFiles(layout, "templates/mypage.tmpl")))
		c.HTML(http.StatusOK, "base", gin.H{
			"CurrentUser": cUser,
			"User":        user,
			"Products":    sdProducts,
			"TotalPay":    totalPay,
		})
	})

	// GET /products/:productId
	r.GET("/products/:productId", func(c *gin.Context) {
		pid, _ := strconv.Atoi(c.Param("productId"))
		product := getProduct(pid)
		comments := getComments(pid)

		cUser := currentUser(sessions.Default(c))
		bought := product.isBought(cUser.ID)

		r.SetHTMLTemplate(template.Must(template.ParseFiles(layout, "templates/product.tmpl")))
		c.HTML(http.StatusOK, "base", gin.H{
			"CurrentUser":   cUser,
			"Product":       product,
			"Comments":      comments,
			"AlreadyBought": bought,
		})
	})

	// POST /products/buy/:productId
	r.POST("/products/buy/:productId", func(c *gin.Context) {
		// need authenticated
		if notAuthenticated(sessions.Default(c)) {
			tmpl, _ := template.ParseFiles("templates/login.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.HTML(http.StatusForbidden, "login", gin.H{
				"Message": "先にログインをしてください",
			})
		} else {
			// buy product
			cUser := currentUser(sessions.Default(c))
			cUser.BuyProduct(c.Param("productId"))

			// redirect to user page
			tmpl, _ := template.ParseFiles("templates/mypage.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.Redirect(http.StatusFound, "/users/"+strconv.Itoa(cUser.ID))
		}
	})

	// POST /comments/:productId
	r.POST("/comments/:productId", func(c *gin.Context) {
		// need authenticated
		if notAuthenticated(sessions.Default(c)) {
			tmpl, _ := template.ParseFiles("templates/login.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.HTML(http.StatusForbidden, "login", gin.H{
				"Message": "先にログインをしてください",
			})
		} else {
			// create comment
			cUser := currentUser(sessions.Default(c))
			cUser.CreateComment(c.Param("productId"), c.PostForm("content"))

			// redirect to user page
			tmpl, _ := template.ParseFiles("templates/mypage.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.Redirect(http.StatusFound, "/users/"+strconv.Itoa(cUser.ID))
		}
	})

	// GET /initialize
	r.GET("/initialize", func(c *gin.Context) {
		db.Exec("DELETE FROM users WHERE id > 5000")
		db.Exec("DELETE FROM products WHERE id > 10000")
		db.Exec("DELETE FROM comments WHERE id > 200000")
		db.Exec("DELETE FROM histories WHERE id > 500000")

		c.String(http.StatusOK, "Finish")
	})

	r.Run(":8080")
}
Example #28
0
func main() {

	flag.Parse()

	r := gin.Default()
	r.LoadHTMLGlob("templates/*")
	r.Use(static.Serve("/static", static.LocalFile("static", false)))

	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"env":       *env,
			"apiPrefix": apiPrefix,
		})
	})

	api := r.Group(apiPrefix)

	posts := []*Post{
		&Post{1, "my first post", "hello"},
		&Post{2, "my next post", "hello again"},
	}

	api.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"posts": posts})
	})

	api.POST("/", func(c *gin.Context) {
		post := &Post{}
		if err := c.BindJSON(post); err != nil {
			c.AbortWithError(http.StatusBadRequest, err)
			return
		}
		post.ID = int64(len(posts) + 1)
		posts = append(posts, post)
		c.JSON(http.StatusOK, post)

	})

	api.GET("/:id", func(c *gin.Context) {

		id, err := strconv.ParseInt(c.Params.ByName("id"), 10, 64)

		if err != nil {
			c.AbortWithError(http.StatusBadRequest, err)
			return
		}

		for _, post := range posts {
			if post.ID == id {
				c.JSON(http.StatusOK, post)
				return
			}
		}

		c.String(http.StatusNotFound, "No post found")
	})

	if err := r.Run(":8080"); err != nil {
		panic(err)
	}
}
Example #29
0
func Run(wg sync.WaitGroup) {
	gin.SetMode(gin.ReleaseMode)

	router := gin.New()
	router.Use(gin.Logger())

	router.Use(static.Serve("/", static.LocalFile("/home/abrander/gocode/src/github.com/abrander/alerto/web/", false)))

	router.GET("/ws", func(c *gin.Context) {
		wshandler(c.Writer, c.Request)
	})

	a := router.Group("/agent")
	{
		a.GET("/", func(c *gin.Context) {
			c.JSON(200, plugins.AvailableAgents())
		})

	}

	h := router.Group("/host")
	{
		h.DELETE("/:id", func(c *gin.Context) {
			id := c.Param("id")

			err := monitor.DeleteHost(id)
			if err != nil {
				c.AbortWithError(500, err)
			} else {
				c.JSON(200, nil)
			}
		})

		h.POST("/new", func(c *gin.Context) {
			var host monitor.Host
			c.Bind(&host)
			err := monitor.AddHost(&host)
			if err != nil {
				c.AbortWithError(500, err)
			} else {
				c.JSON(200, host)
			}
		})

		h.GET("/", func(c *gin.Context) {
			c.JSON(200, monitor.GetAllHosts())
		})
	}

	m := router.Group("/monitor")
	{

		m.GET("/:id", func(c *gin.Context) {
			id := c.Param("id")

			mon, err := monitor.GetMonitor(id)
			if err == monitor.ErrorInvalidId {
				c.AbortWithError(400, err)
			} else if err != nil {
				c.AbortWithError(404, err)
			} else {
				c.JSON(200, mon)
			}
		})

		m.PUT("/:id", func(c *gin.Context) {
			var mon monitor.Monitor
			c.Bind(&mon)
			err := monitor.UpdateMonitor(&mon)
			if err != nil {
				c.AbortWithError(500, err)
			} else {
				c.JSON(200, mon)
			}
		})

		m.DELETE("/:id", func(c *gin.Context) {
			id := c.Param("id")

			err := monitor.DeleteMonitor(id)
			if err != nil {
				c.AbortWithError(500, err)
			} else {
				c.JSON(200, nil)
			}
		})

		m.POST("/new", func(c *gin.Context) {
			var mon monitor.Monitor
			c.Bind(&mon)
			err := monitor.AddMonitor(&mon)
			if err != nil {
				c.AbortWithError(500, err)
			} else {
				c.JSON(200, mon)
			}
		})

		m.GET("/", func(c *gin.Context) {
			c.JSON(200, monitor.GetAllMonitors())
		})
	}

	t := router.Group("/transport")
	{
		t.GET("/", func(c *gin.Context) {
			c.JSON(200, plugins.AvailableTransports())
		})
	}

	templ := template.Must(template.New("web/index.html").Delims("[[", "]]").ParseFiles("web/index.html"))
	router.SetHTMLTemplate(templ)

	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"sshPublicKey": ssh.PublicKey,
		})
	})

	router.Run(":9901")

	wg.Done()
}
Example #30
0
func main() {
	var listen string
	var dockerHost string
	var dockerTLSVerify bool
	var dockerCertPath string
	var debugMode bool
	var debugListen string
	var registryURL string
	var cachePath string
	var dsn string
	var sqlAdapter string

	flag.StringVar(&listen, "listen", ":3000", "host:port to listen on")
	flag.StringVar(&dockerHost, "docker-host", "unix:///var/run/docker.sock", "address of Docker host")
	flag.BoolVar(&dockerTLSVerify, "docker-tls-verify", false, "use TLS client for Docker")
	flag.StringVar(&dockerCertPath, "docker-cert-path", "", "path to the cert.pem, key.pem, and ca.pem for authenticating to Docker")
	flag.BoolVar(&debugMode, "debug", false, "enable /debug endpoints on DEBUG_LISTEN")
	flag.StringVar(&debugListen, "debug-listen", ":3001", "host:port to listen on for debug requests")
	flag.StringVar(&registryURL, "registry-url", "192.168.59.103:5000", "host:port of the registry for pushing images")
	flag.StringVar(&cachePath, "cache-path", "cache/", "path to the directory where cached repos will be stored")
	flag.StringVar(&dsn, "dsn", "file::memory:?cache=shared", "DSN string for connecting to the database")
	flag.StringVar(&sqlAdapter, "sql-adapter", "sqlite3", "adapter to use for the DSN string (currently only supports sqlite3)")
	flag.Parse()

	gin.DisableBindValidation()
	router := gin.Default()
	router.StaticFile("/", "static/index.html")
	router.Use(static.Serve("/", static.LocalFile("static", false)))

	client := dockerClient(dockerHost, dockerTLSVerify, dockerCertPath)
	db, err := sql.Open(sqlAdapter, dsn)
	if err != nil {
		panic(err)
	}
	buildRepo := builds.NewRepository(sqlAdapter, db)
	buildRepo.Migrate()
	logRepo := builds.NewLogRepository(sqlAdapter, db)
	logRepo.Migrate()
	streamRepo := streams.NewRepository()
	builder := builds.NewBuilder(registryURL, client, cachePath)
	buildQueue := builds.NewQueue(buildRepo, streamRepo, logRepo, builder)

	webhookHandler := api.NewWebhookHandler(buildRepo, buildQueue)
	router.POST("/webhooks/github", webhookHandler.Github)

	buildsResource := api.NewBuildsResource(buildRepo, buildQueue)
	router.GET("/builds", buildsResource.Index)
	router.POST("/builds", buildsResource.Create)
	router.GET("/builds/:id", buildsResource.Show)

	streamsResource := api.NewStreamsResource(buildRepo, streamRepo)
	router.GET("/builds/:id/streams/:type", streamsResource.Show)

	logsResource := api.NewLogsResource(buildRepo, logRepo)
	router.GET("/builds/:id/logs/:type", logsResource.Show)

	go buildQueue.Run()

	if debugMode {
		log.Println("Starting debug server on :3001")
		go http.ListenAndServe(debugListen, http.DefaultServeMux)
	}

	router.Run(listen)
}