當前位置: 首頁>>代碼示例>>Golang>>正文


Golang static.LocalFile函數代碼示例

本文整理匯總了Golang中github.com/gin-gonic/contrib/static.LocalFile函數的典型用法代碼示例。如果您正苦於以下問題:Golang LocalFile函數的具體用法?Golang LocalFile怎麽用?Golang LocalFile使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了LocalFile函數的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: 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

示例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() {
	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

示例5: 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

示例6: 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

示例7: 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

示例8: 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

示例9: 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

示例10: 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

示例11: 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

示例12: main

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")
}
開發者ID:doubledutch,項目名稱:dd-vote,代碼行數:15,代碼來源:example.go

示例13: 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

示例14: 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

示例15: 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


注:本文中的github.com/gin-gonic/contrib/static.LocalFile函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。