• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang rest.ResponseWriter类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/ant0ine/go-json-rest/rest.ResponseWriter的典型用法代码示例。如果您正苦于以下问题:Golang ResponseWriter类的具体用法?Golang ResponseWriter怎么用?Golang ResponseWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: 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


示例2: FailedToAuthenticate

func (u Util) FailedToAuthenticate(w rest.ResponseWriter) {
	w.WriteHeader(401)
	w.WriteJson(types.Json{
		"response": "Failed to authenticate user request",
		"reason":   "Missing, illegal or expired token",
	})
}
开发者ID:AbdulZaid,项目名称:cher-ami,代码行数:7,代码来源:responses.go


示例3: handleCacheGet

func handleCacheGet(w rest.ResponseWriter, r *rest.Request) {
	res := CacheResMulti{}
	lockStore.Lock()
	lockStats.Lock()
	for key, item := range store {
		if curCnt, ok := storeStats[key]; ok {
			curCnt++

			if curCnt >= 100 {
				delete(store, key)
				delete(storeStats, key)

				item.DeleteLocal(key)
			} else {
				storeStats[key] = curCnt
				item.IncLocal(key, false)
			}
		} else {
			storeStats[key] = 1
		}

		res.Items = append(res.Items, *item)
	}
	lockStore.Unlock()
	lockStats.Unlock()

	w.WriteJson(res)
}
开发者ID:leetune,项目名称:gitw-challenge,代码行数:28,代码来源:main.go


示例4: PostUser

func (api *Api) PostUser(w rest.ResponseWriter, r *rest.Request) {
	user := User{}

	err := r.DecodeJsonPayload(&user)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	lastInsertId, err := api.DB.Query("INSERT INTO " + TABLENAME + "(" + COLNAME + ") OUTPUT Inserted.ID VALUES('" + user.Name + "')")
	if err != nil {
		fmt.Println(err)
		return
	}

	if lastInsertId.Next() {
		var id int
		if err := lastInsertId.Scan(&id); err != nil {
			log.Fatal(err)
		}
		user.Id = id
	} else {
		rest.NotFound(w, r)
		return
	}
	if err := lastInsertId.Err(); err != nil {
		log.Fatal(err)
	}

	w.WriteJson(&user)
}
开发者ID:sohamsankaran,项目名称:go-database-drivers,代码行数:31,代码来源:sqlserver-json-rest.go


示例5: Post

func Post(w rest.ResponseWriter, r *rest.Request) {
	host := Host{}
	err := r.DecodeJsonPayload(&host)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if host.Id == "" {
		rest.Error(w, "id required", 400)
		return
	}
	if host.Address == "" {
		rest.Error(w, "address required", 400)
		return
	}
	ra, err := net.ResolveIPAddr("ip4:icmp", host.Address)
	if err != nil {
		rest.Error(w, err.Error(), 400)
		return
	}
	lock.Lock()
	q := make(chan bool, 1) // chan for stop ping
	store[host.Id] = &HostStore{
		host,
		time.Now(),
		0.0, 0.0, 0.0, 0.0,
		0,
		ring.New(DefCircleLen),
		q}
	go ping(host.Id, ra, time.Second*DefRTT, q, &lock, store)
	lock.Unlock()
	w.WriteJson(&host)
}
开发者ID:hizel,项目名称:pingd,代码行数:33,代码来源:pingd.go


示例6: StartCluster

// StartCluster starts all nodes in a cluster
func StartCluster(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-cluster")
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}

	ID := r.PathParam("ID")
	if ID == "" {
		logit.Error.Println("StartCluster: error cluster ID required")
		rest.Error(w, "cluster ID required", http.StatusBadRequest)
		return
	}

	cluster, err := admindb.GetCluster(dbConn, ID)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusBadRequest)
	}

	//start docker containers
	containers, err := admindb.GetAllContainersForCluster(dbConn, cluster.ID)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusBadRequest)
	}

	i := 0

	i = 0
	var response swarmapi.DockerStartResponse
	for i = range containers {

		req := &swarmapi.DockerStartRequest{}
		req.ContainerName = containers[i].Name
		logit.Info.Println("will attempt to start container " + req.ContainerName)
		response, err = swarmapi.DockerStart(req)
		if err != nil {
			logit.Error.Println("StartCluster: error when trying to start container" + err.Error())
		}
		logit.Info.Println("StartCluster: started " + response.Output)

		i++
	}

	status := types.SimpleStatus{}
	status.Status = "OK"
	w.WriteHeader(http.StatusOK)
	w.WriteJson(&status)
}
开发者ID:rogervaas,项目名称:crunchy-postgresql-manager,代码行数:61,代码来源:clustermgmt.go


示例7: PostCluster

// PostCluster updates or inserts a new cluster definition
func PostCluster(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()
	//logit.Info.Println("PostCluster: in PostCluster")
	cluster := types.Cluster{}
	err = r.DecodeJsonPayload(&cluster)
	if err != nil {
		logit.Error.Println("error in decode" + err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = secimpl.Authorize(dbConn, cluster.Token, "perm-cluster")
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}

	if cluster.Name == "" {
		logit.Error.Println("PostCluster: error in Name")
		rest.Error(w, "cluster name required", http.StatusBadRequest)
		return
	}

	//logit.Info.Println("PostCluster: have ID=" + cluster.ID + " Name=" + cluster.Name + " type=" + cluster.ClusterType + " status=" + cluster.Status)
	dbcluster := types.Cluster{}
	dbcluster.ID = cluster.ID
	dbcluster.ProjectID = cluster.ProjectID
	dbcluster.Name = cluster.Name
	dbcluster.ClusterType = cluster.ClusterType
	dbcluster.Status = cluster.Status
	dbcluster.Containers = cluster.Containers
	if cluster.ID == "" {
		strid, err := admindb.InsertCluster(dbConn, dbcluster)
		newid := strconv.Itoa(strid)
		if err != nil {
			logit.Error.Println(err.Error())
			rest.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		cluster.ID = newid
	} else {
		//logit.Info.Println("PostCluster: about to call UpdateCluster")
		err2 := admindb.UpdateCluster(dbConn, dbcluster)
		if err2 != nil {
			logit.Error.Println(err.Error())
			rest.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
	}

	w.WriteJson(&cluster)
}
开发者ID:rogervaas,项目名称:crunchy-postgresql-manager,代码行数:61,代码来源:clustermgmt.go


示例8: CreateCard

// CreateCard creates a new card entry.
func CreateCard(w rest.ResponseWriter, r *rest.Request) {
	var err error

	c, err := card.New()
	if err != nil {
		log.Printf("CreateCard: Failed to create card: %s", err)
		rest.Error(w, "Failed to create card", 500)
		return
	}

	decoder := json.NewDecoder(r.Body)
	err = decoder.Decode(&c)
	if err != nil {
		log.Printf("CreateCard: Failed to decode request body: %s", err)
		rest.Error(w, "Failed to decode request body", 500)
		return
	}

	if err := card.GetHandler().SaveCard(*c); err != nil {
		log.Printf("CreateCard: Failed to save card: %s", err)
		rest.Error(w, "Failed to create card", 500)
		return
	}

	log.Printf("CreateCard: Card save was successful (%s)", c.Cid)
	w.WriteJson(c)
}
开发者ID:hairqles,项目名称:scholar,代码行数:28,代码来源:endpoints.go


示例9: 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


示例10: HandleImageList

func HandleImageList(w rest.ResponseWriter, r *rest.Request) {
	lock.Lock()
	cmd := exec.Command("zfs", "list", "-H", "-t", "volume")
	stdout, err := cmd.Output()
	lock.Unlock()

	if err != nil {
		return
	}

	lines := strings.Split(string(stdout), "\n")
	imas := make([]Images, 0)

	for _, line := range lines {
		if strings.Contains(line, "ima-") {
			ima := Images{}
			n := strings.Split(line, "\t")[0]
			n = strings.Split(n, "/")[1]
			ima.Imageid = n
			ima.Os = getImaOs(ima.Imageid)
			imas = append(imas, ima)
		}
	}

	w.WriteJson(imas)
}
开发者ID:gitter-badger,项目名称:pangolin,代码行数:26,代码来源:pangolin-api.go


示例11: AuthenticationAPI

func AuthenticationAPI(w rest.ResponseWriter, req *rest.Request) {
	fmt.Println(":: AuthenticationAPI ::")
	ip, _ := net.LookupIP(req.PathParam("host"))
	// rest.Error(w, err.Error(), http.StatusInternalServerError)
	w.WriteJson(&ip)
	w.WriteJson(map[string]interface{}{"Body": ip})
}
开发者ID:AnuchitPrasertsang,项目名称:golang-middleware-test,代码行数:7,代码来源:main.go


示例12: Translate

func Translate(w rest.ResponseWriter, r *rest.Request) {

	request := &RequestObject{}
	r.DecodeJsonPayload(request)
	c := translator.Translate(request.Text, request.Lang)
	w.WriteJson(c)
}
开发者ID:unitrans,项目名称:unitrans,代码行数:7,代码来源:web_api.go


示例13: KeysList

func KeysList(w rest.ResponseWriter, r *rest.Request) {

	user := r.Env["USER"].(*domain.User)

	user.Pass = ""
	w.WriteJson(user)
}
开发者ID:unitrans,项目名称:unitrans,代码行数:7,代码来源:web_api.go


示例14: 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


示例15: appInfoHandler

func appInfoHandler(w rest.ResponseWriter, r *rest.Request) {
	var marathonApps marathon.MarathonAppsGlobalInfoResponse
	fasthttp.JsonReqAndResHandler(goCore.MarathonAppsUrl, nil, &marathonApps, "GET")
	appsCnt := len(marathonApps.Apps)

	// should not code like this: appsGlobalInfos := [appsCnt]entity.AppsGlobalInfo{}
	appsGlobalInfos := make([]dto.AppsGlobalInfoResponse, appsCnt)

	for i, v := range marathonApps.Apps {
		var perApp dto.AppsGlobalInfoResponse
		if strings.LastIndex(v.Id, "/") == -1 {
			perApp.Id = v.Id
		} else {
			perApp.Id = v.Id[strings.LastIndex(v.Id, "/")+1:]
		}
		perApp.Cpus = strconv.FormatFloat(v.Cpus, 'f', 1, 64)
		perApp.CurrentInstances = strconv.Itoa(v.TasksRunning)
		fmt.Println(v)
		if strings.LastIndex(v.Id, "/") <= 0 { // exclude like /zk or zk
			perApp.Group = "No Groups"
		} else {
			perApp.Group = v.Id[0:strings.LastIndex(v.Id, "/")]
		}
		perApp.Instances = strconv.Itoa(v.Instances)
		perApp.Mem = strconv.FormatFloat(v.Mem, 'f', 1, 64)
		if v.TasksHealthy == 0 && v.TasksUnhealthy == 0 { // when no and healthy check
			perApp.Healthy = "100"
		} else {
			perApp.Healthy = strconv.FormatFloat(float64(v.TasksHealthy)/float64(v.TasksHealthy+v.TasksUnhealthy), 'f', 1, 64)
		}
		perApp.FormatStatus(v.TasksStaged)
		appsGlobalInfos[i] = perApp
	}
	w.WriteJson(appsGlobalInfos)
}
开发者ID:konce,项目名称:chaos,代码行数:35,代码来源:bootstrap.go


示例16: registerUser

func registerUser(w rest.ResponseWriter, r *rest.Request, db neutrino.DbService) {
	var u bson.M

	if err := r.DecodeJsonPayload(&u); err != nil {
		RestErrorInvalidBody(w)
		return
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u["password"].(string)), 10)
	if err != nil {
		RestError(w, err)
		return
	}

	doc := bson.M{
		"_id":       u["email"].(string),
		"password":  hashedPassword,
		"createdAt": time.Now(),
	}

	if err := db.Insert(doc); err != nil {
		RestError(w, err)
		return
	}

	w.WriteHeader(http.StatusOK)
}
开发者ID:gitter-badger,项目名称:neutrino-core,代码行数:27,代码来源:auth.go


示例17: renewInstance

func (routes *Routes) renewInstance(w rest.ResponseWriter, r *rest.Request) {
	iid := r.PathParam(RouteParamInstanceID)
	if iid == "" {
		routes.logger.WithFields(log.Fields{
			"namespace": r.Env["REMOTE_USER"],
			"error":     "instance id is required",
		}).Warn("Failed to renew instance")

		i18n.Error(r, w, http.StatusBadRequest, i18n.ErrorInstanceIdentifierMissing)
		return
	}

	catalog := routes.catalog(w, r)
	if catalog == nil {
		routes.logger.WithFields(log.Fields{
			"namespace": r.Env["REMOTE_USER"],
			"error":     "catalog is nil",
		}).Errorf("Failed to renew instance %s", iid)

		return
	}

	if err := catalog.Renew(iid); err != nil {
		routes.logger.WithFields(log.Fields{
			"namespace": r.Env["REMOTE_USER"],
			"error":     err,
		}).Warnf("Failed to renew instance %s", iid)

		i18n.Error(r, w, statusCodeFromError(err), i18n.ErrorInstanceHeartbeatFailed)
		return
	}

	w.WriteHeader(http.StatusOK)
}
开发者ID:charshy,项目名称:registry,代码行数:34,代码来源:instance_handler.go


示例18: loginUser

func loginUser(w rest.ResponseWriter, r *rest.Request, db neutrino.DbService) {
	var u bson.M

	if err := r.DecodeJsonPayload(&u); err != nil {
		RestError(w, err)
		return
	}

	existingUser, err := db.FindId(u["email"].(string), nil)

	if err != nil {
		RestError(w, err)
		return
	}

	err = bcrypt.CompareHashAndPassword(existingUser["password"].([]byte), []byte(u["password"].(string)))

	if err != nil {
		RestError(w, err)
		return
	}

	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["user"] = u["email"].(string)
	token.Claims["expiration"] = time.Now().Add(time.Minute + 60).Unix()

	tokenStr, err := token.SignedString([]byte(""))

	if err != nil {
		RestError(w, err)
		return
	}

	w.WriteJson(map[string]string{"token": tokenStr})
}
开发者ID:gitter-badger,项目名称:neutrino-core,代码行数:35,代码来源:auth.go


示例19: 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


示例20: PostTransportTraffic

func PostTransportTraffic(w rest.ResponseWriter, r *rest.Request) {
	form := shared.TransportTraffic{}
	err := r.DecodeJsonPayload(&form)
	if err != nil {
		apiutils.WriteRestError(w, apierrors.NewInternalError(err))
		return
	}
	transportTrafficMu.Lock()
	defer transportTrafficMu.Unlock()
	transportTraffic = form
	if lg.V(10) {
		if len(transportTrafficLog) == 6 {
			lg.Infof("transport traffic: %.0fkb/s %.0fkb/s %.0fkb/s %.0fkb/s  %.0fkb/s %.0fkb/s",
				(transportTrafficLog[0].Throughput)/1024,
				(transportTrafficLog[1].Throughput)/1024,
				(transportTrafficLog[2].Throughput)/1024,
				(transportTrafficLog[3].Throughput)/1024,
				(transportTrafficLog[4].Throughput)/1024,
				(transportTrafficLog[5].Throughput)/1024,
			)
			transportTrafficLog = make([]shared.TransportTraffic, 0)
		}
		if transportTraffic.Throughput > 1024 {
			transportTrafficLog = append(transportTrafficLog, form)
		}
	}
	response := true
	w.WriteJson(response)
}
开发者ID:thomasf,项目名称:alkasir,代码行数:29,代码来源:api.go



注:本文中的github.com/ant0ine/go-json-rest/rest.ResponseWriter类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang test.MakeSimpleRequest函数代码示例发布时间:2022-05-24
下一篇:
Golang rest.ResourceHandler类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap