本文整理匯總了Golang中github.com/drone/routes.ServeJson函數的典型用法代碼示例。如果您正苦於以下問題:Golang ServeJson函數的具體用法?Golang ServeJson怎麽用?Golang ServeJson使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ServeJson函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: printResult
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: getPoint
// 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: removePoint
// 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: CreateUser
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: editPoint
// 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: mapChildNamespaceRoute
// 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: FilterToken
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: connectPoint
// 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: mapTopLevelNamespaceRoute
// 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: adduser
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: isErrNotNil
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: isStatusNotOK
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: UploadFile
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: getPoints
// 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: resultSelectUserSQL
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")
}
}