• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang rest.MakeRouter函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: main

func main() {
	api := rest.NewApi()
	statusMw := &rest.StatusMiddleware{}
	api.Use(statusMw)
	api.Use(rest.DefaultDevStack...)
	auth := &rest.AuthBasicMiddleware{
		Realm: "test zone",
		Authenticator: func(userId string, password string) bool {
			if userId == "admin" && password == "admin" {
				return true
			}
			return false
		},
	}
	router, err := rest.MakeRouter(
		rest.Get("/countries", GetAllCountries),
		rest.Get("/.status", auth.MiddlewareFunc(
			func(w rest.ResponseWriter, r *rest.Request) {
				w.WriteJson(statusMw.GetStatus())
			},
		)),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
开发者ID:jemkzheng,项目名称:go-json-rest-examples,代码行数:28,代码来源:main.go


示例2: StartServer

func (s *server) StartServer() error {
	api := rest.NewApi()

	router, err := rest.MakeRouter(
		// system
		&rest.Route{"GET", "/v1/ping", s.ping},
		&rest.Route{"GET", "/v1/version", s.version},

		// v1
		&rest.Route{"GET", "/v1/secrets/:type/:name", s.serveSecret},
	)

	if err != nil {
		return err
	}

	api.SetApp(router)

	go func() {
		s.builder.Conf.Logger.Infof("Starting API on %d", s.builder.Conf.ApiPort)

		// 192.168.99.1
		if err := http.ListenAndServe(fmt.Sprintf("%s:%d", s.builder.Conf.ApiBinding, s.builder.Conf.ApiPort), api.MakeHandler()); err != nil {
			s.builder.Conf.Logger.Errorf("Failed to start API %s", err.Error())
			os.Exit(2)
		}

	}()

	return nil
}
开发者ID:cloud66,项目名称:habitus,代码行数:31,代码来源:server.go


示例3: main

func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Get("/weather/#location", func(w rest.ResponseWriter, req *rest.Request) {
			weather, err := GetWeather(req.PathParam("location"))
			if err != nil {
				rest.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			//w.WriteJson(&weather)
			//
			w.WriteJson(
				&WeatherResponse{
					Location:    fmt.Sprintf("%s", weather.CityName),
					Temperature: KelvinToFarenheit(weather.Main.Temp),
				},
			)
		}),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
开发者ID:kevinpelton,项目名称:weatherservice,代码行数:26,代码来源:main.go


示例4: main

func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	/*
		api.Use(&rest.CorsMiddleware{
			RejectNonCorsRequests: false,
			OriginValidator: func(origin string, request *rest.Request) bool {
				return true
			},
			AllowedMethods: []string{"GET", "POST", "PUT"},
			AllowedHeaders: []string{
				"Accept", "Content-Type", "X-Custom-Header", "Origin"},
			AccessControlAllowCredentials: true,
			AccessControlMaxAge:           3600,
		})
	*/
	router, err := rest.MakeRouter(
		rest.Post("/test", test),
	)

	// 存在しないルート時
	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":9999", api.MakeHandler()))
}
开发者ID:shamoto-donuts,项目名称:goSample,代码行数:29,代码来源:main.go


示例5: MsgServerStart

func MsgServerStart() {

	mqmsg := msgqueue.MqMsg{
		Msg: message.NewMsg(),
	}
	persistent := PerMqAgent{
		Msg: message.NewMsg(),
	}

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	router, err := rest.MakeRouter(
		//rest.Get("/test", msg.TestMsg),
		rest.Get("/testmq/:mqid", msgqueue.DefaultMM.TestMq),
		rest.Post("/send_msg/:mqid", mqmsg.PostMsg),
		rest.Get("/receive_msg/:mqid", mqmsg.GetMsg),
		rest.Post("/send/:mqid", persistent.PostMsg),
		rest.Get("/receive/:mqid", persistent.GetMsg),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":"+ListenPort, api.MakeHandler()))
}
开发者ID:jmptrader,项目名称:Caesar,代码行数:26,代码来源:msgServer.go


示例6: NewRest

// NewRest configures REST api handlers and wrappers.
func NewRest() *rest.Api {
	api := rest.NewApi()
	api.MakeHandler()
	api.Use(rest.DefaultDevStack...)

	api.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		OriginValidator: func(origin string, request *rest.Request) bool {
			return true
		},
		AllowedMethods: []string{"GET", "POST"},
		AllowedHeaders: []string{
			"Accept", "Content-Type", "X-Custom-Header", "Origin"},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           3600,
	})

	router, err := rest.MakeRouter(
		rest.Post("/translations", translations),
		rest.Post("/suggestions", suggestions),
		rest.Get("/health", health),
	)
	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	return api
}
开发者ID:eicca,项目名称:smart-translate-server,代码行数:30,代码来源:rest.go


示例7: main

/*
Microservice for accessing data
*/
func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	api.Use(
		&rest.AuthBasicMiddleware{
			Realm:         "Smart Alarm Clock REST API",
			Authenticator: auth.AuthenticateByFile,
			Authorizator:  auth.AuthorizeRequest})
	router, err := rest.MakeRouter(
		rest.Get("/test/:time", view.GetJSONMessage),
		rest.Get("/calendar/next/:id", view.GetNextCalendarEntry),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	apilog.Init()
	calcom.InitApis()
	log.Fatal(
		http.ListenAndServeTLS(":1443",
			"/etc/sac/keys/cert.pem",
			"/etc/sac/keys/key.pem",
			api.MakeHandler(),
		),
	)
}
开发者ID:rugo,项目名称:sacapi,代码行数:29,代码来源:saccalendar.go


示例8: main

func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Get("/message", func(w rest.ResponseWriter, req *rest.Request) {
			for cpt := 1; cpt <= 10; cpt++ {

				// wait 1 second
				time.Sleep(time.Duration(1) * time.Second)

				w.WriteJson(map[string]string{
					"Message": fmt.Sprintf("%d seconds", cpt),
				})
				w.(http.ResponseWriter).Write([]byte("\n"))

				// Flush the buffer to client
				w.(http.Flusher).Flush()
			}
		}),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)

	server := &graceful.Server{
		Timeout: 10 * time.Second,
		Server: &http.Server{
			Addr:    ":8080",
			Handler: api.MakeHandler(),
		},
	}

	log.Fatal(server.ListenAndServe())
}
开发者ID:ricardolonga,项目名称:go-json-rest-examples,代码行数:35,代码来源:main.go


示例9: main

func main() {
	// context
	ctx = context.Background()

	// db
	hoge.BuildInstances()

	// redis
	redis_pool := newPool()
	ctx = context.WithValue(ctx, "redis", redis_pool)

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Post("/test", baseHandlerFunc(controller.Test)),
	)

	// 存在しないルート時
	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	httpErr := http.ListenAndServe(":9999", api.MakeHandler())
	if httpErr != nil {
		log.Fatal(err, "http error!!")
	}
}
开发者ID:shamoto-donuts,项目名称:goSample,代码行数:28,代码来源:main.go


示例10: initRoutes

func initRoutes(restApi *rest.Api) {
	authController := &AuthController{}
	appController := &ApplicationController{}
	typesController := &TypesController{}

	router, err := rest.MakeRouter(
		rest.Put(authController.Path(), authController.RegisterUserHandler),
		rest.Post(authController.Path(), authController.LoginUserHandler),
		rest.Put("/:appId"+authController.Path(), authController.AppRegisterUserHandler),
		rest.Post("/:appId"+authController.Path(), authController.AppLoginUserHandler),

		rest.Post(appController.Path(), appController.CreateApplicationHandler),
		rest.Get(appController.Path(), appController.GetApplicationsHandler),
		rest.Get(appController.Path()+"/:appId", appController.GetApplicationHandler),
		rest.Delete(appController.Path()+"/:appId", appController.DeleteApplicationHandler),
		rest.Put(appController.Path()+"/:appId", appController.UpdateApplicationHandler),

		rest.Post("/:appId"+typesController.Path(), typesController.CreateTypeHandler),
		rest.Delete("/:appId"+typesController.Path()+"/:typeName", typesController.DeleteType),
		rest.Post("/:appId"+typesController.Path()+"/:typeName", typesController.InsertInTypeHandler),
		rest.Get("/:appId"+typesController.Path()+"/:typeName", typesController.GetTypeDataHandler),
		rest.Get("/:appId"+typesController.Path()+"/:typeName/:itemId", typesController.GetTypeItemById),
		rest.Put("/:appId"+typesController.Path()+"/:typeName/:itemId", typesController.UpdateTypeItemById),
		rest.Delete("/:appId"+typesController.Path()+"/:typeName/:itemId", typesController.DeleteTypeItemById),
	)

	if err != nil {
		log.Fatal(err)
	}

	restApi.SetApp(router)
}
开发者ID:gitter-badger,项目名称:neutrino-core,代码行数:32,代码来源:api.go


示例11: main

func main() {
	// context
	ctx = context.Background()
	db := initDb()
	ctx = context.WithValue(ctx, "test", "aaabbbccc")
	ctx = context.WithValue(ctx, "DB", db)

	// redis
	redis_pool := newPool()
	ctx = context.WithValue(ctx, "redis", redis_pool)

	str := ctx.Value("test")
	log.Println(str)

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Post("/test", baseHandlerFunc(controller.Test)),
	)

	// 存在しないルート時
	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":9999", api.MakeHandler()))
}
开发者ID:shamoto-donuts,项目名称:goSample,代码行数:28,代码来源:main.go


示例12: StartServer

func (app *App) StartServer(addr string, dbFileName string) {
	err := app.InitDB(dbFileName)
	if err != nil {
		log.Fatal(err)
	}
	api := rest.NewApi()
	api.Use(rest.DefaultProdStack...)
	api.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		AllowedMethods:        []string{"GET", "POST"},
		AllowedHeaders: []string{
			"Accept", "Content-Type", "Origin"},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           2592000,

		OriginValidator: func(origin string, request *rest.Request) bool {
			return true
		},
	})
	router, err := rest.MakeRouter(
		rest.Get("/latest", app.GetLatest),
		rest.Get("/last", app.GetLast),
		rest.Get("/all", app.GetAll),
		rest.Post("/postEntry", app.PostEntry),
		//rest.Post("/postSignedEntry", app.PostJwtEntry),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(addr, api.MakeHandler()))
}
开发者ID:ubergesundheit,项目名称:simple-time-series-server,代码行数:32,代码来源:simple-time-series-server.go


示例13: main

func main() {

	logit.Info.Println("cpmcontainerapi: containeragent starting")

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		&rest.Route{"GET", "/status", cpmcontainerapi.Status},
		&rest.Route{"POST", "/remotewritefile", cpmcontainerapi.RemoteWritefile},
		&rest.Route{"POST", "/seed", cpmcontainerapi.Seed},
		&rest.Route{"POST", "/startpg", cpmcontainerapi.StartPG},
		&rest.Route{"POST", "/stoppg", cpmcontainerapi.StopPG},
		&rest.Route{"POST", "/startpgonstandby", cpmcontainerapi.StartPGOnStandby},
		&rest.Route{"POST", "/initdb", cpmcontainerapi.Initdb},
		&rest.Route{"POST", "/startpgpool", cpmcontainerapi.StartPgpool},
		&rest.Route{"POST", "/stoppgpool", cpmcontainerapi.StopPgpool},
		&rest.Route{"POST", "/basebackup", cpmcontainerapi.Basebackup},
		&rest.Route{"POST", "/failover", cpmcontainerapi.Failover},
		&rest.Route{"POST", "/controldata", cpmcontainerapi.Controldata},
		&rest.Route{"POST", "/badgergenerate", cpmcontainerapi.BadgerGenerate},
		&rest.Route{"POST", "/restore", cpmcontainerapi.Restore},
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)

	http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler()))
	http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("/pgdata/pg_log"))))

	log.Fatal(http.ListenAndServe(":10001", nil))
	log.Fatal(http.ListenAndServeTLS(":10000", "/var/cpm/keys/cert.pem", "/var/cpm/keys/key.pem", nil))
}
开发者ID:rogervaas,项目名称:crunchy-postgresql-manager,代码行数:33,代码来源:cpmcontainerserver.go


示例14: MakeApi

func MakeApi() http.Handler {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	jwtMiddleware := &jwt.JWTMiddleware{
		Key:           []byte("super secret key"),
		Realm:         "Spacebook",
		Timeout:       time.Hour,
		MaxRefresh:    time.Hour * 24,
		Authenticator: authUser,
	}

	api.Use(&rest.IfMiddleware{
		Condition: func(request *rest.Request) bool {
			return request.URL.Path == "/pasteswithuser"
		},
		IfTrue: jwtMiddleware,
	})

	router, err := rest.MakeRouter(
		&rest.Route{"GET", "/pastes/:id", GetPaste},
		&rest.Route{"POST", "/pastes", PostPaste},
		&rest.Route{"POST", "/pasteswithuser", PostPasteWithUser},
		&rest.Route{"GET", "/pastes", GetAll},
		&rest.Route{"POST", "/login", jwtMiddleware.LoginHandler},
	)

	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	return api.MakeHandler()
}
开发者ID:StephanDollberg,项目名称:talks,代码行数:34,代码来源:pastebin.go


示例15: main

func main() {

	servePort := os.Getenv(servePortEnv)

	if servePort == "" {
		servePort = defaultServePort
	}

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	router, err := rest.MakeRouter(
		rest.Get("/rnd", genRndNumber),
	)

	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	bindPort := fmt.Sprintf(":%s", servePort)

	log.Printf("server listening on %s", bindPort)

	log.Fatal(http.ListenAndServe(bindPort, api.MakeHandler()))
}
开发者ID:asega-is,项目名称:poc_bk_rannumgen,代码行数:26,代码来源:main.go


示例16: main

func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	//配置API跨域CORS
	api.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		OriginValidator: func(origin string, req *rest.Request) bool {
			return origin == req.Header.Get("Origin")
		},
		AllowedMethods: []string{"GET", "POST", "PUT"},
		AllowedHeaders: []string{
			"Accept", "Content-Type", "X-Custom-Header", "Origin"},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           3600,
	})

	//设置API基本Router
	router, err := rest.MakeRouter(
		rest.Post("/:raw.json", RawWrite),
		rest.Post("/auth/login/:id", AuthLogin),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
开发者ID:ryanemax,项目名称:learngo,代码行数:27,代码来源:rest-main.go


示例17: main

func main() {

	//fmt.Fprintln(os.Stderr, "this is an error message to stderr using Fprintln")
	logit.Info.Println("sleeping during startup to give DNS a chance")

	sleepTime, _ := time.ParseDuration("7s")
	time.Sleep(sleepTime)

	task.LoadSchedules()

	logit.Info.Println("taskserver starting")

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		&rest.Route{"POST", "/status/add", task.StatusAdd},
		&rest.Route{"POST", "/status/update", task.StatusUpdate},
		&rest.Route{"POST", "/executenow", task.ExecuteNow},
		&rest.Route{"POST", "/reload", task.Reload},
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)

	http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler()))

	log.Fatal(http.ListenAndServe(":13001", nil))

}
开发者ID:rogervaas,项目名称:crunchy-postgresql-manager,代码行数:30,代码来源:taskserver.go


示例18: main

func main() {

	logit.Info.Println("serveragent starting")

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		&rest.Route{"POST", "/metrics/iostat", cpmserverapi.MetricIostat},
		&rest.Route{"POST", "/metrics/df", cpmserverapi.MetricDf},
		&rest.Route{"POST", "/metrics/mem", cpmserverapi.MetricMEM},
		&rest.Route{"POST", "/metrics/cpu", cpmserverapi.MetricCPU},
		&rest.Route{"POST", "/docker/inspect", cpmserverapi.DockerInspect},
		&rest.Route{"POST", "/docker/remove", cpmserverapi.DockerRemove},
		&rest.Route{"POST", "/docker/start", cpmserverapi.DockerStart},
		&rest.Route{"POST", "/docker/stop", cpmserverapi.DockerStop},
		&rest.Route{"POST", "/docker/run", cpmserverapi.DockerRun},
		&rest.Route{"POST", "/disk/provision", cpmserverapi.DiskProvision},
		&rest.Route{"POST", "/disk/delete", cpmserverapi.DiskDelete},
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":10001", api.MakeHandler()))
	log.Fatal(http.ListenAndServeTLS(":10000", "/var/cpm/keys/cert.pem", "/var/cpm/keys/key.pem", api.MakeHandler()))
}
开发者ID:CrunchyData,项目名称:crunchy-postgresql-manager-openshift,代码行数:26,代码来源:cpmserverapi.go


示例19: MakeHandler

// MakeHandler creates the api request handler
func MakeHandler() *http.Handler {
	api := rest.NewApi()

	authMiddleware, err := CreateAuthMiddleware()
	if err != nil {
		panic(err)
	}

	api.Use(&rest.IfMiddleware{
		// Only authenticate non login or register requests
		Condition: func(request *rest.Request) bool {
			return (request.URL.Path != variables.APIPathLoginUserServer) && (request.URL.Path != variables.APIPathRegisterUserServer)
		},
		IfTrue: authMiddleware,
	})
	api.Use(rest.DefaultProdStack...)
	router, err := rest.MakeRouter(
		rest.Post(variables.APIPathLoginUserServer, authMiddleware.LoginHandler),
		rest.Get(variables.APIPathRefreshUserServer, authMiddleware.RefreshHandler),
		rest.Post(variables.APIPathRegisterUserServer, PostRegister),
		rest.Get(variables.APIPathUserServer, GetUser),
		rest.Post(variables.APIPathUserServer, PostUser),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	handler := api.MakeHandler()
	return &handler
}
开发者ID:pdxjohnny,项目名称:numapp,代码行数:31,代码来源:handler.go


示例20: main

func main() {
	dsn := fmt.Sprintf("user=%s dbname=%s sslmode=disable",
		os.Getenv("DATABASE_USER"),
		os.Getenv("DATABASE_NAME"))

	db, err := gorm.Open("postgres", dsn)

	fmt.Println(dsn)

	if err != nil {
		panic(err)
	}

	db.DB()
	db.DB().Ping()
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)
	db.SingularTable(true)
	db.LogMode(true)

	api := rest.NewApi()

	api.Use(rest.DefaultDevStack...)

	accounts := &Accounts{Db: db}

	router, err := rest.MakeRouter(
		rest.Get("/users/:username", accounts.Detail),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
开发者ID:ulule,项目名称:deepcopier,代码行数:35,代码来源:main.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang rest.NewApi函数代码示例发布时间:2022-05-24
下一篇:
Golang rest.Get函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap