本文整理汇总了Golang中github.com/ant0ine/go-json-rest/rest.Error函数的典型用法代码示例。如果您正苦于以下问题:Golang Error函数的具体用法?Golang Error怎么用?Golang Error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Error函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: GetStatus
func GetStatus(w rest.ResponseWriter, r *rest.Request) {
Token := r.PathParam("Token")
if Token == "" {
rest.Error(w, "Token required", 400)
return
}
dbConn, err := util.GetConnection(CLUSTERADMIN_DB)
if err != nil {
logit.Error.Println("BackupNow: error " + err.Error())
rest.Error(w, err.Error(), 400)
return
}
defer dbConn.Close()
err = secimpl.Authorize(dbConn, Token, "perm-read")
if err != nil {
logit.Error.Println("GetStatus: validate token error " + err.Error())
rest.Error(w, err.Error(), http.StatusUnauthorized)
return
}
ID := r.PathParam("ID")
if ID == "" {
rest.Error(w, "ID required", 400)
return
}
stat, err := backup.GetStatus(dbConn, ID)
if err != nil {
logit.Error.Println("GetStatus: " + err.Error())
rest.Error(w, err.Error(), 400)
return
}
w.WriteHeader(http.StatusOK)
w.WriteJson(stat)
}
开发者ID:CrunchyData,项目名称:crunchy-postgresql-manager-openshift,代码行数:35,代码来源:backupmgmt.go
示例2: MiddlewareFunc
func (mw *SemVerMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {
minVersion, err := semver.NewVersion(mw.MinVersion)
if err != nil {
panic(err)
}
maxVersion, err := semver.NewVersion(mw.MaxVersion)
if err != nil {
panic(err)
}
return func(writer rest.ResponseWriter, request *rest.Request) {
version, err := semver.NewVersion(request.PathParam("version"))
if err != nil {
rest.Error(writer, "Invalid version: "+err.Error(), http.StatusBadRequest)
return
}
if version.LessThan(*minVersion) {
rest.Error(writer, "Min supported version is "+minVersion.String(), http.StatusBadRequest)
return
}
if maxVersion.LessThan(*version) {
rest.Error(writer, "Max supported version is "+maxVersion.String(), http.StatusBadRequest)
return
}
request.Env["VERSION"] = version
handler(writer, request)
}
}
开发者ID:mehulsbhatt,项目名称:gotelium,代码行数:34,代码来源:middlewares.go
示例3: GetCluster
// GetCluster returns a given cluster definition
func GetCluster(w rest.ResponseWriter, r *rest.Request) {
dbConn, err := util.GetConnection(CLUSTERADMIN_DB)
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), 400)
return
}
defer dbConn.Close()
err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read")
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), http.StatusUnauthorized)
return
}
ID := r.PathParam("ID")
results, err := admindb.GetCluster(dbConn, ID)
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), http.StatusBadRequest)
}
cluster := types.Cluster{}
cluster.ID = results.ID
cluster.ProjectID = results.ProjectID
cluster.Name = results.Name
cluster.ClusterType = results.ClusterType
cluster.Status = results.Status
cluster.CreateDate = results.CreateDate
cluster.Containers = results.Containers
//logit.Info.Println("GetCluser:db call results=" + results.ID)
w.WriteJson(&cluster)
}
开发者ID:rogervaas,项目名称:crunchy-postgresql-manager,代码行数:35,代码来源:clustermgmt.go
示例4: GetChallenge
// GetChallenge Return with the next card to recal.
func GetChallenge(w rest.ResponseWriter, r *rest.Request) {
var challenge *learning.Challenge
ls := r.PathParam("learning_service")
service, err := learning.GetService(ls)
if err != nil {
log.Println("GetChallenge: Failed to load learning service", err)
rest.Error(w, "Failed to get challenge", 404)
}
uid, err := uuid.NewV4()
if err != nil {
log.Printf("GetChallenge: Failed to generate new UUID: %s", err)
rest.Error(w, "Failed to get challenge", 404)
}
challenge, err = service.WhatToLearn(uid.String())
if err != nil {
log.Println("GetChallenge: Failed to load next challange", err)
rest.Error(w, "Failed to get challenge", 404)
}
log.Printf("GetChallenge: challenge: +%v", challenge)
w.WriteJson(challenge)
}
开发者ID:hairqles,项目名称:scholar,代码行数:26,代码来源:endpoints.go
示例5: GetQueues
// GetQueues ...
func GetQueues(w rest.ResponseWriter, r *rest.Request) {
accountID, applicationName, _, err := queueParams(r)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b := GetBase(r)
lp := parseListQuery(r)
var queues []*models.Queue
lr := &models.ListResult{
List: &queues,
}
if err := b.GetQueues(accountID, applicationName, lp, lr); err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if lr.Count == 0 {
rest.NotFound(w, r)
return
}
rt := make([]*Queue, len(queues))
for idx, queue := range queues {
rt[idx] = NewQueueFromModel(queue)
}
w.WriteJson(models.ListResult{
List: rt,
HasMore: lr.HasMore,
Total: lr.Total,
Count: lr.Count,
Page: lr.Page,
Pages: lr.Pages,
})
}
开发者ID:johnnoone,项目名称:hooky,代码行数:36,代码来源:queue.go
示例6: DockerStop
func DockerStop(w rest.ResponseWriter, r *rest.Request) {
logit.Info.Println("DockerStop called")
req := DockerStopRequest{}
err := r.DecodeJsonPayload(&req)
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
docker, err3 := dockerapi.NewClient("unix://var/run/docker.sock")
if err3 != nil {
logit.Error.Println("can't get connection to docker socket")
rest.Error(w, err3.Error(), http.StatusInternalServerError)
return
}
err3 = docker.StopContainer(req.ContainerName, 10)
if err3 != nil {
logit.Error.Println("can't stop container " + req.ContainerName)
rest.Error(w, err3.Error(), http.StatusInternalServerError)
return
}
var response DockerStopResponse
response.Output = "success"
w.WriteJson(&response)
}
开发者ID:CrunchyData,项目名称:crunchy-postgresql-manager-openshift,代码行数:26,代码来源:docker.go
示例7: UpdateUser
// UpdateUser Updates user by user id.
func UpdateUser(w rest.ResponseWriter, r *rest.Request) {
var err error
u, err := user.New()
if err != nil {
log.Printf("UpdateUser: User update failed: %s", err)
rest.Error(w, "User update failed", 500)
return
}
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&u)
if err != nil {
log.Printf("UpdateUser: Failed to decode request body: %s", err)
rest.Error(w, "Failed to decode request body", 500)
return
}
if u.Uid == "" {
log.Println("UpdateUser: Missing user id")
rest.Error(w, "Missing user id", 422)
return
}
if err := user.GetHandler().SaveUser(*u); err != nil {
log.Printf("UpdateUser: Failed to update user: %s", err)
rest.Error(w, "User update failed", 500)
return
}
log.Printf("UpdateUser: User update was successful (%s)", u.Uid)
}
开发者ID:hairqles,项目名称:scholar,代码行数:33,代码来源:endpoints.go
示例8: SendStaticMainHtml
func (i *Impl) SendStaticMainHtml(w rest.ResponseWriter, r *rest.Request) {
rw := w.(http.ResponseWriter)
i.DumpRequestHeader(r)
i.SetResponseContentType("text/html", &w)
htmlData, err := ioutil.ReadFile("index.html")
if err != nil {
rest.Error(w, err.Error(), http.StatusNoContent)
return
}
htmlData, err = i.ReplaceStaticTemplates(htmlData)
if err != nil {
rest.Error(w, err.Error(), http.StatusNoContent)
return
}
// Write the bytes back
rw.WriteHeader(http.StatusOK)
var x int
x, err = rw.Write(htmlData)
if err != nil {
rest.Error(w, fmt.Sprintf("Failed to write %d bytes: %s", x, err.Error()), http.StatusNoContent)
return
}
}
开发者ID:jimmytuc,项目名称:intogooglego,代码行数:27,代码来源:restPostServer.go
示例9: translations
func translations(w rest.ResponseWriter, r *rest.Request) {
var req data.MultiTranslationReq
err := r.DecodeJsonPayload(&req)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if req.Targets == nil {
rest.Error(w, "target locales required", 400)
return
}
if req.Source == "" {
rest.Error(w, "source locale required", 400)
return
}
if len(req.Query) > maxQueryLen {
rest.Error(w, fmt.Sprintf("Max query length is %d", maxQueryLen), 400)
return
}
resp, err := translation.Translate(req)
if err != nil {
rest.Error((w), err.Error(), 500)
return
}
w.WriteJson(resp)
}
开发者ID:eicca,项目名称:smart-translate-server,代码行数:27,代码来源:rest.go
示例10: GetProject
func GetProject(w rest.ResponseWriter, r *rest.Request) {
dbConn, err := util.GetConnection(CLUSTERADMIN_DB)
if err != nil {
logit.Error.Println("BackupNow: error " + err.Error())
rest.Error(w, err.Error(), 400)
return
}
defer dbConn.Close()
err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read")
if err != nil {
logit.Error.Println("GetProject: validate token error " + err.Error())
rest.Error(w, err.Error(), http.StatusUnauthorized)
return
}
ID := r.PathParam("ID")
if ID == "" {
logit.Error.Println("GetProject: error Project ID required")
rest.Error(w, "Project ID required", http.StatusBadRequest)
return
}
results, err := admindb.GetProject(dbConn, ID)
if err != nil {
logit.Error.Println("GetProject:" + err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
project := Project{results.ID, results.Name, results.Desc, results.UpdateDate, "", results.Containers, results.Clusters}
w.WriteJson(&project)
}
开发者ID:CrunchyData,项目名称:crunchy-postgresql-manager-openshift,代码行数:34,代码来源:projectmgmt.go
示例11: DeletePost
func (api *Api) DeletePost(w rest.ResponseWriter, r *rest.Request) {
_, err := api.validateAuthHeader(r.Request)
if err != nil {
rest.Error(w, "Authorization invalid", http.StatusUnauthorized)
return
}
_id := r.PathParam("id")
id, err := strconv.ParseInt(_id, 10, 64)
post := db.Post{}
if err = api.First(&post, id).Error; err != nil {
if err == gorm.RecordNotFound {
rest.NotFound(w, r)
return
} else {
log.Println(gormLoadError("post"), err)
rest.Error(w, INTERNALERROR, http.StatusInternalServerError)
return
}
}
if err := api.Delete(&post).Error; err != nil {
log.Println(gormDeleteError("post"), err)
rest.Error(w, INTERNALERROR, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
开发者ID:Zwiebelring,项目名称:zwiebelnetz,代码行数:31,代码来源:post_controller.go
示例12: MiddlewareFunc
func (a *authMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {
return func(w rest.ResponseWriter, r *rest.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
rest.Error(w, "Not authorized.", 401)
return
}
authHeaderParts := strings.SplitN(authHeader, " ", 2)
if len(authHeaderParts) != 2 || authHeaderParts[0] != "Bearer" {
rest.Error(w, "Not authorized.", 401)
return
}
token, err := jwt.Parse(authHeaderParts[1], func(token *jwt.Token) (interface{}, error) {
if jwt.GetSigningMethod("HS256") != token.Method {
rest.Error(w, "Invalid signing token algorithm.", 500)
return nil, nil
}
return []byte(""), nil
})
r.Env["token"] = token
r.Env["user"] = token.Claims["user"]
if err != nil {
rest.Error(w, err.Error(), 500)
return
}
handler(w, r)
}
}
开发者ID:jonahglover,项目名称:realbase,代码行数:35,代码来源:middleware.go
示例13: PutTask
// PutTask ...
func PutTask(w rest.ResponseWriter, r *rest.Request) {
accountID, applicationName, taskName, err := taskParams(r)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
rt := &Task{}
if err := r.DecodeJsonPayload(rt); err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var active bool
if rt.Active == nil {
active = true
} else {
active = *rt.Active
}
b := GetBase(r)
task, err := b.NewTask(accountID, applicationName, taskName, rt.Queue, rt.URL, rt.HTTPAuth, rt.Method, rt.Headers, rt.Payload, rt.Schedule, rt.Retry, active)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(NewTaskFromModel(task))
}
开发者ID:yonglehou,项目名称:hooky,代码行数:27,代码来源:task.go
示例14: handleReload
func (srv *Server) handleReload(res rest.ResponseWriter, req *rest.Request) {
if srv.ReloadDisabled {
srv.logger.Printf("client was denied reload\n")
rest.Error(res, "reload disabled", 400)
return
}
srv.logger.Printf("client requested reload\n")
var err error
if req.ContentLength > 0 {
data := make(map[string]interface{})
if err = req.DecodeJsonPayload(&data); err != nil {
srv.logger.Printf("client provided invalid context\n")
rest.Error(res, err.Error(), 400)
return
}
err = srv.hooks.Reload(data)
} else {
err = srv.hooks.Reload(nil)
}
if err == nil {
res.WriteJson(&success{"reloaded service"})
} else {
rest.Error(res, err.Error(), 500)
}
}
开发者ID:snowsnail,项目名称:remotectl,代码行数:27,代码来源:server.go
示例15: GetNwayEvents
/*
可用
curl -i -u 1000:1234 http://192.168.1.140:8080/events
*/
func GetNwayEvents(w rest.ResponseWriter, r *rest.Request) {
//authHeader := r.Header.Get("Authorization")
userId := r.Env["REMOTE_USER"]
fmt.Println(userId)
//var strsql string
//strsql := "'" + userId + "'"
fmt.Println("before check")
rows, err := DB.Query("SELECT a.id, a.aleg_number, a.bleg_number, a.router_number::text, a.event_id, a.event_time::text FROM call_in_out_event a ,call_extension b where a.is_read=False and a.extension_id =b.id and b.extension_number=$1", userId)
if err != nil {
//log.Fatal("failed to scan", err)
fmt.Println("failed to NwayEvents")
fmt.Println(err)
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println("after check")
NwayEvents := make([]NwayEvent, 0)
defer rows.Close()
var id int64
//var my sql.NullString
var alegNumber string
var blegNumber string
var routeNumber sql.NullString
var eventId int
var eventTime string
for rows.Next() {
fmt.Println("Sacn to NwayEvents")
err := rows.Scan(&id, &alegNumber, &blegNumber, &routeNumber, &eventId, &eventTime)
if err != nil {
fmt.Println(err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt, err := DB.Prepare("update call_in_out_event set is_read=True where id=$1")
if err != nil {
fmt.Println(err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = stmt.Exec(id)
if err != nil {
fmt.Println(err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var ne NwayEvent
ne.AlegNumber = alegNumber
ne.BlegNumber = blegNumber
ne.EventTime = eventTime
ne.EventId = eventId
ne.RouteNumber = routeNumber.String
NwayEvents = append(NwayEvents, ne)
//fmt.Println(result)
}
w.WriteJson(
NwayEvents,
)
}
开发者ID:nwaycn,项目名称:restful,代码行数:64,代码来源:nway_restful.go
示例16: suggestions
func suggestions(w rest.ResponseWriter, r *rest.Request) {
var req data.SuggestionReq
err := r.DecodeJsonPayload(&req)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if req.FallbackLocale == "" {
req.FallbackLocale = data.Locale("en")
}
if req.Locales == nil {
rest.Error(w, "locales required", 400)
return
}
if len(req.Query) > maxQueryLen {
rest.Error(w, fmt.Sprintf("Max query length is %d", maxQueryLen), 400)
return
}
resp, err := glosbe.Suggest(req)
if err != nil {
rest.Error((w), err.Error(), 500)
return
}
w.WriteJson(resp)
}
开发者ID:eicca,项目名称:smart-translate-server,代码行数:27,代码来源:rest.go
示例17: PostDoc
// PostDoc uses save to save a document
func PostDoc(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
collection := r.PathParam("collection")
// Make sure that the user owns what they are trying to save
_, ok := r.Env["JWT_PAYLOAD"].(map[string]interface{})["backend"]
if !ok && r.Env["REMOTE_USER"] != id {
rest.Error(w, "Cannot modify another users data", http.StatusInternalServerError)
return
}
var doc map[string]interface{}
err := r.DecodeJsonPayload(&doc)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println(doc)
err = save.Save(collection, doc)
if err != nil {
log.Println(err)
rest.Error(w, "Could not save", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.(http.ResponseWriter).Write(variables.BlankResponse)
}
开发者ID:pdxjohnny,项目名称:numapp,代码行数:26,代码来源:post.go
示例18: putDataE
func putDataE(w rest.ResponseWriter, r *rest.Request) {
host := r.PathParam("host")
if host == "" {
rest.Error(w, "host is empty", 400)
return
}
var jsonBody []byte
jsonBody, _ = ioutil.ReadAll(r.Body)
//if err != nil { log.Fatal(err) }
simpleDataFromBody, err2 := simplejson.NewJson(jsonBody)
if err2 != nil {
rest.Error(w, "body (json) is empty", 400)
return
}
if simpleDataFromBody.Get("message").MustString() == "" {
rest.Error(w, "message for "+host+" is not valued", 400)
return
}
if simpleDataFromBody.Get("details").MustString() == "" {
rest.Error(w, "details for "+host+" is not valued", 400)
return
}
CompteurE++
if CompteurE%2 == 0 {
time.Sleep(500 * time.Millisecond)
}
defer r.Body.Close()
w.Header().Set("X-Host", host)
}
开发者ID:jlandure,项目名称:go_server_mock,代码行数:32,代码来源:go_mock.go
示例19: Register
func Register(w rest.ResponseWriter, r *rest.Request) {
var form struct {
Id string `json:"username"`
Pass string `json:"password"`
}
r.DecodeJsonPayload(&form)
if form.Pass == "" {
rest.Error(w, "Invalid input", 400)
return
}
res, err := userRepository.GetUserById(form.Id)
if res != "" {
rest.Error(w, "[username]exists", 400)
return
}
user := &domain.User{Id: form.Id, Pass: domain.HashPassword(form.Pass)}
bytes, _ := json.Marshal(user)
userRepository.SaveUserById(form.Id, string(bytes))
res, err = userRepository.GetUserById(form.Id)
log.Println(res, err)
w.WriteJson(map[string]string{"Status": "OK"})
}
开发者ID:unitrans,项目名称:unitrans,代码行数:25,代码来源:web_api.go
示例20: GetServer
// GetServer return a server definition
func GetServer(w rest.ResponseWriter, r *rest.Request) {
dbConn, err := util.GetConnection(CLUSTERADMIN_DB)
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), 400)
return
}
defer dbConn.Close()
err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read")
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), http.StatusUnauthorized)
return
}
ID := r.PathParam("ID")
//logit.Info.Println("in GetServer with ID=" + ID)
//currently no state about a server is maintained other than IP and port number
//which we use for the ID, Name, and IPAddress values
server := types.Server{ID, ID, ID, ID, "", "", ""}
w.WriteJson(&server)
}
开发者ID:rogervaas,项目名称:crunchy-postgresql-manager,代码行数:26,代码来源:server.go
注:本文中的github.com/ant0ine/go-json-rest/rest.Error函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论