• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang static.Serve函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: main

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)
}
开发者ID:ubuntu-si,项目名称:arso-api,代码行数:44,代码来源:main.go


示例17: main

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")
}
开发者ID:satishsa1107,项目名称:Go-GinGonic-Webserver,代码行数:43,代码来源:server.go


示例18: realMain

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


示例19: main

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


示例20: main

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")
}
开发者ID:Match-Yang,项目名称:developer-center,代码行数:20,代码来源:server.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang gin.BasicAuth函数代码示例发布时间:2022-05-23
下一篇:
Golang static.LocalFile函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap