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


Golang gin.New函数代码示例

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


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

示例1: TestTeams

func TestTeams(t *testing.T) {
	gin.SetMode(gin.TestMode)
	logrus.SetOutput(ioutil.Discard)

	g := goblin.Goblin(t)

	g.Describe("Team endpoint", func() {
		g.It("Should return the team list", func() {
			cache := new(cache.Cache)
			cache.On("Get", "teams:octocat").Return(fakeTeams, nil).Once()

			e := gin.New()
			e.NoRoute(GetTeams)
			e.Use(func(c *gin.Context) {
				c.Set("user", fakeUser)
				c.Set("cache", cache)
			})

			w := httptest.NewRecorder()
			r, _ := http.NewRequest("GET", "/", nil)
			e.ServeHTTP(w, r)

			// the user is appended to the team list so we retrieve a full list of
			// accounts to which the user has access.
			teams := append(fakeTeams, &model.Team{
				Login: fakeUser.Login,
			})

			want, _ := json.Marshal(teams)
			got := strings.TrimSpace(w.Body.String())
			g.Assert(got).Equal(string(want))
			g.Assert(w.Code).Equal(200)
		})

		g.It("Should return a 500 error", func() {
			remote := new(remote.Remote)
			cache := new(cache.Cache)
			cache.On("Get", "teams:octocat").Return(nil, fmt.Errorf("Not Found")).Once()
			remote.On("GetTeams", fakeUser).Return(nil, fmt.Errorf("Not Found")).Once()

			e := gin.New()
			e.NoRoute(GetTeams)
			e.Use(func(c *gin.Context) {
				c.Set("user", fakeUser)
				c.Set("cache", cache)
				c.Set("remote", remote)
			})

			w := httptest.NewRecorder()
			r, _ := http.NewRequest("GET", "/", nil)
			e.ServeHTTP(w, r)

			got := strings.TrimSpace(w.Body.String())
			g.Assert(got).Equal("Error getting team list")
			g.Assert(w.Code).Equal(500)
		})
	})
}
开发者ID:jonbodner,项目名称:lgtm,代码行数:58,代码来源:teams_test.go

示例2: newServer

func newServer() *gin.Engine {
	g := gin.New()
	store := NewCookieStore([]byte("secret123"))
	g.Use(Middleware("my_session", store))

	return g
}
开发者ID:brainqi1991,项目名称:gin-sessions,代码行数:7,代码来源:sessions_test.go

示例3: Test_UpdateHandler

func Test_UpdateHandler(t *testing.T) {
	db := initTestDB(t)
	tasks, _, _ := fillTestDB(t, db)

	r := gin.New()
	r.PUT("/:id", gumtest.MockAuther(gumwrap.Gorp(Update, db), "1"))

	newTask := Task{
		ID:      tasks[0].ID,
		Name:    "Kill spider behind the mirror",
		Desc:    "buy poisen",
		Expires: tasks[0].Expires,
		Done:    false,
	}
	body, err := json.Marshal(newTask)
	if err != nil {
		t.Fatal(err)
	}
	resp := gumtest.NewRouter(r).ServeHTTP("PUT", "/1", string(body))
	expectResp := gumtest.JSONResponse{200, newTask}

	if err := gumtest.EqualJSONResponse(expectResp, resp); err != nil {
		t.Fatal(err)
	}

}
开发者ID:tochti,项目名称:tasks-lib,代码行数:26,代码来源:handler_test.go

示例4: main

func main() {
	r := gin.New()
	r.Use(gin.LoggerWithWriter(log.Writer()))
	r.Use(gin.RecoveryWithWriter(log.Writer()))

	tmpl, err := template.New("").Funcs(tmpl.TemplateFuncs).ParseGlob("templates/*")
	if err != nil {
		panic(err)
	}
	r.SetHTMLTemplate(tmpl)
	r.Static(path.Static("/"), "static")
	r.Static(path.Css("/"), "assets/css")
	r.Static(path.Js("/"), "assets/js")
	r.Static(path.Font("/"), "assets/fonts")
	r.NoRoute(ctl.Render404)

	r.GET(path.Root, posts.Index)
	r.GET(path.Posts, posts.Index)
	r.GET(path.NewPost, posts.New)
	r.POST(path.NewPost, posts.Create)
	r.GET(path.Post(":id"), posts.Show)
	r.GET(path.EditPost(":id"), posts.Edit)
	r.POST(path.EditPost(":id"), posts.Update)
	r.POST(path.DeletePost(":id"), posts.Destroy)

	r.GET(path.Register, users.New)
	r.POST(path.Register, users.Create)
	r.GET(path.Login, users.SessionNew)
	r.POST(path.Login, users.SessionCreate)
	r.GET(path.Logout, users.SessionDestroy)

	r.Run(":8080")
}
开发者ID:yamnikov-oleg,项目名称:gin-sample,代码行数:33,代码来源:main.go

示例5: main

func main() {

	ROOT_DIR, _ = osext.ExecutableFolder()
	config.LoadConfig(ge.BuildFullPath(ROOT_DIR, "config.json"))

	GE = ge.NewGalaxyEmpires(ge.BuildFullPath(ROOT_DIR, "data"), ge.CoordinatesStruct{1, 15, 5})

	r := gin.New()
	r.Use(gin.Logger())
	r.Use(gin.Recovery())
	r.Use(middleware.Errors("", "", nil))

	debug.AssignDebugHandlers(r.Group("/debug"))

	handlers.NewAccountHandler(r.Group("/account"), GE)
	handlers.NewPlayerHandler(r.Group("/player", middleware.Authentication([]byte(config.Config.Key))), GE)
	handlers.NewPlanetHandler(r.Group("/planet", middleware.Authentication([]byte(config.Config.Key))), GE)

	r.Static("/assets", ROOT_DIR+"/web/assets")
	r.StaticFile("/", ROOT_DIR+"/web/index.html")

	if err := r.Run(":" + config.Config.Port); err != nil {
		panic(err)
	}

}
开发者ID:nazwa,项目名称:Galaxy-Empires,代码行数:26,代码来源:main.go

示例6: main

func main() {

	//	当前目录
	rootDir := filepath.Dir(os.Args[0])

	//	设置配置文件
	err := config.SetRootDir(rootDir)
	if err != nil {
		log.Fatal(err)
		return
	}

	//	启动定时任务
	job.Start()

	//	http监听端口
	port := config.Int("http", "port", 9000)
	serverAddress := fmt.Sprintf(":%d", port)

	r := gin.New()
	r.Use(gin.Logger())

	//	注册路由
	RegisterRoute(r)

	r.Run(serverAddress) // listen and serve on 0.0.0.0:8080
}
开发者ID:nzai,项目名称:lottery,代码行数:27,代码来源:main.go

示例7: main

func main() {
	zalando.AccessTuples = []zalando.AccessTuple{{"teams", "Techmonkeys", "Platform Engineering / System"}}
	flag.Parse()
	router := gin.New()
	router.Use(ginglog.Logger(3 * time.Second))
	router.Use(ginoauth2.RequestLogger([]string{"uid"}, "data"))
	router.Use(gin.Recovery())

	public := router.Group("/api")
	public.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello to public world"})
	})

	private := router.Group("/api/private")
	privateUser := router.Group("/api/privateUser")
	glog.Infof("Register allowed users: %+v and groups: %+v", USERS, zalando.AccessTuples)
	private.Use(ginoauth2.Auth(zalando.GroupCheck, zalando.OAuth2Endpoint))
	privateUser.Use(ginoauth2.Auth(zalando.UidCheck, zalando.OAuth2Endpoint))
	private.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello from private for groups"})
	})
	privateUser.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello from private for users"})
	})

	glog.Info("bootstrapped application")
	router.Run(":8081")
}
开发者ID:anujwalia,项目名称:chimp,代码行数:28,代码来源:main.go

示例8: NewOpenVPNAuthd

// NewOpenVPNAuthd creates a new service for shipping out the openvpn config
func NewOpenVPNAuthd(cfg *AuthConfig) (OpenVPNAuthd, error) {
	//var err error

	glog.Infof("creating a new openvpn authd service, config: %s", cfg)

	service := new(openvpnAuthd)
	service.config = cfg

	// step: create the vault client
	glog.V(3).Infof("creating the vault client, address: %s, username: %s", cfg.VaultURL, cfg.VaultUsername)
	client, err := NewVaultClient(cfg.VaultURL, cfg.VaultCaFile, cfg.VaultTLSVerify)
	if err != nil {
		return nil, fmt.Errorf("failed to create a vault client, error: %s", err)
	}
	service.vault = client

	// step: attempt to authenticate to vault
	err = client.Authenticate(cfg.VaultUsername, cfg.VaultPassword)
	if err != nil {
		return nil, fmt.Errorf("failed to authenticate to vault, error: %s", err)
	}

	// step: create the gin router
	router := gin.New()
	router.LoadHTMLGlob("templates/*")
	router.Use(gin.Logger())
	router.Use(gin.Recovery())
	router.GET("/health", service.healthHandler)
	router.GET("/", service.openVPNHandler)

	service.router = router

	return service, nil
}
开发者ID:postfix,项目名称:openvpn-authd,代码行数:35,代码来源:server.go

示例9: loadGin

func loadGin(routes []route) http.Handler {
	router := gin.New()
	for _, route := range routes {
		router.Handle(route.method, route.path, []gin.HandlerFunc{ginHandle})
	}
	return router
}
开发者ID:kosuda,项目名称:go-http-routing-benchmark,代码行数:7,代码来源:routers.go

示例10: main

func main() {
	flag.Parse()

	common.Info("initializing metric http endpoint")
	connector, err := common.BuildRabbitMQConnector(*rabbitHost, *rabbitPort, *rabbitUser, *rabbitPassword, *rabbitExchange)
	if err != nil {
		log.Fatalln("error", err)
	}

	bindTo := fmt.Sprintf(":%d", *serverPort)

	common.Info("binding to:", bindTo)

	service := metricsService{connector: connector}

	gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.Use(gin.Recovery())
	r.POST("/metrics", service.createMetric)
	r.GET("/debug/vars", expvar.Handler())

	if err := r.Run(bindTo); err != nil {
		log.Fatalln(err)
	}
}
开发者ID:ezeql,项目名称:koding-challenge,代码行数:25,代码来源:main.go

示例11: StartGin

func StartGin() {
	gin.SetMode(gin.ReleaseMode)

	router := gin.New()
	gin.Logger()
	router.Use(rateLimit, gin.Recovery())
	router.Use(gin.Logger())
	router.LoadHTMLGlob("resources/*.templ.html")
	router.Static("/static", "resources/static")
	router.GET("/", MyBenchLogger(), index)
	router.GET("/auth", authentication.RequireTokenAuthentication(), index)
	router.POST("/test", controllers.Login)
	router.GET("/room/:name", roomGET)
	router.POST("/room-post/:roomid", roomPOST)
	router.GET("/stream/:roomid", streamRoom)

	//mongodb user create
	uc := user_controllers.NewUserController(getSession())
	router.GET("/user", uc.GetUser)
	router.GET("/message", uc.GetMessage)
	router.POST("/message", uc.CreateMessage)
	router.POST("/user", uc.CreateUser)
	router.DELETE("/user/:id", uc.RemoveUser)

	router.Run(":5001")

}
开发者ID:atyenoria,项目名称:gin-websocket-mongo-mysql-client-jwt-redis,代码行数:27,代码来源:main.go

示例12: main

func main() {
	gin.SetMode(gin.DebugMode)
	r := gin.New()

	r.GET("/:platform/*sourceurl", func(c *gin.Context) {
		platform := c.Params.ByName("platform")
		sourceurl := c.Params.ByName("sourceurl")[1:]

		v := url.Values{}
		var result string
		if platform == "sina" {
			v.Set("source", "")
			// v.Set("access_token", "")
			v.Set("url_long", sourceurl)
			log.Println(v.Encode())

			result = doPost(v.Encode(), "https://api.weibo.com/2/short_url/shorten.json")
		} else if platform == "baidu" {

		} else {
			result = platform + ": " + sourceurl
		}

		c.String(http.StatusOK, result)
	})

	r.Run(":8890")
}
开发者ID:top,项目名称:python,代码行数:28,代码来源:short_url.go

示例13: main

func main() {

	// Set Working direcotry
	_, filename, _, _ := runtime.Caller(0)
	var dir, _ = filepath.Split(filename)
	os.Chdir(dir)

	// Echo instance
	r := gin.New()

	// Global middleware
	r.Use(gin.Logger())
	r.Use(gin.Recovery())

	// Database
	r.Use(config.DbMw())

	// Sessions
	r.Use(config.SessionMw())

	// Templates
	//	config.SetRenderer(e)

	// Routes
	config.Routes(r)

	// Start server
	var port = ":3333"
	log.Println("HTTP Server running on port :3333!")
	r.Run(port)
}
开发者ID:LorenzV,项目名称:go-website-bootstrap,代码行数:31,代码来源:main.go

示例14: TestLogRequest

func TestLogRequest(t *testing.T) {

	s := loadServerCtx()
	s.AllowedApps = append(s.AllowedApps, "test")
	s.AppPasswd["test"] = "pass"

	s.in = make(chan *logData)
	defer close(s.in)
	s.out = make(chan *logMetrics)
	defer close(s.out)

	go logProcess(s.in, s.out)

	r := gin.New()
	auth := r.Group("/", gin.BasicAuth(s.AppPasswd))
	auth.POST("/", s.processLogs)

	req, _ := http.NewRequest("POST", "/", bytes.NewBuffer([]byte("LINE of text\nAnother line\n")))
	req.SetBasicAuth("test", "pass")
	resp := httptest.NewRecorder()
	r.ServeHTTP(resp, req)

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Error(err)
	}
	if string(body) != "OK" {
		t.Error("resp body should match")
	}

	if resp.Code != 200 {
		t.Error("should get a 200")
	}

}
开发者ID:apiaryio,项目名称:heroku-datadog-drain-golang,代码行数:35,代码来源:server_test.go

示例15: main

func main() {
	router := gin.New()
	router.LoadHTMLGlob("templates/*")
	router.Use(gin.Logger())
	router.Use(gin.Recovery())

	v1 := router.Group("/v1")
	// Example for binding JSON ({"user": "manu", "password": "123"})
	v1.POST("/loginJSON", func(c *gin.Context) {
		var json Login
		if c.BindJSON(&json) == nil {
			if json.User == "manu" && json.Password == "123" {
				c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			}
		}
	})

	router.GET("/login", func(c *gin.Context) {
		c.HTML(http.StatusOK, "loginform.tmpl", gin.H{
			"Title": "Login Page",
		})
	})

	// Example for binding a HTML form (user=manu&password=123)
	v1.POST("/loginForm", Hello(), Lolo)

	// Listen and server on 0.0.0.0:8080
	router.Run(":8080")
}
开发者ID:Antse,项目名称:testgin,代码行数:31,代码来源:main.go


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