本文整理匯總了Golang中github.com/gin-gonic/gin.Context.String方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.String方法的具體用法?Golang Context.String怎麽用?Golang Context.String使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gin-gonic/gin.Context
的用法示例。
在下文中一共展示了Context.String方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: UpdatePetWithFormHandler
func UpdatePetWithFormHandler(c *gin.Context) {
queryValues := c.Request.URL.Query()
petId := queryValues.Get("petId")
if petId == "" {
c.JSON(http.StatusBadRequest, gin.H{"missing": "petId"})
return
}
name := c.Request.PostFormValue("name")
if name == "" {
c.JSON(http.StatusBadRequest, gin.H{"missing": "name"})
return
}
status := c.Request.PostFormValue("status")
if status == "" {
c.JSON(http.StatusBadRequest, gin.H{"missing": "status"})
return
}
if err := operations.UpdatePetWithForm(petId, name, status); err == nil {
c.String(http.StatusOK, "Success")
} else {
c.JSON(http.StatusBadRequest, err)
}
}
示例2: CreateTrainingJob
// Create Training Job
func (e EndpointContext) CreateTrainingJob(c *gin.Context) {
// bind to json
user := c.MustGet(MIDDLEWARE_KEY_USER).(User)
db := c.MustGet(MIDDLEWARE_KEY_DB).(couch.Database)
trainingJob := NewTrainingJob(e.Configuration)
trainingJob.UserID = user.Id
// bind the input struct to the JSON request
if ok := c.Bind(trainingJob); !ok {
errMsg := fmt.Sprintf("Invalid input")
c.String(400, errMsg)
return
}
logg.LogTo("REST", "Create new TrainingJob: %+v", trainingJob)
// save training job in db
trainingJob, err := trainingJob.Insert(db)
if err != nil {
c.String(500, err.Error())
return
}
// job will get kicked off by changes listener
// return solver object
c.JSON(201, *trainingJob)
}
示例3: Index
func (ar *APIResource) Index(c *gin.Context) {
if c.Request.Header.Get("Authorization") == "authenticated" {
c.String(http.StatusOK, "Index")
} else {
c.String(http.StatusForbidden, "forbidden")
}
}
示例4: GetResources
func (rc *ResourceController) GetResources(ctx *gin.Context) {
req := ctx.Request
resourceType := getResourceType(req.URL)
logger.Log.WithFields(
logrus.Fields{"resource type": resourceType}).Info("GetResources")
resources := ptm_models.NewSliceForResourceName(resourceType, 0, 0)
c := rc.Database().C(ptm_models.GetCollectionName(resourceType))
// retrieve all documents in the collection
// TODO Restrict this to resource type, just to be extra safe
query := buildSearchQuery(resourceType, ctx)
logger.Log.WithFields(
logrus.Fields{"query": query}).Info("GetResources")
err := c.Find(query).All(resources)
if err != nil {
if err == mgo.ErrNotFound {
ctx.String(http.StatusNotFound, "Not Found")
ctx.Abort()
return
} else {
ctx.AbortWithError(http.StatusBadRequest, err)
return
}
}
ctx.JSON(http.StatusOK, resources)
}
示例5: GetFeed
func GetFeed(c *gin.Context) {
user := session.User(c)
remote := remote.FromContext(c)
var repos []*model.RepoLite
// get the repository list from the cache
reposv, ok := c.Get("repos")
if ok {
repos = reposv.([]*model.RepoLite)
} else {
var err error
repos, err = remote.Repos(user)
if err != nil {
c.String(400, err.Error())
return
}
}
feed, err := store.GetUserFeed(c, repos)
if err != nil {
c.String(400, err.Error())
return
}
c.JSON(200, feed)
}
示例6: ShowIndex
func ShowIndex(c *gin.Context) {
user := session.User(c)
if user == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
// get the repository list from the cache
repos, err := cache.GetRepos(c, user)
if err != nil {
c.String(400, err.Error())
return
}
// filter to only show the currently active ones
activeRepos, err := store.GetRepoListOf(c, repos)
if err != nil {
c.String(400, err.Error())
return
}
c.HTML(200, "index.html", gin.H{
"User": user,
"Repos": activeRepos,
})
}
示例7: apiGetSiteInfo
func apiGetSiteInfo(g *gin.Context) {
url, ok := g.GetQuery("url")
if !ok {
g.String(500, "missing parameter url")
return
}
_, inclBody := g.GetQuery("body")
cw := crawlbase.NewCrawler()
cw.Header.Add("User-Agent", userAgentHeader)
tags, _ := crawlbase.LoadTagsFromFile("tags.json")
cw.Validator.AddValidTags(tags)
page, err := cw.GetPage(url, "GET")
if err != nil {
g.String(500, err.Error())
}
// first check
if !inclBody {
page.RespInfo.Body = ""
}
g.JSON(200, page)
}
示例8: commandRefreshSettings
// commandRefreshSettings precesses request to refresh settings
func (s *DefaultServer) commandRefreshSettings(c *gin.Context, args Args) {
if err := s.refreshSettings(); err != nil {
c.String(http.StatusOK, "false")
return
}
c.String(http.StatusOK, "true")
}
示例9: handler
func handler(c *gin.Context) {
URL := c.PostForm("URL")
name := c.PostForm("Name")
status := c.PostForm("Status")
slack := SlackParams{
Attachments: []SlackAttachments{
SlackAttachments{
Color: color(status),
Fallback: fallback(name, status),
Title: title(name, status),
Text: text(URL),
},
},
Username: "StatusCake Bot",
Mrkdwn: true,
IconEmoji: ":cake:",
}
url_slack := fmt.Sprintf("https://hooks.slack.com/%s", c.Param("url"))
b, err := json.Marshal(slack)
if err != nil {
c.String(400, "fail")
return
}
http.PostForm(url_slack, url.Values{"payload": {string(b)}})
c.String(200, "ok")
}
示例10: PostRepoKey
func PostRepoKey(c *gin.Context) {
repo := session.Repo(c)
keys, err := store.GetKey(c, repo)
if err != nil {
c.String(404, "Error fetching repository key")
return
}
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.String(500, "Error reading private key from body. %s", err)
return
}
pkey := crypto.UnmarshalPrivateKey(body)
if pkey == nil {
c.String(500, "Cannot unmarshal private key. Invalid format.")
return
}
keys.Public = string(crypto.MarshalPublicKey(&pkey.PublicKey))
keys.Private = string(crypto.MarshalPrivateKey(pkey))
err = store.UpdateKey(c, keys)
if err != nil {
c.String(500, "Error updating repository key")
return
}
c.String(201, keys.Public)
}
示例11: directaccessHandler
func directaccessHandler(ctx *gin.Context) {
db := ctx.Params.ByName("database")
path := ctx.Params.ByName("path")
layer := ctx.Params.ByName("layer")
cmd := bytengine.Command{
Name: "directaccess",
IsAdmin: false,
Args: make(map[string]interface{}),
Options: make(map[string]interface{}),
}
cmd.Args["database"] = db
cmd.Args["path"] = path
cmd.Args["layer"] = layer
cmd.Args["writer"] = ctx.Writer
if layer == "json" {
ctx.Writer.Header().Set("Content-Type", "application/json")
} else {
ctx.Writer.Header().Set("Content-Type", "application/octet-stream")
}
req := EngineRequest{
Token: "",
Command: &cmd,
ResponseChan: make(chan EngineResponse),
}
EngineRequestChan <- &req
rep := <-req.ResponseChan
if rep.Error != nil {
data := errorResponse(rep.Error)
ctx.String(404, string(data))
return
}
}
示例12: HandleSucces
// Handles the simple successful return status
func HandleSucces(c *gin.Context, status int, message gin.H) {
if status == 204 {
c.String(status, "")
} else {
c.JSON(status, message)
}
}
示例13: handler
func handler(c *gin.Context) {
if !gConfig.UI.DisableUI {
c.Redirect(http.StatusTemporaryRedirect, gConfig.Repos.Path)
} else {
c.String(200, "nothing to see here\n")
}
}
示例14: processPRHook
func processPRHook(c *gin.Context, prHook *model.PRHook) {
repo, user, err := getRepoAndUser(c, prHook.Repo.Slug)
if err != nil {
return
}
err = remote.SetStatus(c, user, repo, prHook.Number, false)
if err != nil {
log.Errorf("Error setting status. %s", err)
c.String(500, "Error setting status. %s", err)
return
}
config, _, err := getConfigAndMaintainers(c, user, repo)
if err != nil {
return
}
if prHook.Update && config.DoComment {
err = remote.WriteComment(c, user, repo, prHook.Number, "The Pull Request has been updated. No comments before this one will count for approval.")
if err != nil {
log.Errorf("Error writing comment for status. %s", err)
c.String(500, "Error writing comment for status. %s", err)
return
}
}
c.IndentedJSON(200, gin.H{
"number": prHook.Number,
"approved": false,
})
}
示例15: changeUpdate
// update an object from its change form
func changeUpdate(c *gin.Context) {
log.Println("hitting changeUpdate")
action := c.DefaultPostForm("action", "save")
delete(c.Request.Form, "action") // don't keep this as part of the object
modelAdmin, exists := modelAdmins[strings.ToLower(c.Param("model"))]
if !exists {
c.String(http.StatusNotFound, "Not found.")
return
}
if !hasPermissions(c, modelAdmin.ModelName, "write", nil) { // TODO: add in the ID(s)
return
}
switch action {
case "save":
saveFromForm(c)
c.Request.Method = "GET"
c.Redirect(http.StatusFound, fmt.Sprintf("../%v", strings.ToLower(c.Param("model"))))
case "save-continue":
saveFromForm(c)
change(c)
case "delete":
modelAdmin.Accessor.DeletePK(c.Param("pk"))
c.Request.Method = "GET"
c.Redirect(http.StatusFound, fmt.Sprintf("../%v", strings.ToLower(c.Param("model"))))
}
}