Exemple #1
0
func TestHTTPRequest(t *testing.T) {
	r := &http.Request{}
	ctx0 := gourdctx.WithHTTPRequest(context.Background(), r)

	if want, have := r, gourdctx.HTTPRequest(ctx0); want != have {
		t.Errorf("expect %#v, got %#v", want, have)
	}
}
Exemple #2
0
func TestClearGorilla(t *testing.T) {
	r := &http.Request{}
	key := "foo"
	val := "bar"

	// endpoint to test
	ep1 := func(ctx context.Context, request interface{}) (response interface{}, err error) {
		gcontext.Set(gourdctx.HTTPRequest(ctx), key, val) // this is tested in TestUseGorilla
		return
	}
	ep2 := gourdctx.ClearGorilla(ep1)

	// fake request to test the endpoint
	ep2(gourdctx.UseGorilla(nil, r), nil)
	if _, ok := gcontext.GetOk(r, key); ok {
		t.Error("still be able to get gorilla context value after clear")
	}
}
Exemple #3
0
// UserStoreEndpoints return CURD endpoints for UserStore
func UserStoreEndpoints(noun, nounp string) (endpoints map[string]endpoint.Endpoint) {

	// variables to use later
	allocEntityList := func() *[]User { return &[]User{} }
	storeKey := KeyUser
	getStore := func(ctx context.Context) (s *UserStore, err error) {
		raw, err := store.Get(ctx, storeKey)
		if err != nil {
			return
		}

		s, ok := raw.(*UserStore)
		if !ok {
			err = fmt.Errorf("store.Get(\"UserStore\") does not return *UserStore")
			return
		}
		return
	}

	// store endpoints here
	// TODO: may have new struct to store
	endpoints = make(map[string]endpoint.Endpoint)

	endpoints["create"] = func(ctx context.Context, e interface{}) (res interface{}, err error) {

		// get context information
		r := gourdctx.HTTPRequest(ctx)
		if r == nil {
			serr := store.ErrorInternal
			serr.ServerMsg = "missing request in context"
			err = serr
			return
		}

		// get store
		s, err := getStore(ctx)
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf("error obtaining %s store (%s)", storeKey, err)
			err = serr
			return
		}
		defer s.Close()

		// create entity
		err = s.Create(nil, e)
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf(
				"error creating %s: %#v, entity: %#v", noun, err.Error(), e)
			err = serr
			return
		}

		// encode response
		res = map[string]interface{}{
			nounp: &[]User{*e.(*User)},
		}
		return

	}

	endpoints["retrieve"] = func(ctx context.Context, request interface{}) (res interface{}, err error) {

		sReq := request.(*httpservice.Request)
		q := sReq.Query

		// get context information
		r := gourdctx.HTTPRequest(ctx)
		if r == nil {
			serr := store.ErrorInternal
			serr.ServerMsg = "missing request in context"
			err = serr
			return
		}

		// get store
		s, err := getStore(ctx)
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf("error obtaining %s store (%s)", storeKey, err)
			err = serr
			return
		}
		defer s.Close()

		// allocate memory for variables
		el := allocEntityList()

		// retrieve
		err = s.Search(q).All(el)
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf("error searching %s: %s",
				noun, err)
			err = serr
			return
		}

		// encode response
		if s.Len(el) == 0 {
			err = store.ErrorNotFound
			return
		}

		res = map[string]interface{}{
			nounp: el,
		}
		return

	}

	endpoints["list"] = func(ctx context.Context, request interface{}) (res interface{}, err error) {

		sReq := request.(*httpservice.Request)
		q := sReq.Query

		// get context information
		r := gourdctx.HTTPRequest(ctx)
		if r == nil {
			serr := store.ErrorInternal
			serr.ServerMsg = "missing request in context"
			err = serr
			return
		}

		// get store
		s, err := getStore(ctx)
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf("error obtaining %s store (%s)", storeKey, err)
			err = serr
			return
		}
		defer s.Close()

		// allocate memory for variables
		el := allocEntityList()

		results := s.Search(q)
		count, err := results.Count()
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf("error counting %s: %s",
				noun, err)
			err = serr
			return
		}

		err = results.All(el)
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf("error searching %s: %s",
				noun, err)
			err = serr
			return
		}

		// TODO: need to fix overflow error of pager variables
		res = map[string]interface{}{
			nounp: el,
			"paging": store.NewPager().
				SetTotal(int(count)).
				SetLimit(int(q.GetLimit()), int(q.GetOffset())),
		}
		return
	}

	endpoints["update"] = func(ctx context.Context, request interface{}) (res interface{}, err error) {

		sReq := request.(*httpservice.Request)
		q := sReq.Query
		e := sReq.Payload
		cond := q.GetConds()

		// get context information
		r := gourdctx.HTTPRequest(ctx)
		if r == nil {
			serr := store.ErrorInternal
			serr.ServerMsg = "missing request in context"
			err = serr
			return
		}

		// get store
		s, err := getStore(ctx)
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf("error obtaining %s store (%s)", storeKey, err)
			err = serr
			return
		}
		defer s.Close()

		// update entity
		if err = s.Update(cond, e); err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf(
				"error encoding %s list: %s",
				noun, err)
			err = serr
			return
		}

		res = map[string]interface{}{
			nounp: &[]User{*e.(*User)},
		}
		return
	}

	endpoints["delete"] = func(ctx context.Context, request interface{}) (res interface{}, err error) {

		// allocate memory for variables
		el := allocEntityList()

		// store query of id
		sReq := request.(*httpservice.Request)
		q := sReq.Query
		cond := q.GetConds()

		// get context information
		r := gourdctx.HTTPRequest(ctx)
		if r == nil {
			serr := store.ErrorInternal
			serr.ServerMsg = "missing request in context"
			err = serr
			return
		}

		// get store
		s, err := getStore(ctx)
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf("error obtaining %s store (%s)", storeKey, err)
			err = serr
			return
		}
		defer s.Close()

		// find the content of the id
		err = s.Search(q).All(el)
		if err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf("error searching %s: %s",
				noun, err)
			err = serr
			return
		}

		// delete entity
		if err = s.Delete(cond); err != nil {
			serr := store.ErrorInternal
			serr.ServerMsg = fmt.Sprintf(
				"error encoding %s list: %s",
				noun, err)
			err = serr
			return
		}

		res = map[string]interface{}{
			nounp: el,
		}
		return
	}

	return
}
Exemple #4
0
func UserStoreServices(paths httpservice.Paths, endpoints map[string]endpoint.Endpoint) (handlers httpservice.Services) {

	// variables to use later
	noun := paths.Noun()
	storeKey := KeyUser
	getStore := func(ctx context.Context) (s *UserStore, err error) {
		raw, err := store.Get(ctx, storeKey)
		if err != nil {
			return
		}

		s, ok := raw.(*UserStore)
		if !ok {
			err = fmt.Errorf(`store.Get(KeyUser) does not return *KeyUser`)
			return
		}
		return
	}

	// define default middlewares
	var prepareCreate endpoint.Middleware = func(inner endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (respond interface{}, err error) {
			// placeholder: anything you want to do with the entity
			//              before append to database
			httpservice.EnforceCreate(request)
			return inner(ctx, request)
		}
	}

	var prepareUpdate endpoint.Middleware = func(inner endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (response interface{}, err error) {

			sReq := request.(*httpservice.Request)

			// get context information
			r := gourdctx.HTTPRequest(ctx)
			if r == nil {
				serr := store.ErrorInternal
				serr.ServerMsg = "missing request in context"
				err = serr
				return
			}

			el := &[]User{}
			q := sReq.Query

			// get store
			s, err := getStore(ctx)
			if err != nil {
				serr := store.ErrorInternal
				serr.ServerMsg = fmt.Sprintf("error obtaining %s store (%s)", storeKey, err)
				err = serr
				return
			}
			defer s.Close()

			// find the previous content of the id
			err = s.Search(q).All(el)
			if err != nil {
				serr := store.ErrorInternal
				serr.ServerMsg = fmt.Sprintf("error searching %s: %s",
					noun.Singular(), err)
				err = serr
				return
			}

			// tell the inner
			if len(*el) > 0 {
				sReq.Previous = &(*el)[0]
			}

			// enforce agreement on sReq.Payload with previous sReq.Entity
			httpservice.EnforceUpdate(sReq.Previous, sReq.Payload)

			// placeholder: anything you want to do with the entity
			//              before update to database
			return inner(ctx, sReq)
		}
	}

	var prepareList endpoint.Middleware = func(inner endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (response interface{}, err error) {
			response, err = inner(ctx, request)
			if err != nil {
				return
			}

			vmap := response.(map[string]interface{})
			list := vmap[noun.Plural()].(*[]User)
			if list == nil || *list == nil {
				*list = make([]User, 0)
			}
			vmap[noun.Plural()] = list

			// placeholder: anything you want to do with the entity
			//              list response
			return vmap, nil
		}
	}

	// wrap inner response with default protocol
	var prepareProtocol endpoint.Middleware = func(inner endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (response interface{}, err error) {

			v, err := inner(ctx, request)
			if err != nil {
				return
			}

			switch v.(type) {
			case map[string]interface{}:
				response = store.ExpandResponse(v.(map[string]interface{}))
			default:
				response = store.NewResponse(noun.Plural(), v)
			}

			return
		}
	}

	// generates response permission checker middleware
	checkPermBefore := func(permission string) endpoint.Middleware {
		return func(inner endpoint.Endpoint) endpoint.Endpoint {
			return func(ctx context.Context, request interface{}) (response interface{}, err error) {
				m := perm.GetMux(ctx)
				err = m.Allow(ctx, permission, request)
				if err != nil {
					return
				}
				return inner(ctx, request)
			}
		}
	}

	// generates request permission checker middleware
	checkPermAfter := func(permission string) endpoint.Middleware {
		return func(inner endpoint.Endpoint) endpoint.Endpoint {
			return func(ctx context.Context, request interface{}) (response interface{}, err error) {

				v, err := inner(ctx, request)
				if err != nil {
					return
				}

				m := perm.GetMux(ctx)
				err = m.Allow(ctx, permission, request, v)
				if err != nil {
					return
				}

				response = v
				return

			}
		}
	}

	//
	// ==== raw decode functions
	//

	decodeServiceIDReq := func(ctx context.Context, r *http.Request) (request *httpservice.Request, err error) {
		id := r.URL.Query().Get(":id") // will change
		cond := store.NewConds().Add("id", id)
		request = &httpservice.Request{
			Request: r,
			Query:   store.NewQuery().SetConds(cond),
		}
		return
	}

	decodeJSONEntity := func(ctx context.Context, r *http.Request) (entity *User, err error) {
		// allocate entity
		entity = &User{}

		// decode request
		dec := json.NewDecoder(r.Body)
		err = dec.Decode(entity)
		return
	}

	//
	// ==== httptransport.DecodeRequestFunc implementations
	//

	// decodeIDReq generically decoded :id field
	// (works with pat based URL routing, router specific)
	var decodeIDReq httptransport.DecodeRequestFunc = func(ctx context.Context, r *http.Request) (request interface{}, err error) {
		return decodeServiceIDReq(ctx, r)
	}

	// decodeListReq decode query for list endpoint
	var decodeListReq httptransport.DecodeRequestFunc = func(ctx context.Context, r *http.Request) (request interface{}, err error) {

		sReq := &httpservice.Request{
			Request: r,
			Query:   store.NewQuery(),
		}

		// parse sort parameter
		sortStr := r.FormValue("sorts")
		if sortStr != "" {
			sorts := strings.Split(sortStr, ",")
			for _, sort := range sorts {
				sReq.Query.Sort(sort)
			}
		}

		// parse paging request parameter
		offset, limit := func(r *http.Request) (o, l uint64) {
			ostr := r.FormValue("offset")
			lstr := r.FormValue("limit")
			if ostr != "" {
				if ot, err := strconv.ParseUint(ostr, 10, 64); err == nil {
					o = ot
				}
			}
			if lstr != "" {
				if lt, err := strconv.ParseUint(lstr, 10, 64); err == nil {
					l = lt
				}
			}
			return
		}(r)

		// retrieve
		sReq.Query.SetOffset(offset)
		sReq.Query.SetLimit(limit)

		request = sReq
		return
	}

	// decodeJSONReq returns a DecodeRequestFunc that decode request
	// into allocated memory structure
	var decodeJSONReq httptransport.DecodeRequestFunc = func(ctx context.Context, r *http.Request) (request interface{}, err error) {
		return decodeJSONEntity(ctx, r)
	}

	// decodeUpdate returns a DecodeRequestFunc that decode request
	var decodeUpdate httptransport.DecodeRequestFunc = func(ctx context.Context, r *http.Request) (request interface{}, err error) {

		sReq, err := decodeServiceIDReq(ctx, r)
		if err != nil {
			return
		}

		sReq.Payload, err = decodeJSONEntity(ctx, r)
		if err != nil {
			return
		}

		request = sReq
		return
	}

	//
	// ==== httpservce.Services
	//

	// define middleware chains of all RESTful endpoints
	handlers = make(map[string]*httpservice.Service)

	handlers["create"] = httpservice.NewJSONService(
		paths.Plural(), endpoints["create"])
	handlers["create"].Weight = 1
	handlers["create"].Methods = []string{"POST"}
	handlers["create"].DecodeFunc = decodeJSONReq
	handlers["create"].Middlewares.Add(httpservice.MWProtocol, prepareProtocol)
	handlers["create"].Middlewares.Add(httpservice.MWPrepare, prepareCreate)
	handlers["create"].Middlewares.Add(httpservice.MWInner,
		checkPermBefore("create "+noun.Singular()))

	handlers["retrieve"] = httpservice.NewJSONService(
		paths.Singular(), endpoints["retrieve"])
	handlers["retrieve"].Methods = []string{"GET"}
	handlers["retrieve"].DecodeFunc = decodeIDReq
	handlers["retrieve"].Middlewares.Add(httpservice.MWProtocol, prepareProtocol)
	handlers["retrieve"].Middlewares.Add(httpservice.MWPrepare, prepareList)
	handlers["retrieve"].Middlewares.Add(httpservice.MWInner,
		checkPermAfter("retrieve "+noun.Singular()))

	handlers["update"] = httpservice.NewJSONService(
		paths.Singular(), endpoints["update"])
	handlers["update"].Methods = []string{"PUT"}
	handlers["update"].DecodeFunc = decodeUpdate
	handlers["update"].Middlewares.Add(httpservice.MWProtocol, prepareProtocol)
	handlers["update"].Middlewares.Add(httpservice.MWPrepare, prepareUpdate)
	handlers["update"].Middlewares.Add(httpservice.MWInner,
		checkPermBefore("update "+noun.Singular()))

	handlers["list"] = httpservice.NewJSONService(
		paths.Plural(), endpoints["list"])
	handlers["list"].Weight = 1
	handlers["list"].Methods = []string{"GET"}
	handlers["list"].DecodeFunc = decodeListReq
	handlers["list"].Middlewares.Add(httpservice.MWProtocol, prepareProtocol)
	handlers["list"].Middlewares.Add(httpservice.MWPrepare, prepareList)
	handlers["list"].Middlewares.Add(httpservice.MWInner,
		checkPermAfter("list "+noun.Singular()))

	handlers["delete"] = httpservice.NewJSONService(
		paths.Singular(), endpoints["delete"])
	handlers["delete"].Methods = []string{"DELETE"}
	handlers["delete"].DecodeFunc = decodeIDReq
	handlers["delete"].Middlewares.Add(httpservice.MWProtocol, prepareProtocol)
	handlers["delete"].Middlewares.Add(httpservice.MWInner,
		checkPermBefore("delete "+noun.Singular()))

	return
}