當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。