本文整理汇总了Golang中github.com/ant0ine/go-json-rest/rest.NewApi函数的典型用法代码示例。如果您正苦于以下问题:Golang NewApi函数的具体用法?Golang NewApi怎么用?Golang NewApi使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewApi函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: APIRequest
func APIRequest(url string, method string, model interface{}, token string) {
jwtMiddleware := &jwt.JWTMiddleware{
Key: SecretKey,
Realm: Realm,
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
Authenticator: func(userId string, password string) bool {
return Authenticator(userId, password)
},
}
api := rest.NewApi()
api.Use(&rest.IfMiddleware{
Condition: func(request *rest.Request) bool {
return CheckCondition(request)
},
IfTrue: jwtMiddleware,
})
api.SetApp(NewRouter(jwtMiddleware, testConn))
Request = test.MakeSimpleRequest(method, url, model)
if token != "" {
Request.Header.Set("Authorization", "Bearer "+token)
}
recorded := test.RunRequest(tst, api.MakeHandler(), Request)
Response = recorded.Recorder
}
示例2: main
func main() {
flag.Parse()
sm := newSyncMaster(*dbDir)
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := rest.MakeRouter(
&rest.Route{"GET", "/labels/since/:nonce/for/:mpk", sm.GetLabels},
&rest.Route{"POST", "/label", sm.CreateLabel},
&rest.Route{"POST", "/labels", sm.CreateLabels},
)
if err != nil {
log.Fatal(err)
}
api.SetApp(router)
sm.logger.Info("Server started and listening on %s", *listenPort)
if *useTLS {
sm.logger.Info("Using SSL with certificate '%s' and keyfile '%s'", *certPath, *keyPath)
log.Fatal(http.ListenAndServeTLS(*listenPort, *certPath, *keyPath, api.MakeHandler()))
} else {
log.Fatal(http.ListenAndServe(*listenPort, api.MakeHandler()))
}
}
示例3: main
func main() {
svmw := SemVerMiddleware{
MinVersion: "1.0.0",
MaxVersion: "3.0.0",
}
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := rest.MakeRouter(
rest.Get("/#version/message", svmw.MiddlewareFunc(
func(w rest.ResponseWriter, req *rest.Request) {
version := req.Env["VERSION"].(*semver.Version)
if version.Major == 2 {
// http://en.wikipedia.org/wiki/Second-system_effect
w.WriteJson(map[string]string{
"Body": "Hello broken World!",
})
} else {
w.WriteJson(map[string]string{
"Body": "Hello World!",
})
}
},
)),
)
if err != nil {
log.Fatal(err)
}
api.SetApp(router)
http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler()))
log.Fatal(http.ListenAndServe(":8080", nil))
}
示例4: 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
}
示例5: main
func main() {
fmt.Printf("grouch: a RESTful object store.\n")
// Open the config file
config := readConfig("./config.json")
fmt.Printf("Data directory: %s\n", config.Directory)
fmt.Printf("Mode: %s\n", config.Mode)
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
endpoint := "/" + config.Directory + "/#file"
router, err := rest.MakeRouter(
rest.Get(endpoint, func(w rest.ResponseWriter, req *rest.Request) {
file, err := ioutil.ReadFile(
config.Directory + "/" + req.PathParam("file"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fileContents := string(file)
w.WriteJson(&fileContents)
}),
)
if err != nil {
log.Fatal(err)
}
api.SetApp(router)
log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
示例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
}
示例7: TestGJRMiddlewareWithRaceCondition
// TestGJRMiddlewareWithRaceCondition test GRJ middleware under race condition.
func TestGJRMiddlewareWithRaceCondition(t *testing.T) {
runtime.GOMAXPROCS(4)
api := rest.NewApi()
api.Use(NewGJRMiddleware(newRedisLimiter("5-M", "limitertests:gjrrace")))
api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson(map[string]string{"message": "ok"})
}))
handler := api.MakeHandler()
req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
req.RemoteAddr = fmt.Sprintf("178.1.2.%d:180", Random(1, 90))
nbRequests := 100
successCount := 0
var wg sync.WaitGroup
wg.Add(nbRequests)
for i := 1; i <= nbRequests; i++ {
go func() {
recorded := test.RunRequest(t, handler, req)
if recorded.Recorder.Code == 200 {
successCount++
}
wg.Done()
}()
}
wg.Wait()
assert.Equal(t, 5, successCount)
}
示例8: 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!!")
}
}
示例9: 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()))
}
示例10: GetApi
func (restapi *CyberBullyingEntryPointRestApiImpl) GetApi() (Api *rest.Api) {
if restapi.Api == nil {
restapi.Api = rest.NewApi()
restapi.Api.Use(rest.DefaultDevStack...)
}
return restapi.Api
}
示例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()))
}
示例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()))
}
示例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))
}
示例14: 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()))
}
示例15: 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()))
}