本文整理匯總了Golang中github.com/gin-gonic/gin.Context.Data方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.Data方法的具體用法?Golang Context.Data怎麽用?Golang Context.Data使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gin-gonic/gin.Context
的用法示例。
在下文中一共展示了Context.Data方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ProviderGetEpisode
func ProviderGetEpisode(ctx *gin.Context) {
provider := ctx.Params.ByName("provider")
showId := ctx.Params.ByName("showId")
seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
episodeNumber, _ := strconv.Atoi(ctx.Params.ByName("episode"))
log.Println("Searching links for TVDB Id:", showId)
show, err := tvdb.NewShowCached(showId, "en")
if err != nil {
ctx.Error(err)
return
}
episode := show.Seasons[seasonNumber].Episodes[episodeNumber-1]
log.Printf("Resolved %s to %s", showId, show.SeriesName)
searcher := providers.NewAddonSearcher(provider)
torrents := searcher.SearchEpisodeLinks(show, episode)
if ctx.Request.URL.Query().Get("resolve") == "true" {
for _, torrent := range torrents {
torrent.Resolve()
}
}
data, err := json.MarshalIndent(providerDebugResponse{
Payload: searcher.GetEpisodeSearchObject(show, episode),
Results: torrents,
}, "", " ")
if err != nil {
xbmc.AddonFailure(provider)
ctx.Error(err)
}
ctx.Data(200, "application/json", data)
}
示例2: HandleQuery
func HandleQuery(query string, c *gin.Context) {
rawQuery, err := base64.StdEncoding.DecodeString(query)
if err == nil {
query = string(rawQuery)
}
result, err := DB(c).Query(query)
if err != nil {
c.JSON(400, NewError(err))
return
}
format := getQueryParam(c, "format")
filename := getQueryParam(c, "filename")
if filename == "" {
filename = fmt.Sprintf("pgweb-%v.%v", time.Now().Unix(), format)
}
if format != "" {
c.Writer.Header().Set("Content-disposition", "attachment;filename="+filename)
}
switch format {
case "csv":
c.Data(200, "text/csv", result.CSV())
case "json":
c.Data(200, "applicaiton/json", result.JSON())
case "xml":
c.XML(200, result)
default:
c.JSON(200, result)
}
}
示例3: Count
func Count(context *gin.Context) {
appenginecontext := appengine.NewContext(context.Request)
image := context.Param("image")
imageId, err := strconv.Atoi(image)
if err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
appenginecontext.Debugf("%s", err)
return
}
var counter Counter
key := datastore.NewKey(appenginecontext, "counters", "", int64(imageId), nil)
if err := datastore.Get(appenginecontext, key, &counter); err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
appenginecontext.Debugf("%s", err)
return
}
counter.Hits = counter.Hits + 1
counter.Last = time.Now()
_, err = datastore.Put(appenginecontext, key, &counter)
if err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
appenginecontext.Debugf("%s", err)
return
}
output, _ := base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")
context.Data(200, "image/gif", output)
}
示例4: FriendshipShow
// FriendshipShow takes a given ID from gin.Context
// @returns a specific friendship JSON object
func FriendshipShow(c *gin.Context) {
friendship := models.Friendship{}
if database.DBCon.First(&friendship, c.Param("id")).RecordNotFound() {
c.AbortWithError(http.StatusNotFound, appError.RecordNotFound).
SetMeta(appError.RecordNotFound)
return
}
var fd models.FriendshipData
database.DBCon.First(&friendship.User, friendship.UserID)
database.DBCon.First(&friendship.Friend, friendship.FriendID)
database.DBCon.First(&fd, friendship.FriendshipDataID)
if friendship.UserID == fd.PositiveUserID {
friendship.Balance = fd.Balance
} else {
friendship.Balance = -fd.Balance
}
data, err := jsonapi.Marshal(friendship)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err).
SetMeta(appError.JSONParseFailure)
return
}
c.Data(http.StatusOK, "application/vnd.api+json", data)
}
示例5: rpcEndpoint
func rpcEndpoint(c *gin.Context) {
op := c.MustGet("nuget.op").(string)
query := c.MustGet("nuget.search").(*NuGetQuery)
oplog := log.WithFields(log.Fields{
"op": op,
"query": query,
})
switch op {
case "$metadata":
c.Data(200, XmlMimeType, []byte(NuGetMetadata))
break
case "Packages":
data := c.MustGet("nuget.op.data").(*PackagesCommand)
Packages(c, data, query, oplog.WithField("data", data))
case "FindPackagesById":
data := c.MustGet("nuget.op.data").(*FindPackagesByIdCommand)
FindPackagesById(c, data, query, oplog.WithField("data", data))
case "Search":
data := c.MustGet("nuget.op.data").(*SearchCommand)
Search(c, data, query, oplog.WithField("data", data))
case "GetUpdates":
data := c.MustGet("nuget.op.data").(*GetUpdatesCommand)
GetUpdates(c, data, query, oplog.WithField("data", data))
default:
c.Status(400)
}
}
示例6: FriendshipIndex
// FriendshipIndex takes in query params through
// gin.Context and is restricted to the currentUser
// @returns an array of friendship JSON objects
func FriendshipIndex(c *gin.Context) {
friendships := []models.Friendship{}
var curUser models.User
database.DBCon.First(&curUser, c.Keys["CurrentUserID"])
database.DBCon.Model(&curUser).Related(&friendships, "Friendships")
// Get user and friend and friendshipData
// TODO: n + 1 query problem here, so we'll figure this out later
for i := range friendships {
var fd models.FriendshipData
database.DBCon.First(&friendships[i].Friend, friendships[i].FriendID)
database.DBCon.First(&fd, friendships[i].FriendshipDataID)
if curUser.ID == fd.PositiveUserID {
friendships[i].Balance = fd.Balance
} else {
friendships[i].Balance = -fd.Balance
}
friendships[i].User = curUser
}
data, err := jsonapi.Marshal(friendships)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err).
SetMeta(appError.JSONParseFailure)
return
}
c.Data(http.StatusOK, "application/vnd.api+json", data)
}
示例7: getTagsFile
func (s *Server) getTagsFile(c *gin.Context) {
id := c.Param("id")
content_path := c.Param("path")[1:] // '/' を消す
tag, err := TagFileFromFile(s.tagFilepath(id))
if err != nil {
c.AbortWithError(500, err)
return
}
bucket, err := tag.Bucket(s)
if err != nil {
c.AbortWithError(500, err)
return
}
content, found := bucket.Contents[content_path]
if !found {
c.AbortWithError(500, fmt.Errorf("content %s not found", content_path))
return
}
content_body, err := ioutil.ReadFile(s.hashFilepath(content.Hash))
if err != nil {
c.AbortWithError(500, err)
return
}
content_body, err = decode(content_body, tag.EncryptKey, tag.EncryptIv, content.Attr)
if err != nil {
c.AbortWithError(500, err)
return
}
c.Data(200, "text/plain", content_body)
}
示例8: HandleQuery
func HandleQuery(query string, c *gin.Context) {
rawQuery, err := base64.StdEncoding.DecodeString(query)
if err == nil {
query = string(rawQuery)
}
result, err := DbClient.Query(query)
if err != nil {
c.JSON(400, NewError(err))
return
}
q := c.Request.URL.Query()
if len(q["format"]) > 0 && q["format"][0] == "csv" {
filename := fmt.Sprintf("pgweb-%v.csv", time.Now().Unix())
if len(q["filename"]) > 0 && q["filename"][0] != "" {
filename = q["filename"][0]
}
c.Writer.Header().Set("Content-disposition", "attachment;filename="+filename)
c.Data(200, "text/csv", result.CSV())
return
}
c.JSON(200, result)
}
示例9: DataStoreGet
func DataStoreGet(r *gin.Context) {
var patient, module, id string
patient = r.Param("patient")
if patient == "" {
log.Print("DataStoreGet(): No patient provided")
r.JSON(http.StatusInternalServerError, false)
return
}
module = r.Param("module")
if module == "" {
log.Print("DataStoreGet(): No module provided")
r.JSON(http.StatusInternalServerError, false)
return
}
id = r.Param("id")
if id == "" {
log.Print("DataStoreGet(): No id provided")
r.JSON(http.StatusInternalServerError, false)
return
}
var content []byte
err := model.DbMap.SelectOne(&content, "SELECT contents FROM pds WHERE patient = ? AND module = LOWER(?) AND id = ?", patient, module, id)
if err != nil {
log.Print(err.Error())
r.JSON(http.StatusInternalServerError, false)
return
}
// TODO: FIXME: Need to properly determine mimetype
r.Data(http.StatusOK, "application/x-binary", content)
return
}
示例10: FindPackagesById
func FindPackagesById(c *gin.Context, d *FindPackagesByIdCommand, q *NuGetQuery, logger *log.Entry) {
logger.Info("FindPackagesById")
var match *rekt.Entry
for _, pkg := range registry.Packages {
if pkg.Title == d.Id && (q.Filter != "IsLatestVersion" || pkg.IsLatestVersion) {
match = pkg
}
}
feed := &rekt.Feed{
Id: "https://www.example.com/api/v2/FindPackagesById",
Title: "FindPackagesById",
Updated: time.Now(),
Entries: []*rekt.Entry{match},
}
atom, err := feed.ToAtom()
if err != nil {
c.Status(500)
return
}
c.Data(200, AtomMimeType, atom)
return
}
示例11: Fetch
// this is when we return raw data back to the client
// for fetching files from a workspace
func Fetch(c *gin.Context) {
// this is the workspace ID
workspaceId := c.Param("id")
// this is the relative path of the resource
resource := c.Param("path")
// if the resource is empty, then
// we will render a workspace response
// see `Workspace`
if resource == "/" || resource == "" {
Workspace(c)
return
}
log.Printf("id=\"%s\", resource=\"%s\"", workspaceId, resource)
// slurp up the entire file, and return it
// as mime content-type data
content, err := ioutil.ReadFile(Resolve(workspaceId, resource))
if err != nil {
panic(err.Error())
}
// use `mime.TypeByExtension` to guess the content-type
mimetype := mime.TypeByExtension(path.Ext(resource))
// again gin API is really nice and simple
c.Data(http.StatusOK, mimetype, content)
}
示例12: JSONTest
// JSONTest is a testing page only, it will be removed when no longer needed.
func JSONTest(c *gin.Context) {
// user := auth.AuthenticatedUser(c)
user := auth.User{
ID: 345,
Username: "test.user",
Email: "[email protected]",
Active: true,
Superuser: false,
Groups: []auth.Group{
{
ID: 1,
Name: "Group 1",
Permissions: []auth.Permission{
{ID: 1, Name: "user-create", Description: "Can create users"},
{ID: 2, Name: "user-update", Description: "Can update users"},
{ID: 3, Name: "user-delete", Description: "Can delete users"},
{ID: 4, Name: "user-read", Description: "Can read users"},
},
},
{
ID: 2,
Name: "Group 2",
Permissions: []auth.Permission{
{ID: 4, Name: "user-read", Description: "Can read users"},
},
},
},
}
json, _ := jsonapi.MarshalToJSON(user)
c.Data(200, "application/vnd.api+json", json)
}
示例13: ProfilingInfoJSONHandler
// ProfilingInfoJSONHandler is a HTTP Handler to return JSON of the Heap memory statistics and any extra info the server wants to tell us about
func ProfilingInfoJSONHandler(c *gin.Context) {
log.Println("ProfilingInfoJSONHandler")
// struct for output
type outputStruct struct {
HeapInfo []HeapMemStat
ExtraServiceInfo map[string]interface{}
}
response := outputStruct{}
// Fetch the most recent memory statistics
responseChannel := make(chan []TimedMemStats)
proxyStatsRequestChannel <- responseChannel
response.HeapInfo = timedMemStatsToHeapMemStats(<-responseChannel)
// fetch the extra service info, if available
extraServiceInfoRetrieverMutex.RLock()
defer extraServiceInfoRetrieverMutex.RUnlock()
if extraServiceInfoRetriever != nil {
response.ExtraServiceInfo = extraServiceInfoRetriever()
}
// convert to JSON and write to the client
js, err := json.Marshal(response)
if err != nil {
c.Error(err)
return
}
//w.Write(js)
c.Data(http.StatusOK, "application/json", js)
}
示例14: HandleRun
func HandleRun(c *gin.Context) {
req, err := ParseRequest(c.Request)
if err != nil {
errorResponse(400, err, c)
return
}
config, exists := c.Get("config")
if !exists {
errorResponse(400, fmt.Errorf("Cant get config"), c)
return
}
client, exists := c.Get("client")
if !exists {
errorResponse(400, fmt.Errorf("Cant get client"), c)
return
}
run := NewRun(config.(*Config), client.(*docker.Client), req)
defer run.Destroy()
result, err := performRun(run)
if err != nil {
errorResponse(400, err, c)
return
}
c.Header("X-Run-Command", req.Command)
c.Header("X-Run-ExitCode", strconv.Itoa(result.ExitCode))
c.Header("X-Run-Duration", result.Duration)
c.Data(200, req.Format, result.Output)
}
示例15: serveStaticFile
func serveStaticFile(c *gin.Context, option string) {
staticFile, err := ioutil.ReadFile(path.Join(RuntimeArgs.SourcePath, "static") + option)
if err != nil {
c.AbortWithStatus(404)
} else {
c.Data(200, contentType(option), []byte(staticFile))
}
}