本文整理匯總了Golang中github.com/gin-gonic/gin.Default函數的典型用法代碼示例。如果您正苦於以下問題:Golang Default函數的具體用法?Golang Default怎麽用?Golang Default使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Default函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: NewWebServer
// NewWebServer : create and configure a new web server
func NewWebServer(c *Config, l *Store, level int) *WebHandler {
wh := &WebHandler{}
// create the router
if level == 0 {
gin.SetMode(gin.ReleaseMode)
wh.router = gin.New()
}
if level == 1 {
gin.SetMode(gin.ReleaseMode)
wh.router = gin.Default()
}
if level > 1 {
wh.router = gin.Default()
}
// bind the lease db
wh.store = l
// bind the config
wh.config = c
// bind the config to the file store
wh.fs = c.fs
// templates
// base os selector
t, err := template.New("list").Parse(OsSelector)
if err != nil {
logger.Critical("template error : %v", err)
return nil
}
// class selector
_, err = t.New("class").Parse(ClassSelector)
if err != nil {
logger.Critical("template error : %v", err)
return nil
}
wh.templates = t
// rocket handlers
wh.RocketHandler()
// chose and operating system
wh.router.GET("/choose", wh.Lister)
wh.router.GET("/choose/:dist/:mac", wh.Chooser)
wh.router.GET("/class/:dist/:mac", wh.ClassChooser)
wh.router.GET("/setclass/:dist/:class/:mac", wh.ClassSet)
// get the boot line for your operating system
wh.router.GET("/boot/:dist/:mac", wh.Starter)
// load the kernel and file system
wh.router.GET("/image/:dist/*path", wh.Images)
// serve the bin folder
wh.router.GET("/bin/*path", wh.Binaries)
// actions for each distro
wh.router.GET("/action/:dist/:action", wh.Action)
// configs for each distro
wh.router.GET("/config/:dist/:action", wh.Config)
if wh.config.Spawn {
wh.SpawnHandler()
}
return wh
}
示例2: main
func main() {
port := flag.Int("port", 8080, "port")
backends := flag.String("workers", "", "knonw workers (ex: 'localhost:8081,localhost:8082')")
strategy := flag.String("strategy", "majority", "balancing strategy ['one', 'two', 'majority', 'all']")
poolSize := flag.Int("pool", 3, "size of the pool of available worker sets")
flag.Parse()
cfg := profile.Config{
CPUProfile: true,
MemProfile: true,
ProfilePath: ".",
}
p := profile.Start(&cfg)
defer p.Stop()
proxy := Proxy{NewBalancer(initListOfBckends(backends), strategy, poolSize)}
server := gin.Default()
server.GET("/", func(c *gin.Context) {
pipes := &Pipes{
Done: make(chan struct{}),
Result: make(chan *DataFormat),
}
go proxy.ProcessFirstResponse(pipes)
defer close(pipes.Done)
select {
case data := <-pipes.Result:
c.JSON(200, data)
case <-time.After(globalTimeout):
c.JSON(500, nil)
}
})
go func() {
admin := gin.Default()
admin.POST("/worker/*endpoint", func(c *gin.Context) {
worker := c.Param("endpoint")
done := make(chan struct{})
go proxy.AddBackend(fmt.Sprintf("http:/%s/", worker), done)
select {
case <-done:
c.String(200, "")
case <-time.After(globalTimeout):
c.String(500, "")
close(done)
}
})
admin.Run(fmt.Sprintf(":%d", *port-10))
}()
server.Run(fmt.Sprintf(":%d", *port))
}
示例3: runHttpServer
func runHttpServer() {
router := gin.Default()
router.GET("/", handleGetServices)
router.GET("/services", handleGetServices)
router.GET("/services/:name", handleGetService)
router.Run("0.0.0.0:5000")
}
示例4: main
func main() {
// fire this up
router := gin.Default()
router.Use(gin.Logger())
// load the dang templates
router.LoadHTMLGlob("templates/*.html")
// router.Use(static.Serve("/static", static.LocalFile("html", false)))
router.Static("/static", "static")
// handle root
router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "wat")
})
// check the incoming phrase
router.GET("/blink/:phrase", func(c *gin.Context) {
phrase := c.Param("phrase")
c.HTML(http.StatusOK, "main.html", gin.H{
"title": phrase,
"phrase": phrase,
"twitter_handle": "mike_dory",
"google_analytics_id": "XXXXX-XX",
})
})
// run!
router.Run(":8081")
}
示例5: setup
func setup() {
database.Open("testing.db")
timeStamp, _ := time.Parse(time.RFC3339Nano, "2015-11-19T12:19:33.865042825+01:00")
items := []*model.Item{
&model.Item{
Code: "url",
Type: model.URLItemType,
Content: "https://ariejan.net",
CreatedAt: timeStamp,
},
&model.Item{
Code: "txt",
Type: model.TextItemType,
Content: "Lorem ipsum",
CreatedAt: timeStamp,
},
}
for _, item := range items {
database.SaveItem(item)
}
router = gin.Default()
web.Setup(router.Group("/"), database)
}
示例6: main
func main() {
//move this into an env
dsn := "homestead:[email protected](localhost:33060)/wheniwork?charset=utf8&parseTime=True&loc=Local"
repository, err := wiw.NewMySQLRepo(dsn)
if err != nil {
log.Println("ERROR: Cannot build repository")
log.Println(err)
log.Fatal("Exiting...")
return
}
router := gin.Default()
schedulerAPI := schedulerService{repository}
authMiddleware := router.Group("/", schedulerAPI.Authorization)
setIDMiddleware := authMiddleware.Group("/", schedulerAPI.ValidateID)
authMiddleware.POST("/shifts/", schedulerAPI.CreateOrUpdateShift)
setIDMiddleware.PUT("/shifts/:id", schedulerAPI.CreateOrUpdateShift)
authMiddleware.GET("/shifts/", schedulerAPI.ViewShiftsByDate)
setIDMiddleware.GET("/users/:id/shifts/", schedulerAPI.ViewShiftsForUser)
setIDMiddleware.GET("/users/:id/colleagues/", schedulerAPI.ViewColleagues)
setIDMiddleware.GET("/users/:id/managers", schedulerAPI.ViewManagers)
setIDMiddleware.GET("/users/:id", schedulerAPI.ViewUser)
router.Run(":3001")
}
示例7: Run
// Run runs the app
func (app *Application) Run() error {
r := gin.Default()
r.LoadHTMLGlob("templates/*")
// inject Config into context
r.Use(func(c *gin.Context) {
c.Set("cfg", app.Config)
c.Next()
})
// CSRF
r.Use(wraphh.WrapHH(nosurf.NewPure))
r.Static(app.Options.StaticURL, app.Options.StaticDir)
r.GET("/", indexPage)
api := r.Group("/api")
api.GET("/all/", getMovies)
api.GET("/", getRandomMovie)
api.POST("/", addMovie)
api.GET("/suggest", suggest)
api.GET("/movie/:id", getMovie)
api.DELETE("/movie/:id", deleteMovie)
api.PATCH("/seen/:id", markSeen)
r.Run()
return nil
}
示例8: main
func main() {
// prepare host:port to listen to
bind := fmt.Sprintf("%s:%s", "", "8000")
// just predefine the err variable to avoid some problems
var err error
// create an instance of Telegram Bot Api
bot, err = telegram.NewBotAPI(BOTAPIKEY)
if err != nil {
log.Panic(err)
}
// Compile the regexpression to match /[email protected]
actionSeprator := regexp.MustCompile(`^\/[\[email protected]]+`)
// prepare the Gin Router
router := gin.Default()
// on request
router.POST("/", func(c *gin.Context) {
buf, err := ioutil.ReadAll(c.Request.Body)
update := telegram.Update{}
json.Unmarshal(buf, &update)
if err != nil {
c.String(500, err.Error())
return
}
// Extracting action name from text
botName := ""
act := actionSeprator.FindString(update.Message.Text)
actLength := len(act)
atsignPos := strings.Index(act, "@")
if atsignPos != -1 {
botName = act[atsignPos+1:]
act = act[:atsignPos]
}
if botName != "" && botName != BOTNAME {
c.String(200, "Wrong bot")
return
}
act = strings.TrimPrefix(act, "/")
act = strings.ToLower(act)
update.Message.Text = update.Message.Text[actLength:]
// check if the requested action exist or not
_, has := actions[act]
if has {
err = actions[act](c, &update)
if err != nil {
c.String(500, err.Error())
return
}
}
c.String(200, "done")
})
router.Run(bind)
}
示例9: main
func main() {
r := gin.Default()
r.GET("/long_async", func(c *gin.Context) {
// create copy to be used inside the goroutine
cCp := c.Copy()
go func() {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
// note than you are using the copied context "c_cp", IMPORTANT
log.Println("Done! in path " + cCp.Request.URL.Path)
}()
})
r.GET("/long_sync", func(c *gin.Context) {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
// since we are NOT using a goroutine, we do not have to copy the context
log.Println("Done! in path " + c.Request.URL.Path)
})
// Listen and server on 0.0.0.0:8080
r.Run(":8080")
}
示例10: route
func route() {
// If we're in production mode don't run gin in develop
if *production {
gin.SetMode(gin.ReleaseMode)
}
// Create new router
router = gin.Default()
// Compile html templates
router.LoadHTMLGlob("app/html/*.html")
// Add all routes
addRoutes()
// Add static routes
router.Static("/", "./public/")
// Create http server based off of net/http
addr := fmt.Sprintf("%s:%d", *host, *port)
s := &http.Server{
Addr: addr,
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
// Log
log.Fatal(s.ListenAndServe())
}
示例11: main
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
r.Run(":3000")
}
示例12: main
func main() {
router := gin.Default()
usf4Map := TitleMap{name: "usf4", characterMap: BuildData("usf4")}
router.GET("/:title/:name", func(context *gin.Context) {
switch title := context.Param("title"); title {
case "usf4":
name := context.Param("name")
if strings.EqualFold(name, "characters") {
context.JSON(200, gin.H{
"names": CharacterNames(title),
})
} else {
character, characterFound := usf4Map.characterMap[name]
if !characterFound {
context.JSON(404, gin.H{
"message": "character not found",
})
}
context.String(200, character.data)
}
case "sfv":
context.JSON(501, gin.H{
"message": "coming soon",
})
default:
context.JSON(404, gin.H{
"message": "title not found",
})
}
})
router.Run(":8080")
}
示例13: main
func main() {
r := gin.Default()
g := r.Group("/i", func(c *gin.Context) {
c.Header("Cache-Control", "max-age=315360000")
})
g.GET("/g/:name", func(c *gin.Context) {
name := c.Param("name")
queryWidth := c.DefaultQuery("w", "512")
queryMargin := c.DefaultQuery("m", "32")
width, err := strconv.Atoi(queryWidth)
margin, err2 := strconv.Atoi(queryMargin)
if err != nil || err2 != nil {
log.Println(err, err2)
c.AbortWithError(http.StatusInternalServerError, errors.New("Invalid parameters"))
return
}
GenerateGitHub(c, name, width, margin)
})
g.GET("/8/:gender/:name", Generate8bit)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
r.Run(":" + port)
}
示例14: main
func main() {
mux := http.NewServeMux()
Admin.MountTo("/admin", mux)
// frontend routes
router := gin.Default()
router.LoadHTMLGlob("templates/*")
// serve static files
router.StaticFS("/system/", http.Dir("public/system"))
router.StaticFS("/assets/", http.Dir("public/assets"))
// books
bookRoutes := router.Group("/books")
{
// listing
bookRoutes.GET("", controllers.ListBooksHandler)
bookRoutes.GET("/", controllers.ListBooksHandler) // really? i need both of those?...
// single book - product page
bookRoutes.GET("/:id", controllers.ViewBookHandler)
}
mux.Handle("/", router)
// handle login and logout of users
mux.HandleFunc("/login", controllers.LoginHandler)
mux.HandleFunc("/logout", controllers.LogoutHandler)
// start the server
http.ListenAndServe(":9000", mux)
}
示例15: Init
func Init() {
if router == nil {
gin.SetMode(gin.TestMode)
router = gin.Default()
templ := template.New("index")
router.SetHTMLTemplate(templ)
store := sessions.NewCookieStore([]byte("foundation"))
router.Use(sessions.Sessions("foundation", store))
portNo := 0
go func() {
router.GET("/", func(c *gin.Context) {
shared = *c
})
for portNo = 8124; true; portNo++ {
addr := fmt.Sprintf(`:%d`, portNo)
err := router.Run(addr)
if err != nil {
if strings.HasSuffix(err.Error(), `address already in use`) {
continue
}
}
break
}
}()
time.Sleep(50 * time.Millisecond)
http.Get(fmt.Sprintf("http://localhost:%d/", portNo)) // portNoが0じゃなくなるまでwaitしたほうが良い気もするが一旦
}
}