コード例 #1
0
ファイル: teams_test.go プロジェクト: jonbodner/lgtm
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)
		})
	})
}
コード例 #2
0
func newServer() *gin.Engine {
	g := gin.New()
	store := NewCookieStore([]byte("secret123"))
	g.Use(Middleware("my_session", store))

	return g
}
コード例 #3
0
ファイル: handler_test.go プロジェクト: tochti/tasks-lib
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)
	}

}
コード例 #4
0
ファイル: main.go プロジェクト: yamnikov-oleg/gin-sample
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")
}
コード例 #5
0
ファイル: main.go プロジェクト: nazwa/Galaxy-Empires
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)
	}

}
コード例 #6
0
ファイル: main.go プロジェクト: nzai/lottery
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
}
コード例 #7
0
ファイル: main.go プロジェクト: anujwalia/chimp
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")
}
コード例 #8
0
ファイル: server.go プロジェクト: postfix/openvpn-authd
// 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
}
コード例 #9
0
func loadGin(routes []route) http.Handler {
	router := gin.New()
	for _, route := range routes {
		router.Handle(route.method, route.path, []gin.HandlerFunc{ginHandle})
	}
	return router
}
コード例 #10
0
ファイル: main.go プロジェクト: ezeql/koding-challenge
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)
	}
}
コード例 #11
0
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")

}
コード例 #12
0
ファイル: short_url.go プロジェクト: top/python
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")
}
コード例 #13
0
ファイル: main.go プロジェクト: LorenzV/go-website-bootstrap
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)
}
コード例 #14
0
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")
	}

}
コード例 #15
0
ファイル: main.go プロジェクト: Antse/testgin
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": "******", "password": "******"})
	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")
}
コード例 #16
0
ファイル: handler_test.go プロジェクト: tochti/gin-gum
func Test_SignIn_Fail(t *testing.T) {
	user := User{
		ID:       1,
		Username: "******",
		Password: "******",
	}
	userStore := TestUserStore{user}

	sess := gumtest.NewTestSession(
		"444",
		user.Username,
		time.Now().Add(1*time.Hour),
	)
	sessionStore := TestSessionStore{sess}

	r := gin.New()
	h := SignIn(sessionStore, userStore)
	r.GET("/:name/:password", h)

	name := base64.StdEncoding.EncodeToString([]byte(user.Username))
	pass := base64.StdEncoding.EncodeToString([]byte("wrong"))

	url := fmt.Sprintf("/%v/%v", name, pass)
	resp := gumtest.NewRouter(r).ServeHTTP("GET", url, "")

	if resp.Code != http.StatusUnauthorized {
		t.Fatalf("Expect %v was %v", http.StatusUnauthorized, resp.Code)
	}

}
コード例 #17
0
ファイル: api.go プロジェクト: Skullever/digo
// Listen Tells Gin API to start
func Listen(iface string, s *discordgo.Session, logger *logging.Logger) {
	// set the refs to point to main
	var v1 *gin.RouterGroup
	session = s
	c := config.Get()
	log = logger

	if c.LogLevel != "debug" {
		gin.SetMode(gin.ReleaseMode)
	}

	//r := gin.Default()
	r := gin.New()

	r.Use(loggerino())
	r.Use(gin.Recovery())

	if c.APIPassword != "" {
		log.Info("Basic Authentication enabled for API")
		v1 = r.Group("/v1", gin.BasicAuth(gin.Accounts{
			c.APIUsername: c.APIPassword,
		}))
	} else {
		log.Warning("DIGO_API_PASSWORD and DIGO_API_USERNAME are not set")
		log.Warning("The API is open to all requests")
		v1 = r.Group("/v1")
	}

	v1.GET("/version", versionV1)
	v1.GET("/channels", channelsV1)
	v1.POST("/message", messageV1)

	go r.Run(iface)
	log.Noticef("Digo API is listening on %s", c.APIInterface)
}
コード例 #18
0
ファイル: routes_test.go プロジェクト: sohlich/go-plag
//Sets gin to testing mode and presets the
//data storage to FakeDataStorage
//to emulate the database.
func preTest() (*gin.Engine, DataStorage) {
	gin.SetMode(gin.TestMode)
	oldMongo := mongo
	mongo = &FakeDataStorage{}
	router := gin.New()
	return router, oldMongo
}
コード例 #19
0
ファイル: server.go プロジェクト: sdvdxl/wine
func init() {
	//初始化gin处理引擎
	//	gin.SetMode(gin.ReleaseMode)
	g = gin.New()
	g.Use(HandlerError())

	{
		funcMap := template.FuncMap{"Equals": func(v1, v2 interface{}) bool {
			log.Logger.Debug("invoke function Equals")
			return v1 == v2
		}}
		tmp := template.New("myTemplate")
		templatePages := TemplatesFinder("templates")
		tmp.Funcs(funcMap).ParseFiles(templatePages...)

		g.SetHTMLTemplate(tmp)

		{ //这三个顺序不能变更,否则得不到正常处理
			//先设置/读取session信息
			g.Use(sessions.Sessions("my_session", session.SessionStore))

			//然后校验请求的URL
			g.Use(userauth.CheckLoginPage())

			//最后处理静态文件
			g.Use(static.ServeRoot("/", "static")) // static files have higher priority over dynamic routes

		}

	}
}
コード例 #20
0
ファイル: server_test.go プロジェクト: mitre/ptmatch
func (s *ServerSuite) TestEchoRoutes(c *C) {
	e := gin.New()

	h := func(*gin.Context) {}
	routes := []struct {
		Method string
		Path   string
	}{
		{"GET", "/RecordMatchContext"},
		{"GET", "/RecordMatchContext/:id"},
		{"POST", "/RecordMatchContext"},
		{"PUT", "/RecordMatchContext/:id"},
		{"DELETE", "/RecordMatchContext/:id"},
	}
	for _, r := range routes {
		switch r.Method {
		case "GET":
			e.GET(r.Path, h)
		case "PUT":
			e.PUT(r.Path, h)
		case "POST":
			e.POST(r.Path, h)
		case "DELETE":
			e.DELETE(r.Path, h)
		case "PATCH":
			e.PATCH(r.Path, h)
		}
	}

	for i, r := range e.Routes() {
		c.Assert(routes[i].Method, Equals, r.Method)
		c.Assert(routes[i].Path, Equals, r.Path)
	}
}
コード例 #21
0
ファイル: example.go プロジェクト: doubledutch/dd-vote
func main() {
	r := gin.New()

	// Add a ginrus middleware, which:
	//   - Logs all requests, like a combined access and error log.
	//   - Logs to stdout.
	//   - RFC3339 with UTC time format.
	r.Use(ginrus.Ginrus(logrus.StandardLogger(), time.RFC3339, true))

	// Add similar middleware, but:
	//   - Only logs requests with errors, like an error log.
	//   - Logs to stderr instead of stdout.
	//   - Local time zone instead of UTC.
	logger := logrus.New()
	logger.Level = logrus.ErrorLevel
	logger.Out = os.Stderr
	r.Use(ginrus.Ginrus(logger, time.RFC3339, false))

	// Example ping request.
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
	})

	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}
コード例 #22
0
ファイル: handler_test.go プロジェクト: theplant/resources
func TestProvideModel(t *testing.T) {
	r := Resource{}
	assertNoErr(db.Save(&r).Error)

	router = gin.New()
	router.GET("/r/:id", res.ProvideModel(func(c *gin.Context, s resources.DBModel) {
		if s == nil {
			t.Fatal("ProvideModel passed a nil DBModel")
		}
		c.String(200, "OK")
	}))

	tests := []struct {
		Code int
		ID   string
	}{
		{200, strconv.FormatUint(uint64(r.ID), 10)},
		// We only have one resource, so this shouldn't exist
		{404, strconv.FormatUint(uint64(r.ID+1), 10)},
		{404, "0"},
		{404, "not-an-id"},
	}

	for _, test := range tests {
		path := fmt.Sprintf("/r/%s", test.ID)
		res := doRequest(t, "GET", path, nil)

		if res.Code != test.Code {
			t.Fatalf("Error finding resource at %s, expected %d, got %d: %v", path, test.Code, res.Code, res)
		}
	}
}
コード例 #23
0
ファイル: server.go プロジェクト: oblank/forum
func Server() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	if _, err := database.InitDb(); err != nil {
		panic(err)
	}

	app := gin.New()
	app.Use(func(c *gin.Context) {
		c.Set(config.SecretKey, config.GetSecret())
		c.Next()
	})
	if config.GetEnv() != config.EnvProduction {
		app.Use(gin.Logger())
		app.Use(gin.Recovery())
	} else {
		app.Use(middleware.Recovery())
	}

	app.Use(middleware.ErrorHandler())
	app.Static("/public", "./public")
	//Set up api v1
	setupApiV1(app)

	env := config.GetEnvValue()
	app.Run(env.Server.Host + ":" + strconv.Itoa(env.Server.Port))
}
コード例 #24
0
ファイル: wiki.go プロジェクト: supermet/gowiki
func init() {
	//configs = my_local.Load_config(filepath.Join(getCurrentDir(), "config.json"))
	configs = my_config.Load_config("./config.json")
	//cookieHandler = securecookie.New(
	//	securecookie.GenerateRandomKey(32),
	//	securecookie.GenerateRandomKey(32))
	cookieHandler = securecookie.New(
		[]byte(configs.HashKey),
		[]byte(configs.BlockKey))
	CSRF = csrf.Protect([]byte(configs.CsrfAuthKey), csrf.Secure(false))
	// First we create a FuncMap with which to register the function.
	funcMap = template.FuncMap{
		// The name "title" is what the function will be called in the template text.
		"trim":  strings.TrimSpace,
		"lower": strings.ToLower,
		"upper": strings.ToUpper,
		"safehtml": func(text string) template.HTML {
			return template.HTML(text)
		},
	}
	g_templates = make(myTemplates)
	loadTemplates("")
	fmt.Printf("%v\n", g_templates)
	r = gin.New()
}
コード例 #25
0
ファイル: recover_test.go プロジェクト: on99/convention
func TestRecover(t *testing.T) {
	Convey("Given engine with recover handler", t, func() {
		ml := mockFatalLogger{bytes.NewBuffer(nil)}

		r := gin.New()
		r.Use(Recover(ml))

		route := "/api/v1/user"
		r.GET(route, func(c *gin.Context) {
			panic("internal error")
		})

		Convey("When request", func() {
			req, _ := http.NewRequest("GET", route, nil)
			resp := httptest.NewRecorder()
			r.ServeHTTP(resp, req)

			Convey("status code should be 500", func() {
				So(resp.Code, ShouldEqual, http.StatusInternalServerError)
			})

			Convey("response body should be empty", func() {
				So(resp.Body.String(), ShouldEqual, "")
			})

			expected := "panic reason -> internal error"
			Convey("first line of log should be "+expected, func() {
				So(strings.Split(ml.String(), "\n")[0], ShouldEqual, expected)
			})
		})
	})
}
コード例 #26
0
func StartGin() {
	gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.GET("/testApiPing", apiPing)
	r.GET("/testApiDB", apiDB)
	r.Run(":8082")
}
コード例 #27
0
ファイル: main.go プロジェクト: neutrinoapp/neutrino
func main() {
	r.SetVerbose(true)

	defer utils.Recover()
	utils.ListenSignals()
	utils.Liveness()

	if os.Getenv("DEBUG_N") != "true" {
		gin.SetMode(gin.ReleaseMode)
	}

	engine := gin.New()

	engine.Use(gin.Recovery())
	engine.Use(func() gin.HandlerFunc {
		return func(c *gin.Context) {
			defer c.Next()
			log.Info(c.Request.Method, c.Request.URL.Path, c.Writer.Status())
		}
	}())

	api.Initialize(engine)

	engine.Run(config.Get(config.KEY_API_PORT))
}
コード例 #28
0
ファイル: resourcer_test.go プロジェクト: sirlori/contrib
func TestCollectioner(t *testing.T) {
	router := gin.New()
	called := false

	mockdb, err := sqlmock.New()
	assert.Nil(t, err)
	db, err := gorm.Open("mysql", mockdb)
	assert.Nil(t, err)
	group := router.Group("/users")

	group.Use(ResourcerGorm(&GormCollectioner{}, &db))
	group.GET("/photos", func(c *gin.Context) {
		called = true
		_, ok := c.Get("gin.contrib.resource")
		assert.True(t, ok)
	})

	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/users/photos", nil)

	sqlmock.ExpectQuery("\\*").
		WillReturnRows(sqlmock.NewRows([]string{"id", "name", "password"}).
			AddRow(1, "username", "password"))
	router.ServeHTTP(w, req)
	assert.True(t, called)
	assert.Equal(t, w.Code, 200)
}
コード例 #29
0
func TestSendSomeJson(test *testing.T) {

	router := gin.New()
	router.GET("/somejson", SomeJSON)

	type Msg struct {
		Key string `json:"key"`
	}

	var expected Msg
	expected.Key = "value"
	//expectedJson, _ := json.Marshal(expected)

	request, _ := http.NewRequest("GET", "/somejson", nil)
	writer := httptest.NewRecorder()
	router.ServeHTTP(writer, request)

	actualBytes, _ := ioutil.ReadAll(writer.Body)
	actualMsg := Msg{}
	error := json.Unmarshal(actualBytes, &actualMsg)

	if error != nil {
		fmt.Println(error)
	}

	//Some debugging lines
	//fmt.Println(string(expectedJson))
	//fmt.Println(expectedJson)
	//fmt.Println(actualBytes)
	//fmt.Println(actualMsg)

	assert.Equal(test, expected, actualMsg)

}
コード例 #30
0
ファイル: main.go プロジェクト: nilsmagnus/folketelling
func main() {
	port := os.Getenv("PORT")

	if port == "" {
		log.Fatal("$PORT must be set")
	}

	router := gin.New()
	router.Use(gin.Logger())
	router.Static("/js", "js")
	router.Static("/static", "static")

	router.LoadHTMLGlob("templates/*.html")

	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	router.GET("/pages/:page", func(c *gin.Context) {
		page := fmt.Sprint(c.Params.ByName("page"), ".html")
		c.HTML(http.StatusOK, page, nil)
	})

	router.GET("/ssbapi/:number", ssbHandler)

	router.Run(":" + port)
}