当前位置: 首页>>代码示例>>Golang>>正文


Golang server.Handler函数代码示例

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


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

示例1: setupAPIConfigs

func setupAPIConfigs(app *server.App) {
	var API = app.API()
	// --------------------------------------------------------------------------
	// Sever Config
	API.GET("/configs/",
		server.Handler(func(req *wcg.Request) response.Response {
			return response.NewJSONResponse(configs.GetAll(req))
		}))

	API.GET("/configs/:key.json",
		server.Handler(func(req *wcg.Request) response.Response {
			val := configs.Get(req, req.Param("key"))
			if val == nil {
				return response.NotFound(req)
			} else {
				return response.NewJSONResponse(val)
			}
		}),
	)

	API.PUT("/configs/:key.json",
		middleware.ParseForm(func(v *validators.FormValidator) {
			v.Field("value").Required()
		}),
		server.Handler(func(req *wcg.Request) response.Response {
			val := configs.Get(req, req.Param("key"))
			if val == nil {
				return response.NotFound(req)
			} else {
				val.Value = req.Form("value")
				configs.PutMulti(req, val)
				return response.NewJSONResponse(val)
			}
		}))
}
开发者ID:speedland,项目名称:service,代码行数:35,代码来源:api_configs.go

示例2: setupAPIGates

func setupAPIGates(app *server.App) {
	var API = app.API()

	// --------------------------------------------------------------------------
	// Gate
	API.GET("/gates/",
		server.Handler(func(req *wcg.Request) response.Response {
			return response.NewJSONResponse(gates.GetAll(req))
		}))

	API.GET("/gates/:key.json",
		server.Handler(func(req *wcg.Request) response.Response {
			val := gates.Get(req, req.Param("key"))
			if val == nil {
				return response.NotFound(req)
			} else {
				return response.NewJSONResponse(val)
			}
		}))

	API.PUT("/gates/:key.json",
		middleware.ParseForm(nil),
		server.Handler(func(req *wcg.Request) response.Response {
			val := gates.Get(req, req.Param("key"))
			if val == nil {
				return response.NotFound(req)
			} else {
				val.UIDs = req.HTTPRequest().Form["uids"]
				gates.PutMulti(req, val)
				return response.NewJSONResponse(val)
			}
		}))
}
开发者ID:speedland,项目名称:service,代码行数:33,代码来源:api_gates.go

示例3: EntityTail

func EntityTail(query *entities.Query) server.Handler {
	return server.Handler(
		func(req *wcg.Request) response.Response {
			result := query.MustExecute(req)
			return response.NewJSONResponse(result.Tail())
		})
}
开发者ID:speedland,项目名称:service,代码行数:7,代码来源:entity.go

示例4: EntityPutOrCreate

func EntityPutOrCreate(put *entities.Put, keyParams string) server.Handler {
	return server.Handler(
		func(req *wcg.Request) response.Response {
			return processEntityPut(req, put, keyParams, true)
		},
	)
}
开发者ID:speedland,项目名称:service,代码行数:7,代码来源:entity.go

示例5: EntityDelete

func EntityDelete(del *entities.Delete, keyParam string) server.Handler {
	return server.Handler(
		func(req *wcg.Request) response.Response {
			del.Key(req.Param(keyParam)).MustCommit(req)
			return response.NewJSONResponse(true)
		})
}
开发者ID:speedland,项目名称:service,代码行数:7,代码来源:entity.go

示例6: ParseForm

func ParseForm(configure func(*validators.FormValidator)) server.Handler {
	// it's ok to set nil as configure to parse form without validation.
	var v *validators.FormValidator
	if configure != nil {
		v = validators.NewFormValidator()
		configure(v)
	}
	return server.Handler(
		func(req *wcg.Request) response.Response {
			if m := req.Method(); m != "POST" && m != "PUT" {
				return nil
			}
			if req.Header("content-type") != "application/x-www-form-urlencoded" {
				req.Logger.Debugf("Skip FormValidation since the requested content is not a form")
				return nil
			}
			err := req.HTTPRequest().ParseForm()
			if err == nil {
				req.Logger.Debugf("Request Form: %v", req.HTTPRequest().Form)
			} else {
				req.Logger.Warnf("ParseForm failed in FormValidaiton process. Triggered ValidationError: %v", err)
				return response.BadRequest(req, err)
			}

			if v == nil {
				req.Logger.Debugf("Skip FormValidation since no validator is defined.")
				return nil
			}
			if err := v.Eval(req.HTTPRequest().Form); err != nil {
				return response.BadRequest(req, err)
			}
			return nil
		})
}
开发者ID:speedland,项目名称:service,代码行数:34,代码来源:parse_form.go

示例7: Parallel

func Parallel(handlers map[string]server.Handler) server.Handler {
	return server.Handler(
		func(req *wcg.Request) response.Response {
			var status = make(map[string]int)
			var data = make(map[string]interface{})
			var mutex sync.Mutex
			var wg sync.WaitGroup
			for k, q := range handlers {
				wg.Add(1)
				go func(k string, h server.Handler) {
					defer wg.Done()
					v := h.Handle(req)
					if vv, ok := v.(*response.JSONResponse); ok {
						mutex.Lock()
						defer mutex.Unlock()
						status[k] = vv.StatusCode
						data[k] = vv.Data
					}
				}(k, q)
			}
			wg.Wait()
			for k, code := range status {
				// return non 2xx response
				if code > 0 && (code < 200 || code >= 300) {
					return response.NewJSONResponseWithStatus(data[k], code)
				}
			}
			return response.NewJSONResponse(data)
		})
}
开发者ID:speedland,项目名称:service,代码行数:30,代码来源:parallel.go

示例8: setupAPIStats

func setupAPIStats(app *server.App) {
	var API = app.API()

	// --------------------------------------------------------------------------
	// Stats
	API.GET("/stats/",
		server.Handler(func(req *wcg.Request) response.Response {
			stats, _ := runtime.Stats(gae.NewContext(req))
			json := map[string]interface{}{
				"version":     lib.Commit,
				"timestamp":   lib.Timestamp,
				"stats":       stats,
				"environment": lib.CurrentEnvironment(),
				"envvars":     lib.GetEnvVars(),
			}
			if _, dsStats, err := entities.DatastoreStat.Get().Key("total_entities_usage").One(req); err != nil {
				json["datastore"] = dsStats
			}

			// use array response for API convention.
			return response.NewJSONResponse(
				[](map[string]interface{}){
					json,
				},
			)
		}))
}
开发者ID:speedland,项目名称:service,代码行数:27,代码来源:api_stats.go

示例9: getIEPG

func getIEPG(id string, f func(req *wcg.Request, iepg *pt.IEPG) response.Response) server.Handler {
	return server.Handler(func(req *wcg.Request) response.Response {
		_, one := IEPG.Get().Key(req.Param(id)).Cache(true).MustOne(req)
		if one == nil {
			return response.NotFound(req)
		}
		return f(req, one.(*pt.IEPG))
	})
}
开发者ID:speedland,项目名称:service,代码行数:9,代码来源:api_iepg_records.go

示例10: setupAPIUsers

func setupAPIUsers(app *server.App) {
	var API = app.API()

	API.GET("/me/",
		server.Handler(func(req *wcg.Request) response.Response {
			if req.User == nil || request.ByGuest(req) {
				return response.NewJSONResponse(nil)
			}
			return response.NewJSONResponse(req.User)
		}))

	API.POST("/me/gates/",
		server.Handler(func(req *wcg.Request) response.Response {
			keys := strings.Split(req.Form("keys"), ",")
			result := gates.EvalKeys(req, keys...)
			return response.NewJSONResponse(result)
		}))
}
开发者ID:speedland,项目名称:service,代码行数:18,代码来源:api_users.go

示例11: EntityGet

func EntityGet(get *entities.Get, keyParam string) server.Handler {
	return server.Handler(
		func(req *wcg.Request) response.Response {
			_, one := get.Key(req.Param(keyParam)).MustOne(req)
			if one == nil {
				return response.APINotFound
			}
			return response.NewJSONResponse(one)
		})
}
开发者ID:speedland,项目名称:service,代码行数:10,代码来源:entity.go

示例12: setupAPIConfigs

func setupAPIConfigs(app *server.App) {
	var API = app.API()
	API.GET("/configs/:userid/messenger.json",
		middleware.Gate("family"),
		validateUserID,
		requireMessengeOptIn,
		server.Handler(
			func(req *wcg.Request) response.Response {
				_, one := MessengerNotification.Get().Key(req.Param("userid")).UseDefaultIfNil(true).Cache(true).MustOne(req)
				return response.NewJSONResponse(one)
			},
		))

	API.PUT("/configs/:userid/messenger.json",
		middleware.Gate("family"),
		validateUserID,
		requireMessengeOptIn,
		middleware.ParseForm(nil),
		middleware.EntityPutOrCreate(MessengerNotification.Put(), "userid"))

	API.POST("/configs/:userid/messenger/notify/",
		middleware.Gate("family"),
		validateUserID,
		requireMessengeOptIn,
		server.Handler(
			func(req *wcg.Request) response.Response {
				content, err := createDailyNotificationContent(req)
				if err != nil {
					return response.InternalServerError(req, err)
				}
				err = messenger.NewMessengerClient(req).SendText(content.title + "\n" + strings.Join(content.lines, "\n"))
				if err != nil {
					req.Logger.Errorf("Failed to notify a message to messenger: %v", err)
				}
				return response.NewJSONResponse(map[string]interface{}{
					"ok": true,
				})
			},
		))

}
开发者ID:speedland,项目名称:service,代码行数:41,代码来源:api_configs.go

示例13: EntityPost

func EntityPost(post *entities.Put) server.Handler {
	return server.Handler(
		func(req *wcg.Request) response.Response {
			ent, err := post.Kind().CreateEntityFromForm(req.HTTPRequest().Form)
			if err != nil { // ParseError
				req.Logger.Warnf("You should use ParseForm middleware to avoid the error in EntityPost: %v", err)
				return response.BadRequest(req, ErrInvalidFormParameters)
			}
			_, ent_ := post.MustUpdate(req, ent)
			return response.NewJSONResponseWithStatus(ent_, 201)
		})
}
开发者ID:speedland,项目名称:service,代码行数:12,代码来源:entity.go

示例14: Test_Parallel

func Test_Parallel(t *testing.T) {
	assert := gaetest.NewAssert(t)
	router := wcg.NewRouter()
	funA := server.Handler(func(req *wcg.Request) response.Response {
		return response.NewJSONResponse(true)
	})
	funB := server.Handler(func(req *wcg.Request) response.Response {
		return response.NewJSONResponse(false)
	})

	router.GET("/*", Parallel(map[string]server.Handler{
		"a": funA,
		"b": funB,
	}))
	req := ts.GET("/a/")
	res := req.RouteTo(router)

	var got map[string]bool
	assert.HTTPStatus(200, res)
	assert.JSONResponse(&got, res)
	assert.OK(got["a"])
	assert.Not(got["b"])
}
开发者ID:speedland,项目名称:service,代码行数:23,代码来源:parallel_test.go

示例15: ValidateQuery

func ValidateQuery(configure func(*validators.FormValidator)) server.Handler {
	if configure == nil {
		panic(fmt.Errorf("You must pass configure function on ValidateQuery"))
	}
	v := validators.NewFormValidator()
	configure(v)
	return server.Handler(
		func(req *wcg.Request) response.Response {
			if err := v.Eval(req.URL().Query()); err != nil {
				return response.BadRequest(req, err)
			}
			return nil
		})
}
开发者ID:speedland,项目名称:service,代码行数:14,代码来源:validate_query.go


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