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


Golang gin.Default函数代码示例

本文整理汇总了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
}
开发者ID:dardevelin,项目名称:astralboot,代码行数:59,代码来源:web.go

示例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))
}
开发者ID:alombarte,项目名称:gokatas,代码行数:56,代码来源:main.go

示例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")
}
开发者ID:sosedoff,项目名称:howdy,代码行数:7,代码来源:server.go

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

}
开发者ID:mikedory,项目名称:blink-go,代码行数:31,代码来源:app.go

示例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)
}
开发者ID:bubblebox,项目名称:server,代码行数:27,代码来源:web_suite_test.go

示例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")
}
开发者ID:ezeql,项目名称:wiw-scheduler-api,代码行数:28,代码来源:main.go

示例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
}
开发者ID:danjac,项目名称:random-movies,代码行数:33,代码来源:handlers.go

示例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)
}
开发者ID:emadgh,项目名称:TelegramBot,代码行数:60,代码来源:main.go

示例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")
}
开发者ID:SunChaoran,项目名称:helloGin,代码行数:26,代码来源:goroutines-inside-a-middleware.go

示例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())
}
开发者ID:lukevers,项目名称:converse,代码行数:31,代码来源:route.go

示例11: main

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})
	r.Run(":3000")
}
开发者ID:daine46,项目名称:go-test,代码行数:7,代码来源:main.go

示例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")
}
开发者ID:jpgnotgif,项目名称:fgframes.go,代码行数:34,代码来源:fgframes.go

示例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)
}
开发者ID:julianshen,项目名称:goticon,代码行数:35,代码来源:goticon.go

示例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)
}
开发者ID:bozzcq,项目名称:qor-example,代码行数:31,代码来源:main.go

示例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したほうが良い気もするが一旦
	}
}
开发者ID:gophergala2016,项目名称:source,代码行数:32,代码来源:context.go


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