Пример #1
0
func printResult(w http.ResponseWriter, status int, message string, valueType interface{}) {
	w.WriteHeader(status)
	if isStatusNotOK(w, status, message) {
		routes.ServeJson(w, service.GetErrorMessageType(status, message))
		return
	}
	routes.ServeJson(w, service.GetGeneralMsgType(status, message, valueType))
}
Пример #2
0
// GET /points/:id
func getPoint(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	id, _ := strconv.Atoi(params.Get(":id"))

	var result Point
	err := Points.Find(bson.M{"id": id}).One(&result)
	if err != nil {
		routes.ServeJson(w, Response{"error", 404, "Not Found", nil})
		return
	}
	routes.ServeJson(w, result)
}
Пример #3
0
// DELETE /points/:id
func removePoint(w http.ResponseWriter, r *http.Request) {
	badRequestError := Response{"error", 400, "Bad Request", nil}
	params := r.URL.Query()
	id, _ := strconv.Atoi(params.Get(":id"))

	err := Points.Remove(bson.M{"id": id})
	if err != nil {
		routes.ServeJson(w, badRequestError)
		return
	}
	routes.ServeJson(w, Response{"succsess", 200, "", nil})
}
Пример #4
0
func CreateUser(w http.ResponseWriter, r *http.Request) {
	if r.Header.Get("Authorization") != "1234" {
		w.WriteHeader(500)
		return
	}
	NewUser := atomicUser(newUserJson(r.Body))
	if NewUser.PhoneNumber == "" {
		w.WriteHeader(422)
		routes.ServeJson(w, service.GetErrorMessageType(422, "phone_number is empty"))
		return
	}

	mobileBytes := []byte(NewUser.PhoneNumber)
	hashedPassword, err := bcrypt.GenerateFromPassword(mobileBytes, 10)

	if isErrNotNil(w, 508, err) {
		return
	}

	SQL := fmt.Sprintf("INSERT INTO users SET user_name='%s', phone_number='%s', token = '%s'", NewUser.UserName, NewUser.PhoneNumber, hashedPassword)
	status, message, newId := service.ExecuteInsertSqlResult(SQL)
	userCreated := responses.UserCreated{int(newId), NewUser.UserName, NewUser.PhoneNumber, fmt.Sprintf("%s", hashedPassword)}
	switch {
	case status == http.StatusConflict:
		// 1. Update user_name and token in users
		field := fmt.Sprintf("user_name='%s', token = '%s'", NewUser.UserName, hashedPassword)
		condition := fmt.Sprintf("phone_number = '%s'", NewUser.PhoneNumber)
		statusUpdate, messageUpdate := service.UpdateQuery("users", field, condition)
		if isStatusNotOK(w, statusUpdate, messageUpdate) {
			return
		}
		// 2. Get user_id
		conditionSelect := fmt.Sprintf("phone_number = %s", NewUser.PhoneNumber)
		sequelSelect := service.SelectQuery("user_id", "users", conditionSelect)
		sqlRow, err := service.ExecuteChannelSqlRow(sequelSelect)
		if isErrNotNil(w, 508, err) {
			return
		}
		// 3. Check if result exists
		errSqlRow := sqlRow.Scan(&userCreated.UserId)
		statusRow, messageRow := service.CheckScanRowSQL(errSqlRow)
		if isStatusNotOK(w, statusRow, messageRow) {
			return
		}
		// 4. Return existing mobile_phone with given user_name and new token
		w.WriteHeader(statusRow)
		routes.ServeJson(w, service.GetGeneralMsgType(statusRow, messageRow, userCreated))
	default:
		w.WriteHeader(status)
		routes.ServeJson(w, service.GetGeneralMsgType(status, message, userCreated))
	}
}
Пример #5
0
// PUT /points/:id
func editPoint(w http.ResponseWriter, r *http.Request) {
	badRequestError := Response{"error", 400, "Bad Request", nil}

	var (
		point  Point
		rpoint PointFromRequest
	)

	routes.ReadJson(r, &rpoint)

	params := r.URL.Query()
	id, _ := strconv.Atoi(params.Get(":id"))

	err := Points.Find(bson.M{"id": id}).One(&point)
	if err != nil {
		fmt.Println(err)
		routes.ServeJson(w, badRequestError)
		return
	}

	if rpoint.Ssid != nil {
		point.Ssid = *rpoint.Ssid
	}

	if rpoint.Mac != nil {
		point.Mac = *rpoint.Mac
	}

	if rpoint.Password != nil {
		point.Password = *rpoint.Password
	}

	if rpoint.Latitude != nil {
		point.Latitude = *rpoint.Latitude
	}

	if rpoint.Longitude != nil {
		point.Longitude = *rpoint.Longitude
	}

	Points.Update(bson.M{"id": id}, point)
	if err != nil {
		fmt.Println(err)
		routes.ServeJson(w, badRequestError)
		return
	}

	routes.ServeJson(w, point)
}
Пример #6
0
// mapChildNamespaceRoute sets a handler returning a dictionary of resources
// supported by a certain API version identified by the given namespace
func mapChildNamespaceRoute(route martini.Router, namespace *schema.Namespace) {
	log.Debug("[Path] %s", namespace.GetFullPrefix())
	route.Get(
		namespace.GetFullPrefix(),
		func(w http.ResponseWriter, r *http.Request, p martini.Params, context martini.Context) {
			resources := []schema.NamespaceResource{}
			for _, s := range schema.GetManager().Schemas() {
				if s.NamespaceID == namespace.ID {
					resources = append(resources, schema.NamespaceResource{
						Links: []schema.Link{
							schema.Link{
								Href: s.GetPluralURL(),
								Rel:  "self",
							},
						},
						Name:       s.Singular,
						Collection: s.Plural,
					})
				}
			}

			routes.ServeJson(w, map[string][]schema.NamespaceResource{"resources": resources})
		},
	)
}
Пример #7
0
func FilterToken(w http.ResponseWriter, r *http.Request) {
	method := r.Method
	url := fmt.Sprintf("%s", r.URL)

	allowedMethodUnAuth := (method == "POST")
	listExceptionURL := (url == "/api/v1/users" || url == "/api/v1/users/token")
	serveStaticPath := (strings.Contains(url, "/static/") && method == "GET")

	if !serveStaticPath {
		service.SetHeaderParameterJson(w)
	}

	switch {
	case serveStaticPath:
		return
	case listExceptionURL && allowedMethodUnAuth:
		return
	//TO DO: case create user auth header for api_key & secret_api
	default:
		status, message, mobilePhone := service.GetTokenHeader(r.Header.Get("Authorization"))
		r.Header.Set("mobile_phone", mobilePhone)
		r.Header.Set("status_filter", strconv.Itoa(status))
		if status != 200 {
			w.WriteHeader(status)
			routes.ServeJson(w, responses.DefaultMessage{status, message})
		}
	}
}
Пример #8
0
// POST /points/:id/connection
func connectPoint(w http.ResponseWriter, r *http.Request) {
	badRequestError := Response{"error", 400, "Bad Request", nil}
	params := r.URL.Query()
	id, _ := strconv.Atoi(params.Get(":id"))

	selector := bson.M{"id": id}
	changing := bson.M{"$inc": bson.M{"connections": 1}}
	err := Points.Update(selector, changing)
	if err != nil {
		routes.ServeJson(w, badRequestError)
		return
	}

	connectionsQueue.PushFront(connectionRecord{time.Now().Unix(), id})
	routes.ServeJson(w, Response{"succsess", 200, "", nil})
}
Пример #9
0
// mapTopLevelNamespaceRoute maps route listing available subnamespaces (versions)
// for a top-level namespace
func mapTopLevelNamespaceRoute(route martini.Router, namespace *schema.Namespace) {
	log.Debug("[Path] %s/", namespace.GetFullPrefix())
	route.Get(
		namespace.GetFullPrefix()+"/",
		func(w http.ResponseWriter, r *http.Request, p martini.Params, context martini.Context) {
			versions := []schema.Version{}
			for _, childNamespace := range schema.GetManager().Namespaces() {
				if childNamespace.Parent == namespace.ID {
					versions = append(versions, schema.Version{
						Status: "SUPPORTED",
						ID:     childNamespace.Prefix,
						Links: []schema.Link{
							schema.Link{
								Href: childNamespace.GetFullPrefix() + "/",
								Rel:  "self",
							},
						},
					})
				}
			}

			if len(versions) != 0 {
				versions[len(versions)-1].Status = "CURRENT"
			}

			routes.ServeJson(w, map[string][]schema.Version{"versions": versions})
		})
}
Пример #10
0
func adduser(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	var p Person
	err := decoder.Decode(&p)
	if err != nil {
		fmt.Fprintf(w, "json decode error")
	}
	fmt.Fprintf(w, "id:%s name:%s %s", p.Id, p.Firstname, p.Lastname)

	if p.Firstname != "" && p.Lastname != "" {
		if insert, _ := dbmap.Exec(`INSERT INTO user (firstname, lastname) VALUES (?, ?)`,
			p.Firstname, p.Lastname); insert != nil {
			user_id, err := insert.LastInsertId()
			if err == nil {
				content := &Person{
					Id:        user_id,
					Firstname: p.Firstname,
					Lastname:  p.Lastname,
				}
				routes.ServeJson(w, content)
			}
		} else {
			fmt.Fprintf(w, "Error: insert failed")
		}
	}
	//curl --noproxy localhost http://localhost:9090/users/ -X POST -d '{ "Firstname": "Tsugunao", "Lastname" : "kobayashi"}'
}
Пример #11
0
func isErrNotNil(w http.ResponseWriter, status int, err error) bool {
	if err != nil {
		w.WriteHeader(status)
		routes.ServeJson(w, service.GetErrorMessageType(status, err.Error()))
		return true
	}
	return false
}
Пример #12
0
func isStatusNotOK(w http.ResponseWriter, status int, message string) bool {
	if status != http.StatusOK {
		w.WriteHeader(status)
		routes.ServeJson(w, service.GetErrorMessageType(status, message))
		return true
	}
	return false
}
Пример #13
0
func UploadFile(w http.ResponseWriter, r *http.Request) {
	phoneNumber := r.Header.Get("phone_number")
	file, header, err := r.FormFile("file")
	statusNotAcceptable := http.StatusNotAcceptable
	// 1. Get file from form-data
	if isErrNotNil(w, statusNotAcceptable, err) {
		return
	}
	// 2. Read file
	fileType := header.Header.Get("Content-Type")

	if !allowedImageType(fileType) {
		w.WriteHeader(http.StatusUnsupportedMediaType)
		routes.ServeJson(w, service.GetErrorMessageType(http.StatusUnsupportedMediaType, "type is not allowed"))
		return
	}
	// 3. Generate new filename
	nameFile, errNewPath := service.GenerateNewPath()
	if isErrNotNil(w, statusNotAcceptable, errNewPath) {
		return
	}
	// 4. Read multipart file

	buff, errReadFile := ioutil.ReadAll(file)
	if isErrNotNil(w, statusNotAcceptable, errReadFile) {
		return
	}
	//5. Upload to cloudinary
	resChannelUpload := service.UploadImage(nameFile, buff)
	cloudinaryInfo := <-resChannelUpload
	close(resChannelUpload)
	if cloudinaryInfo.Err != nil {
		internalServerStatus := http.StatusInternalServerError
		w.WriteHeader(internalServerStatus)
		routes.ServeJson(w, service.GetErrorMessageType(internalServerStatus, "internal server error with cloudinary"))
		return
	}
	// 6. Update cloudinary path to profile user
	cloudinaryPath := cloudinaryInfo.FilePath
	field := fmt.Sprintf("profile_picture = '%s'", cloudinaryPath)
	condition := fmt.Sprintf("phone_number = '%s'", phoneNumber)
	statusUpdate, messageUpdate := service.UpdateQuery("users", field, condition)
	profilePictureUser := requests.UserProfilePictureType{phoneNumber, cloudinaryPath}
	printResult(w, statusUpdate, messageUpdate, profilePictureUser)
}
Пример #14
0
// GET /points
func getPoints(w http.ResponseWriter, r *http.Request) {
	var result []Point
	err := Points.Find(bson.M{}).All(&result)
	if err != nil {
		fmt.Println("===============================")
		fmt.Println("error: ", err)
		fmt.Println("===============================")
	}

	routes.ServeJson(w, result)
}
Пример #15
0
func resultSelectUserSQL(w http.ResponseWriter, sequel string) {
	rows, err := service.ExecuteChannelSqlRows(sequel)
	internalServerStatus := http.StatusInternalServerError
	if isErrNotNil(w, internalServerStatus, err) {
		w.WriteHeader(internalServerStatus)
		routes.ServeJson(w, service.GetErrorMessageType(internalServerStatus, err.Error()))
		return
	}
	select {
	case resChanUsers := <-mapUsers(rows):
		if resChanUsers.Datas == nil {
			betterEmptyThanNil := make([]interface{}, 0)
			resChanUsers.Datas = betterEmptyThanNil
		}
		statusOK := http.StatusOK
		w.WriteHeader(statusOK)
		routes.ServeJson(w, service.GetGeneralMsgType(statusOK, "success", resChanUsers))
	case <-service.TimeOutInMilis(service.GlobalTimeOutDB):
		printDefaultMessage(w, 508, "request timeout")
	}
}
Пример #16
0
// GET /points/nearest?lat=*&lng=*&dist=_
func getNearestPoints(w http.ResponseWriter, r *http.Request) {
	badRequestError := Response{"error", 400, "Bad Request", nil}
	params := r.URL.Query()

	lat, err1 := strconv.ParseFloat(params.Get("lat"), 64)
	lng, err2 := strconv.ParseFloat(params.Get("lng"), 64)

	if err1 != nil || err2 != nil {
		routes.ServeJson(w, badRequestError)
		return
	}

	maxDistance := float64(50)
	if d, err := strconv.ParseFloat(params.Get("dist"), 32); err == nil {
		maxDistance = d
	}

	currentPoint := geo.NewPoint(lat, lng)

	var p Point
	result := make([]distanceRecord, 0)
	iter := Points.Find(bson.M{}).Iter()
	for iter.Next(&p) {
		lat, _ := strconv.ParseFloat(p.Latitude, 64)
		lng, _ := strconv.ParseFloat(p.Longitude, 64)

		point := geo.NewPoint(lat, lng)
		distance := currentPoint.GreatCircleDistance(point) * 1000

		if distance <= maxDistance {
			result = append(result, distanceRecord{p.Id, distance})
		}
	}

	slice.Sort(result, func(i, j int) bool {
		return result[i].Distance < result[j].Distance
	})
	routes.ServeJson(w, result)
}
Пример #17
0
func serveResponse(w http.ResponseWriter, context map[string]interface{}) {
	response := context["response"]
	responseCode, ok := context["code"].(int)
	if !ok {
		responseCode = 200
	}
	if 200 <= responseCode && responseCode < 300 {
		w.WriteHeader(responseCode)
		routes.ServeJson(w, response)
	} else {
		message := util.MaybeMap(context["exception"])
		middleware.HTTPJSONError(w, message["message"].(string), responseCode)
	}
}
Пример #18
0
// POST /points
func newPoint(w http.ResponseWriter, r *http.Request) {
	badRequestError := Response{"error", 400, "Bad Request", nil}

	var (
		point  Point
		rpoint PointFromRequest
	)

	routes.ReadJson(r, &rpoint)

	if rpoint.Ssid == nil || rpoint.Latitude == nil || rpoint.Longitude == nil {
		routes.ServeJson(w, badRequestError)
		return
	}

	point.Ssid = *rpoint.Ssid
	point.Latitude = *rpoint.Latitude
	point.Longitude = *rpoint.Longitude

	point.Id = GetCounter("points")
	IncCounter("points")

	if rpoint.Mac != nil {
		point.Mac = *rpoint.Mac
	}

	if rpoint.Password != nil {
		point.Password = *rpoint.Password
	}

	err := Points.Insert(&point)
	if err != nil {
		routes.ServeJson(w, badRequestError)
		return
	}
	routes.ServeJson(w, point)
}
Пример #19
0
func UpdatePhoneNumber(w http.ResponseWriter, r *http.Request) {
	phoneNumber := r.Header.Get("phone_number")
	userTokenJson := requests.PhoneNumberJson{}
	service.DecodeJson(&userTokenJson, r.Body)
	newphoneNumber := userTokenJson.PhoneNumber
	if phoneNumber == "" {
		w.WriteHeader(400)
		routes.ServeJson(w, service.GetErrorMessageType(400, "data empty"))
	} else {
		resultHashed := hashedMobileNumber(phoneNumber)
		field := fmt.Sprintf("phone_number = '%s', token = '%s'", newphoneNumber, resultHashed)
		condition := fmt.Sprintf("phone_number = '%s'", phoneNumber)
		statusUpdate, messageUpdate := service.UpdateQuery("users", field, condition)
		userToken := requests.UserToken{newphoneNumber, resultHashed}
		printResult(w, statusUpdate, messageUpdate, userToken)
	}
}
Пример #20
0
func handleError(writer http.ResponseWriter, err error) {
	switch err := err.(type) {
	default:
		middleware.HTTPJSONError(writer, err.Error(), http.StatusInternalServerError)
	case resources.ResourceError:
		code := problemToResponseCode(err.Problem)
		middleware.HTTPJSONError(writer, err.Message, code)
	case extension.Error:
		message, code := unwrapExtensionException(err.ExceptionInfo)
		if 200 <= code && code < 300 {
			writer.WriteHeader(code)
			routes.ServeJson(writer, message)
		} else {
			middleware.HTTPJSONError(writer, message["error"].(string), code)
		}
	}
}
Пример #21
0
func getusers(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "get users")
	type Users []Person

	/*
	   var users = Users {
	       Person{Id:1, Firstname:"Tsugunao", Lastname:"Kobayashi"},
	       Person{Id:2, Firstname:"Yuka", Lastname:"Kobayashi"},
	   }
	*/

	var users []Person
	_, err := dbmap.Select(&users, "SELECT * FROM user")
	if err == nil {
		routes.ServeJson(w, &users)
	} else {
		fmt.Fprintf(w, "Error: no users in the table")
	}
	//routes.ServeJson(w, &users)
	// curl --noproxy localhost http://localhost:9090/users
}
Пример #22
0
//MapRouteBySchemas setup route for all loaded schema
func MapRouteBySchemas(server *Server, dataStore db.DB) {
	route := server.martini
	log.Debug("[Initializing Routes]")
	schemaManager := schema.GetManager()
	route.Get("/_all", func(w http.ResponseWriter, r *http.Request, p martini.Params, auth schema.Authorization) {
		responses := make(map[string]interface{})
		context := map[string]interface{}{
			"path":          r.URL.Path,
			"http_request":  r,
			"http_response": w,
		}
		for _, s := range schemaManager.Schemas() {
			policy, role := authorization(w, r, schema.ActionRead, s.GetPluralURL(), s, auth)
			if policy == nil {
				continue
			}
			context["policy"] = policy
			context["role"] = role
			context["auth"] = auth
			context["sync"] = server.sync
			if err := resources.GetResources(
				context, dataStore,
				s,
				resources.FilterFromQueryParameter(
					s, r.URL.Query()), nil); err != nil {
				handleError(w, err)
				return
			}
			resources.ApplyPolicyForResources(context, s)
			response := context["response"].(map[string]interface{})
			responses[s.GetDbTableName()] = response[s.Plural]
		}
		routes.ServeJson(w, responses)
	})
	for _, s := range schemaManager.Schemas() {
		MapRouteBySchema(server, dataStore, s)
	}
}
Пример #23
0
func modifyuser(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	id := params.Get(":id")
	fmt.Fprintf(w, "user updated: id:%s", id)

	var user Person
	err := dbmap.SelectOne(&user, "SELECT * FROM user WHERE id=?", id)
	if err == nil {
		decoder := json.NewDecoder(r.Body)
		var p Person
		err := decoder.Decode(&p)
		if err != nil {
			fmt.Fprintf(w, "json decode error")
		}

		user_id, _ := strconv.ParseInt(id, 0, 64)
		content := Person{
			Id:        user_id,
			Firstname: p.Firstname,
			Lastname:  p.Lastname,
		}
		if content.Firstname != "" && content.Lastname != "" {
			_, err = dbmap.Update(&content)
			if err == nil {
				routes.ServeJson(w, content)
			} else {
				checkErr(err, "Update failed")
			}
		} else {
			fmt.Fprintf(w, "Error: fields are empty")
		}
	} else {
		fmt.Fprintf(w, "Error: user not found")
	}
	// curl --noproxy localhost http://localhost:9090/users/3 -X PUT -d '{ "Firstname": "Tsugu", "Lastname":"kobayashi"}'

}
Пример #24
0
func getuser(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	id := params.Get(":id")
	fmt.Fprintf(w, "get user: id:%s", id)
	/*
	   user_id, _ := strconv.ParseInt(id, 0, 64)
	   if user_id == 1{
	       person :=  &Person{Id:1, Firstname:"Tsugunao", Lastname:"Kobayashi"}
	       data, err := json.Marshal(person)
	       if err != nil {
	           fmt.Println(err)
	       }
	       fmt.Fprintf(w, "%s\n", string(data))
	       //routes.ServeJson(w, &person)
	   } else if user_id == 2 {
	       person :=  &Person{Id:1, Firstname:"Yuka", Lastname:"Kobayashi"}
	       routes.ServeJson(w, &person)
	   } else {
	       fmt.Fprintf(w, "Error id %d is not defined", id)
	   }
	*/
	var user Person
	err := dbmap.SelectOne(&user, "SELECT * FROM user WHERE id=?", id)

	if err == nil {
		user_id, _ := strconv.ParseInt(id, 0, 64)
		content := &Person{
			Id:        user_id,
			Firstname: user.Firstname,
			Lastname:  user.Lastname,
		}
		routes.ServeJson(w, content)
	} else {
		fmt.Fprintf(w, "Error id %d is not defined", id)
	}
	//curl --noproxy localhost http://localhost:9090/users/1
}
Пример #25
0
func GenerateNewToken(w http.ResponseWriter, r *http.Request) {
	userId := 0
	userTokenJson := requests.PhoneNumberJson{}
	service.DecodeJson(&userTokenJson, r.Body)

	sqlRow, err := service.ExecuteChannelSqlRow(getUserIdSQL(userTokenJson.PhoneNumber))
	if isErrNotNil(w, 508, err) {
		return
	}
	errSqlRow := sqlRow.Scan(&userId)
	status, message := service.CheckScanRowSQL(errSqlRow)
	if isStatusNotOK(w, status, message) {
		return
	}
	phoneNumber := userTokenJson.PhoneNumber
	resultHashed := hashedMobileNumber(phoneNumber)
	statusInsertToken, messageInsertToken := insertTokenToUsersTable(resultHashed, phoneNumber)
	w.WriteHeader(statusInsertToken)
	if isStatusNotOK(w, statusInsertToken, messageInsertToken) {
		return
	}
	userToken := requests.UserToken{phoneNumber, resultHashed}
	routes.ServeJson(w, service.GetGeneralMsgType(statusInsertToken, messageInsertToken, userToken))
}
Пример #26
0
//MapRouteBySchema setup api route by schema
func MapRouteBySchema(server *Server, dataStore db.DB, s *schema.Schema) {
	if s.IsAbstract() {
		return
	}
	route := server.martini

	singleURL := s.GetSingleURL()
	pluralURL := s.GetPluralURL()
	singleURLWithParents := s.GetSingleURLWithParents()
	pluralURLWithParents := s.GetPluralURLWithParents()

	//load extension environments
	environmentManager := extension.GetManager()
	if _, ok := environmentManager.GetEnvironment(s.ID); !ok {
		env, err := server.NewEnvironmentForPath(s.ID, pluralURL)
		if err != nil {
			log.Fatal(fmt.Sprintf("[%s] %v", pluralURL, err))
		}
		environmentManager.RegisterEnvironment(s.ID, env)
	}

	log.Debug("[Plural Path] %s", pluralURL)
	log.Debug("[Singular Path] %s", singleURL)
	log.Debug("[Plural Path With Parents] %s", pluralURLWithParents)
	log.Debug("[Singular Path With Parents] %s", singleURLWithParents)

	//setup list route
	getPluralFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
		addJSONContentTypeHeader(w)
		fillInContext(context, dataStore, r, w, s, p, server.sync, identityService, server.queue)
		if err := resources.GetMultipleResources(context, dataStore, s, r.URL.Query()); err != nil {
			handleError(w, err)
			return
		}
		w.Header().Add("X-Total-Count", fmt.Sprint(context["total"]))
		routes.ServeJson(w, context["response"])
	}
	route.Get(pluralURL, middleware.Authorization(schema.ActionRead), getPluralFunc)
	route.Get(pluralURLWithParents, middleware.Authorization(schema.ActionRead), func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
		addParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])
		getPluralFunc(w, r, p, identityService, context)
	})

	//setup show route
	getSingleFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
		addJSONContentTypeHeader(w)
		fillInContext(context, dataStore, r, w, s, p, server.sync, identityService, server.queue)
		id := p["id"]
		if err := resources.GetSingleResource(context, dataStore, s, id); err != nil {
			handleError(w, err)
			return
		}
		routes.ServeJson(w, context["response"])
	}
	route.Get(singleURL, middleware.Authorization(schema.ActionRead), getSingleFunc)
	route.Get(singleURLWithParents, middleware.Authorization(schema.ActionRead), func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
		addParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])
		getSingleFunc(w, r, p, identityService, context)
	})

	//setup delete route
	deleteSingleFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
		addJSONContentTypeHeader(w)
		fillInContext(context, dataStore, r, w, s, p, server.sync, identityService, server.queue)
		id := p["id"]
		if err := resources.DeleteResource(context, dataStore, s, id); err != nil {
			handleError(w, err)
			return
		}
		w.WriteHeader(http.StatusNoContent)
	}
	route.Delete(singleURL, middleware.Authorization(schema.ActionDelete), deleteSingleFunc)
	route.Delete(singleURLWithParents, middleware.Authorization(schema.ActionDelete), func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
		addParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])
		deleteSingleFunc(w, r, p, identityService, context)
	})

	//setup create route
	postPluralFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
		addJSONContentTypeHeader(w)
		fillInContext(context, dataStore, r, w, s, p, server.sync, identityService, server.queue)
		dataMap, err := middleware.ReadJSON(r)
		if err != nil {
			handleError(w, resources.NewResourceError(err, fmt.Sprintf("Failed to parse data: %s", err), resources.WrongData))
			return
		}
		dataMap = removeResourceWrapper(s, dataMap)
		if s.Parent != "" {
			if _, ok := dataMap[s.ParentID()]; !ok {
				queryParams := r.URL.Query()
				parentIDParam := queryParams.Get(s.ParentID())
				if parentIDParam != "" {
					dataMap[s.ParentID()] = parentIDParam
				}
			}
		}
		if err := resources.CreateResource(context, dataStore, identityService, s, dataMap); err != nil {
			handleError(w, err)
			return
		}
		w.WriteHeader(http.StatusCreated)
		routes.ServeJson(w, context["response"])
	}
	route.Post(pluralURL, middleware.Authorization(schema.ActionCreate), postPluralFunc)
	route.Post(pluralURLWithParents, middleware.Authorization(schema.ActionCreate),
		func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
			addParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])
			postPluralFunc(w, r, p, identityService, context)
		})

	//setup create or update route
	putSingleFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
		addJSONContentTypeHeader(w)
		fillInContext(context, dataStore, r, w, s, p, server.sync, identityService, server.queue)
		id := p["id"]
		dataMap, err := middleware.ReadJSON(r)
		if err != nil {
			handleError(w, resources.NewResourceError(err, fmt.Sprintf("Failed to parse data: %s", err), resources.WrongData))
			return
		}
		dataMap = removeResourceWrapper(s, dataMap)
		if isCreated, err := resources.CreateOrUpdateResource(
			context, dataStore, identityService, s, id, dataMap); err != nil {
			handleError(w, err)
			return
		} else if isCreated {
			w.WriteHeader(http.StatusCreated)
		}
		routes.ServeJson(w, context["response"])
	}
	route.Put(singleURL, middleware.Authorization(schema.ActionUpdate), putSingleFunc)
	route.Put(singleURLWithParents, middleware.Authorization(schema.ActionUpdate),
		func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
			addParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])
			putSingleFunc(w, r, p, identityService, context)
		})

	//setup update route
	patchSingleFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
		addJSONContentTypeHeader(w)
		fillInContext(context, dataStore, r, w, s, p, server.sync, identityService, server.queue)
		id := p["id"]
		dataMap, err := middleware.ReadJSON(r)
		if err != nil {
			handleError(w, resources.NewResourceError(err, fmt.Sprintf("Failed to parse data: %s", err), resources.WrongData))
			return
		}
		dataMap = removeResourceWrapper(s, dataMap)
		if err := resources.UpdateResource(
			context, dataStore, identityService, s, id, dataMap); err != nil {
			handleError(w, err)
			return
		}
		routes.ServeJson(w, context["response"])
	}
	route.Patch(singleURL, middleware.Authorization(schema.ActionUpdate), patchSingleFunc)
	route.Patch(singleURLWithParents, middleware.Authorization(schema.ActionUpdate),
		func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {
			addParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])
			patchSingleFunc(w, r, p, identityService, context)
		})

	//Custom action support
	for _, actionExt := range s.Actions {
		action := actionExt
		ActionFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params,
			identityService middleware.IdentityService, auth schema.Authorization, context middleware.Context) {
			addJSONContentTypeHeader(w)
			fillInContext(context, dataStore, r, w, s, p, server.sync, identityService, server.queue)
			id := p["id"]
			input := make(map[string]interface{})
			if action.InputSchema != nil {
				var err error
				input, err = middleware.ReadJSON(r)
				if err != nil {
					handleError(w, resources.NewResourceError(err, fmt.Sprintf("Failed to parse data: %s", err), resources.WrongData))
					return
				}
			}

			// TODO use authorization middleware
			manager := schema.GetManager()
			path := r.URL.Path
			policy, role := manager.PolicyValidate(action.ID, path, auth)
			if policy == nil {
				middleware.HTTPJSONError(w, fmt.Sprintf("No matching policy: %s %s %s", action, path, s.Actions), http.StatusUnauthorized)
				return
			}
			context["policy"] = policy
			context["tenant_id"] = auth.TenantID()
			context["auth_token"] = auth.AuthToken()
			context["role"] = role
			context["catalog"] = auth.Catalog()
			context["auth"] = auth

			if err := resources.ActionResource(
				context, dataStore, identityService, s, action, id, input); err != nil {
				handleError(w, err)
				return
			}
			routes.ServeJson(w, context["response"])
		}
		route.AddRoute(action.Method, s.GetActionURL(action.Path), ActionFunc)
	}
}
Пример #27
0
func videoReady(w http.ResponseWriter, videoReady bool) {
	routes.ServeJson(w, map[string]interface{}{"video_ready": videoReady})
}
Пример #28
0
func index(w http.ResponseWriter, r *http.Request) {
	routes.ServeJson(w, httpInstance.bitTorrent.GetTorrentInfos())
}
Пример #29
0
func printDefaultMessage(w http.ResponseWriter, status int, message string) {
	w.WriteHeader(status)
	routes.ServeJson(w, service.GetDefaultMessage(status, message))
}
Пример #30
0
// The index handler
func IndexHandler(w http.ResponseWriter, req *http.Request) {
	msgDict := map[string]string{"Name": "S3Proxy", "Description": "An AWS S3 proxy server"}
	routes.ServeJson(w, &msgDict)
	return
}