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

Golang rest.ResourceHandler类代码示例

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

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



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

示例1: main

func main() {
	handler := rest.ResourceHandler{
		EnableStatusService: true,
	}
	auth := &rest.AuthBasicMiddleware{
		Realm: "test zone",
		Authenticator: func(userId string, password string) bool {
			if userId == "admin" && password == "admin" {
				return true
			}
			return false
		},
	}
	handler.SetRoutes(
		&rest.Route{"GET", "/countries", GetAllCountries},
		&rest.Route{"GET", "/.status",
			auth.MiddlewareFunc(
				func(w rest.ResponseWriter, r *rest.Request) {
					w.WriteJson(handler.GetStatus())
				},
			),
		},
	)
	http.ListenAndServe(":8080", &handler)
}
开发者ID:parisholley,项目名称:go-json-rest-examples,代码行数:25,代码来源:main.go


示例2: main

// -- Main function --
// Sets up server and Tasks struct, starts listening on 8080
func main() {
	//set flags
	configFile := flag.String("config", "", "An optional filepath for a config file.")
	flag.Parse()

	if *configFile != "" {
		log.Printf("configFile: " + *configFile)
	}

	//setup tasks
	tasks := new(Tasks)
	tasks.ConfigFile = *configFile
	//load config
	tasks.SetupAmqpConnection()

	//setup resource handler and routes
	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	err := handler.SetRoutes(
		rest.RouteObjectMethod("POST", "/tasks", tasks, "PostTask"),
	)
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(http.ListenAndServe(":8080", &handler))
}
开发者ID:divideandconquer,项目名称:go-celery-api,代码行数:29,代码来源:go-celery-api.go


示例3: BenchmarkGoJsonRest_Middleware

func BenchmarkGoJsonRest_Middleware(b *testing.B) {
	handler := rest.ResourceHandler{
		DisableJsonIndent: true,
		DisableXPoweredBy: true,
		Logger:            log.New(ioutil.Discard, "", 0),
		PreRoutingMiddlewares: []rest.Middleware{
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
		},
	}
	handler.SetRoutes(
		&rest.Route{"GET", "/action", goJsonRestHelloHandler},
	)

	rw, req := testRequest("GET", "/action")

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		handler.ServeHTTP(rw, req)
		if rw.Code != 200 {
			panic("no good")
		}
	}
}
开发者ID:kosuda,项目名称:golang-mux-benchmark,代码行数:28,代码来源:mux_bench_test.go


示例4: MakeHandler

func MakeHandler(api cheramiapi.Api, disableLogs bool) (rest.ResourceHandler, error) {
	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
		DisableLogger:            disableLogs,
	}

	err := handler.SetRoutes(
		&rest.Route{"POST", "/signup", api.Signup},
		&rest.Route{"POST", "/sessions", api.Login},
		&rest.Route{"DELETE", "/sessions", api.Logout},
		&rest.Route{"GET", "/users/:handle", api.GetUser},
		&rest.Route{"PATCH", "/users/:handle", api.EditUser},
		&rest.Route{"GET", "/users", api.SearchForUsers},
		&rest.Route{"GET", "/messages", api.GetMessages},
		&rest.Route{"GET", "/messages/:id", api.GetMessageById},
		&rest.Route{"POST", "/messages", api.NewMessage},
		&rest.Route{"PATCH", "/messages/:id", api.EditMessage},
		&rest.Route{"DELETE", "/messages", api.DeleteMessage},
		&rest.Route{"POST", "/joindefault", api.JoinDefault},
		&rest.Route{"POST", "/join", api.Join},
		&rest.Route{"POST", "/block", api.BlockUser},
		&rest.Route{"POST", "/circles", api.NewCircle},
		&rest.Route{"GET", "/circles", api.SearchCircles},
	)

	return handler, err
}
开发者ID:AbdulZaid,项目名称:cher-ami,代码行数:27,代码来源:routes.go


示例5: BenchmarkGoJsonRest_Composite

func BenchmarkGoJsonRest_Composite(b *testing.B) {
	namespaces, resources, requests := resourceSetup(10)

	handler := rest.ResourceHandler{
		DisableJsonIndent: true,
		DisableXPoweredBy: true,
		Logger:            log.New(ioutil.Discard, "", 0),
		PreRoutingMiddlewares: []rest.Middleware{
			&benchmarkGoJsonRestCompositeMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
			&benchmarkGoJsonRestMiddleware{},
		},
	}
	routes := make([]*rest.Route, 0, len(namespaces)*len(resources)*5)
	for _, ns := range namespaces {
		for _, res := range resources {
			routes = append(routes, &rest.Route{"GET", "/" + ns + "/" + res, goJsonRestHelloHandler})
			routes = append(routes, &rest.Route{"POST", "/" + ns + "/" + res, goJsonRestHelloHandler})
			routes = append(routes, &rest.Route{"GET", "/" + ns + "/" + res + "/:id", goJsonRestHelloHandler})
			routes = append(routes, &rest.Route{"PUT", "/" + ns + "/" + res + "/:id", goJsonRestHelloHandler})
			routes = append(routes, &rest.Route{"DELETE", "/" + ns + "/" + res + "/:id", goJsonRestHelloHandler})
		}
	}
	handler.SetRoutes(routes...)

	benchmarkRoutes(b, &handler, requests)
}
开发者ID:kosuda,项目名称:golang-mux-benchmark,代码行数:31,代码来源:mux_bench_test.go


示例6: newHandler

func newHandler() rest.ResourceHandler {
	handler := rest.ResourceHandler{}
	handler.SetRoutes(
		&rest.Route{"GET", "/verify/", getEmailVerify},
	)
	return handler
}
开发者ID:taterbase,项目名称:smtp-callback-verification,代码行数:7,代码来源:web.go


示例7: TestHandler

func TestHandler(t *testing.T) {

	handler := rest.ResourceHandler{
		DisableJsonIndent: true,
		ErrorLogger:       log.New(ioutil.Discard, "", 0),
	}

	handler.SetRoutes(
		&rest.Route{"POST", "/api/coach/checkin",
			func(w rest.ResponseWriter, r *rest.Request) {
				w.WriteHeader(http.StatusCreated)
				data := map[string]string{"id": "53f87e7ad18a68e0a884d31e"}
				w.WriteJson(data)
			},
		},
		&rest.Route{"POST", "/api/coach/checkout",
			func(w rest.ResponseWriter, r *rest.Request) {
				w.WriteHeader(http.StatusAccepted)
			},
		},
	)

	recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest(
		"POST", "http://www.sprint3r.com/api/coach/checkin", &map[string]string{"name": "iporsut", "league": "dtac"}))
	recorded.CodeIs(201)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"id":"53f87e7ad18a68e0a884d31e"}`)

	recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest(
		"POST", "http://www.sprint3r.com/api/coach/checkout", &map[string]string{"name": "iporsut", "league": "dtac"}))
	recorded.CodeIs(202)
	recorded.ContentTypeIsJson()
}
开发者ID:roongr2k7,项目名称:time_tracker_api,代码行数:33,代码来源:handler_test.go


示例8: main

func main() {
	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	handler.SetRoutes(
		&rest.Route{"POST", "/hashes", Hash},
	)
	http.ListenAndServe(":8080", &handler)
}
开发者ID:rdegges,项目名称:cryptly-api,代码行数:9,代码来源:cryptly.go


示例9: LaunchRestServer

func LaunchRestServer() {

	//加载rest配置
	//config, err := ConfigFromFile(configPath)
	//if err != nil {
	//	panic(err.Error())
	//}

	var logErr error
	restLog, logErr := os.OpenFile("./log/rest_access.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	if logErr != nil {
		panic(logErr)
	}
	defer restLog.Close()
	restErrLog, logErr := os.OpenFile("./log/rest_error.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	if logErr != nil {
		panic(logErr)
	}
	defer restErrLog.Close()

	handler := rest.ResourceHandler{
		PreRoutingMiddlewares: []rest.Middleware{
			&rest.AuthBasicMiddleware{
				Realm: "eggs zone",
				//AllowedMethods: []string{"GET", "POST", "PUT"},
				Authenticator: func(userId string, password string) bool {
					if userId == "orp" && password == "orp" {
						return true
					}
					return false
				},
			},
		},
		Logger:      log.New(restLog, "", 0),
		ErrorLogger: log.New(restErrLog, "", log.Ldate|log.Ltime|log.Llongfile),
	}

	err := handler.SetRoutes(
		//register
		&rest.Route{"POST", "/register/module", postRegisterModuleTask},
		&rest.Route{"GET", "/register/module", getRegisterModuleTask},

		//&rest.Route{"POST", "/register/package", postRegisterPackageTask},
		//&rest.Route{"GET", "/register/package", getRegisterPackageTask},
		//packer
		//&rest.Route{"POST", "/packer/:taskId", postPackerTask},
		//&rest.Route{"GET", "/packer/:taskId", getPackerTask},
		//version
		//&rest.Route{"GET", "/version/diff/:vnew/:vold", getVersionDiffTask},
	)
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(http.ListenAndServe(":8080", &handler))
}
开发者ID:ohlinux,项目名称:golang-snippet-cn,代码行数:55,代码来源:rest_server.go


示例10: init

func init() {

	handler := rest.ResourceHandler{}
	handler.SetRoutes(
		&rest.Route{"GET", "/countries", GetAllCountries},
		&rest.Route{"POST", "/countries", PostCountry},
		&rest.Route{"GET", "/countries/:code", GetCountry},
		&rest.Route{"DELETE", "/countries/:code", DeleteCountry},
	)
	http.Handle("/", &handler)
}
开发者ID:parisholley,项目名称:go-json-rest-examples,代码行数:11,代码来源:main.go


示例11: main

func main() {
	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	handler.SetRoutes(
		&rest.Route{"POST", "/task/add", CreateTask},
		&rest.Route{"GET", "/task/list", ReadAllTasks},
		&rest.Route{"GET", "/task/:id", ReadTask},
		&rest.Route{"POST", "/task/:id", UpdateTask},
		&rest.Route{"POST", "/task/delete/:id", DeleteTask},
	)
	http.ListenAndServe(":8080", &handler)
}
开发者ID:palaniap,项目名称:GO_TaskManager,代码行数:13,代码来源:ceresti.go


示例12: main

func main() {

	api := Api{}
	api.InitDB()
	api.InitSchema()

	handler := rest.ResourceHandler{
		EnableStatusService:      true,
		EnableRelaxedContentType: true,
		PreRoutingMiddlewares: []rest.Middleware{
			&rest.AuthBasicMiddleware{
				Realm: "test zone",
				Authenticator: func(userId string, password string) bool {
					if userId == "admin" && password == "admin" {
						return true
					}
					return false
				},
			},
		},
	}
	svmw := SemVerMiddleware{
		MinVersion: "1.2.0",
		MaxVersion: "3.0.0",
	}
	err := handler.SetRoutes(
		&rest.Route{"GET", "/#version/countries", svmw.MiddlewareFunc(GetAllCountries)},
		&rest.Route{"POST", "/countries", PostCountry},
		&rest.Route{"GET", "/countries/:code", GetCountry},
		&rest.Route{"DELETE", "/countries/:code", DeleteCountry},
		&rest.Route{"GET", "/.status",
			func(w rest.ResponseWriter, r *rest.Request) {
				w.WriteJson(handler.GetStatus())
			},
		},
		// ORM
		&rest.Route{"GET", "/reminders", api.GetAllReminders},
		&rest.Route{"POST", "/reminders", api.PostReminder},
		&rest.Route{"GET", "/reminders/:id", api.GetReminder},
		&rest.Route{"PUT", "/reminders/:id", api.PutReminder},
		&rest.Route{"DELETE", "/reminders/:id", api.DeleteReminder},
	)
	if err != nil {
		log.Fatal(err)
	}
	http.Handle("/api/", http.StripPrefix("/api", &handler))
	log.Fatal(http.ListenAndServe(":8080", nil))
	// log.Fatal(http.ListenAndServe(":8080", &handler))

}
开发者ID:mehulsbhatt,项目名称:gotelium,代码行数:50,代码来源:main.go


示例13: setupRestAPI

func setupRestAPI(router *mux.Router, oAuth *oAuthHandler) {
	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
		PreRoutingMiddlewares:    []rest.Middleware{oAuth},
	}
	handler.SetRoutes(
		&rest.Route{"GET", "/api/me", func(w rest.ResponseWriter, req *rest.Request) {
			data := context.Get(req.Request, USERDATA)
			w.WriteJson(&data)
		}},
	)

	router.Handle("/api/me", &handler)
}
开发者ID:felipeweb,项目名称:osin-mongo-storage,代码行数:14,代码来源:main.go


示例14: main

func main() {
	mongoPersister := MongoPersister{}
	handler := rest.ResourceHandler{}
	handler.SetRoutes(
		&rest.Route{"GET", "/api/v1/change_pk", func(w rest.ResponseWriter, req *rest.Request) {
			var longBook Book = Book{Title: "Harry Potter", Author: "JK Rolling", Pages: 1000}
			mongoPersister.InsertPerson()
			w.WriteJson(&Message{
				Body: longBook.CategoryByLength(),
			})
		}},
	)
	http.ListenAndServe(":8080", &handler)
}
开发者ID:roofimon,项目名称:gorest-json-mgo,代码行数:14,代码来源:helloGoRestJson.go


示例15: main

func main() {

	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	handler.SetRoutes(
		&rest.Route{"GET", "/task/list", GetAllTasks},
		&rest.Route{"POST", "/task/add", PostTask},
		&rest.Route{"GET", "/task/:taskdesc", GetTask},
		&rest.Route{"POST", "/task/:taskdesc", UpdateTask},
		&rest.Route{"DELETE", "/task/:taskdesc", DeleteTask},
	)
	http.ListenAndServe(":8080", &handler)
}
开发者ID:priyanka88,项目名称:Web-service-using-Go,代码行数:14,代码来源:Task.go


示例16: main

func main() {
	handler := rest.ResourceHandler{}
	err := handler.SetRoutes(
		&rest.Route{"GET", "/", func(w rest.ResponseWriter, req *rest.Request) {
			w.WriteJson(&Message{
				Body: "Hello World!",
			})
		}},
	)
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), &handler))
}
开发者ID:rysenko,项目名称:goat,代码行数:14,代码来源:web.go


示例17: StartClientApi

func StartClientApi() {
	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	//api := clientApi{}
	err := handler.SetRoutes(
		rest.RouteObjectMethod("POST", "/jobs", api, "CreateJob"),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.server = manners.NewServer()
	glog.Info("client api starting")
	api.server.ListenAndServe(":8080", &handler)
}
开发者ID:kmanley,项目名称:golang-grid,代码行数:15,代码来源:client_api.go


示例18: main

func main() {
	path := flag.String("config", "./smsadapter.conf", "设置配置文件的路径")
	flag.Parse()
	*path = filepath.FromSlash(*path)

	c, err := goconfig.LoadConfigFile(*path)
	if err != nil {
		log.Fatal(err)
	}

	ip, iperr := c.GetValue("local", "listen")
	if iperr != nil {
		log.Printf("%v use default:0.0.0.0", iperr)
		ip = "0.0.0.0"
	}

	port, porterr := c.Int("local", "port")
	if porterr != nil {
		log.Panicf("%v,use default:8500", porterr)
		port = 8500
	}

	smssender := sms.NewSmsHttp()
	smssender.Init(c)

	fmt.Println("listen on " + ip + ":" + strconv.Itoa(port))
	handler := rest.ResourceHandler{}
	errx := handler.SetRoutes(
		&rest.Route{"GET", "/message", func(w rest.ResponseWriter, req *rest.Request) {
			w.WriteJson(&Message{
				Body: "Hello World!",
			})
		}},
		&rest.Route{"GET", "/sms/send", func(w rest.ResponseWriter, req *rest.Request) {
			w.Header().Set("Content-Type", "Application/json; charset=utf-8")
			phone := req.FormValue("phone")
			password := req.FormValue("password")
			rsp := smssender.Send(phone, password)
			w.WriteJson(rsp)
		}},
	)
	if errx != nil {
		log.Fatal(errx)
	}

	log.Fatal(http.ListenAndServe(ip+":"+strconv.Itoa(port), &handler))
	fmt.Println("exit1")
}
开发者ID:xjplke,项目名称:smsadapter,代码行数:48,代码来源:smsadapter.go


示例19: main

func main() {
	var port int
	var logpath string

	// configure command line flags
	flag.IntVar(&port, "port", 8080, "HTTP Server Port")
	flag.StringVar(&filepath, "filepath", "output.json", "Output JSON file path")
	flag.StringVar(&logpath, "logpath", "log-server.log", "Log file path")
	flag.Parse()

	// set up logging
	l, err := os.OpenFile(logpath, os.O_RDWR|os.O_CREATE, 0644)
	defer l.Close()
	if err != nil {
		log.Fatalf("error opening log file: %v", err)
	}
	logger := log.New(io.Writer(l), "", 0)

	// set up HTTP server
	httpAddr := fmt.Sprintf(":%v", port)
	logger.Printf("Listening on %v", httpAddr)

	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
		EnableGzip:               true,
		EnableLogAsJson:          true,
		Logger:                   logger,
		PreRoutingMiddlewares: []rest.Middleware{
			&rest.CorsMiddleware{
				RejectNonCorsRequests: false,
				OriginValidator: func(origin string, request *rest.Request) bool {
					return true
				},
				AllowedMethods:                []string{"GET", "POST"},
				AllowedHeaders:                []string{"Accept", "Content-Type", "X-Requested-With"},
				AccessControlAllowCredentials: true,
				AccessControlMaxAge:           3600,
			},
		},
	}
	handler.SetRoutes(
		&rest.Route{"POST", "/log", PostLogHandler},
		&rest.Route{"GET", "/logs", GetLogsHandler},
	)

	log.Fatal(http.ListenAndServe(httpAddr, &handler))
}
开发者ID:jgoodall,项目名称:log-server,代码行数:47,代码来源:log-server.go


示例20: main

func main() {
	api := Api{}
	api.initDB()

	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	handler.SetRoutes(
		rest.RouteObjectMethod("GET", "/api/users", &api, "GetAllUsers"),
		rest.RouteObjectMethod("POST", "/api/users", &api, "PostUser"),
		rest.RouteObjectMethod("GET", "/api/users/:id", &api, "GetUser"),
		/*&rest.RouteObjectMethod("PUT", "/api/users/:id", &api, "PutUser"),*/
		rest.RouteObjectMethod("DELETE", "/api/users/:id", &api, "DeleteUser"),
	)

	http.ListenAndServe(":"+HTTPREST_SERVERPORT, &handler)
}
开发者ID:sohamsankaran,项目名称:go-database-drivers,代码行数:17,代码来源:sqlserver-json-rest.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang rest.ResponseWriter类代码示例发布时间:2022-05-24
下一篇:
Golang rest.Request类代码示例发布时间: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