当前位置: 首页>>代码示例>>Golang>>正文


Golang static.Serve函数代码示例

本文整理汇总了Golang中github.com/gin-gonic/contrib/static.Serve函数的典型用法代码示例。如果您正苦于以下问题:Golang Serve函数的具体用法?Golang Serve怎么用?Golang Serve使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Serve函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: main

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")

}
开发者ID:AccretionD,项目名称:QROrders_frontend,代码行数:33,代码来源:shop.go

示例2: Install

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
}
开发者ID:hverr,项目名称:status-dashboard,代码行数:49,代码来源:static.go

示例3: main

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)
	}
}
开发者ID:fmr,项目名称:kanban,代码行数:26,代码来源:main.go

示例4: main

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")
}
开发者ID:xinhuang327,项目名称:simple-monitor,代码行数:29,代码来源:main.go

示例5: main

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")
}
开发者ID:e0,项目名称:teacherMe,代码行数:57,代码来源:app.go

示例6: main

func main() {

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

	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")
}
开发者ID:rpoletaev,项目名称:dirty-chat,代码行数:57,代码来源:main.go

示例7: main

// 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")
}
开发者ID:doubledutch,项目名称:dd-vote,代码行数:14,代码来源:example.go

示例8: main

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"))
}
开发者ID:railsme,项目名称:go-by-examples,代码行数:10,代码来源:main.go

示例9: main

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()
}
开发者ID:theaidem,项目名称:ginplate,代码行数:41,代码来源:main.go

示例10: Service

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)))
	}
}
开发者ID:joelhawksley,项目名称:helios,代码行数:12,代码来源:static.go

示例11: main

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)

}
开发者ID:AlexGx,项目名称:pavo,代码行数:14,代码来源:main.go

示例12: Service

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
	}
}
开发者ID:begizi,项目名称:helios-server,代码行数:14,代码来源:static.go

示例13: init

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)
	})
}
开发者ID:gophergala2016,项目名称:kentia,代码行数:15,代码来源:router.go

示例14: Start

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
}
开发者ID:davidwinton,项目名称:feedbag,代码行数:46,代码来源:feedbag.go

示例15: main

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)
}
开发者ID:wadahiro,项目名称:gin-react-boilerplate,代码行数:17,代码来源:main.go


注:本文中的github.com/gin-gonic/contrib/static.Serve函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。