本文整理匯總了Golang中github.com/hoisie/web.Context類的典型用法代碼示例。如果您正苦於以下問題:Golang Context類的具體用法?Golang Context怎麽用?Golang Context使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Context類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: getCover
func getCover(ctx *web.Context, album string) string {
dir := musicDir + "/" + album
cover := "static/image/missing.png"
if exists(dir + "/cover.jpg") {
cover = dir + "/cover.jpg"
} else if exists(dir + "/cover.png") {
cover = dir + "/cover.png"
}
//Open the file
f, err := os.Open(cover)
if err != nil {
return "Error reading file!\n"
}
//Get MIME
r, err := ioutil.ReadAll(f)
if err != nil {
return "Error reading file!\n"
}
mime := http.DetectContentType(r)
_, err = f.Seek(0, 0)
if err != nil {
return "Error reading the file\n"
}
//This is weird - ServeContent supposedly handles MIME setting
//But the Webgo content setter needs to be used too
//In addition, ServeFile doesn't work, ServeContent has to be used
ctx.ContentType(mime)
http.ServeContent(ctx.ResponseWriter, ctx.Request, cover, time.Now(), f)
return ""
}
示例2: Remove
func Remove(ctx *web.Context, val string) string {
id, err := strconv.Atoi(val)
if err != nil {
return "Invalid or malformed id"
}
db := util.GetDb()
_, submit_exists := ctx.Params["doit"]
if submit_exists {
db.Exec("DELETE FROM entries WHERE id=$1", id)
ctx.Redirect(302, "/manage/existing")
return "Redirect"
}
// Get the post
row := db.QueryRow("SELECT title FROM entries WHERE id=$1", id)
entry := new(util.Entry)
row.Scan(&entry.Title)
send := map[string]interface{}{
"Title": entry.Title,
}
return util.RenderTemplate("remove.mustache", send)
}
示例3: logout
func logout(ctx *web.Context) string {
session, _ := CookieStore.Get(ctx.Request, "monet-session")
session.Values["authenticated"] = false
session.Save(ctx.Request, ctx.ResponseWriter)
ctx.Redirect(302, "/admin/login/")
return ""
}
示例4: Publish
func (c *Controller) Publish(ctx *web.Context) {
if !c.sessionManager.LoggedIn(ctx) {
ctx.Redirect(303, "/login")
return
}
ctx.WriteString(c.Page("publish.html"))
}
示例5: getSong
func getSong(ctx *web.Context, song string) string {
//Open the file
f, err := os.Open("static/queue/" + song)
if err != nil {
return "Error reading file!\n"
}
//Get MIME
r, err := ioutil.ReadAll(f)
if err != nil {
return "Error reading file!\n"
}
mime := http.DetectContentType(r)
_, err = f.Seek(0, 0)
if err != nil {
return "Error reading the file\n"
}
//This is weird - ServeContent supposedly handles MIME setting
//But the Webgo content setter needs to be used too
//In addition, ServeFile doesn't work, ServeContent has to be used
ctx.ContentType(mime)
http.ServeContent(ctx.ResponseWriter, ctx.Request, "static/queue/"+song, time.Now(), f)
return ""
}
示例6: fragmentShaderHandler
func fragmentShaderHandler(ctx *web.Context, path string) {
file, err := os.Open(path)
check(err)
ctx.ContentType("x-shader/x-fragment")
_, err = io.Copy(ctx, file)
check(err)
}
示例7: api
func api(ctx *web.Context, username string) string {
user, err := getUser(username)
ctx.SetHeader("Content-Type", "application/prs.kevinburke.snapchat-v1+json", true)
if err != nil {
checkError(err)
ctx.NotFound("User not found")
return ""
}
friends, err := getFriendsById(user.Id)
checkError(err)
var links Links
var users []User
users = append(users, *user)
for i := 0; i < len(friends.Friends); i++ {
friend := friends.Friends[i]
link := Link{friend.UserId, friend.FriendId, friend.Index}
links.Links = append(links.Links, link)
user, err := getUserById(friend.UserId)
checkError(err)
users = append(users, *user)
}
response := Response{links.Links, users}
bytes, err := json.Marshal(response)
checkError(err)
return string(bytes)
}
示例8: handleEntry
func handleEntry(ctx *web.Context, hash string) {
type entry struct {
ChainID string
Content string
ExtIDs []string
}
e := new(entry)
if entry, err := factomapi.EntryByHash(hash); err != nil {
wsLog.Error(err)
ctx.WriteHeader(httpBad)
ctx.Write([]byte(err.Error()))
return
} else {
e.ChainID = entry.ChainID.String()
e.Content = hex.EncodeToString(entry.Content)
for _, v := range entry.ExtIDs {
e.ExtIDs = append(e.ExtIDs, hex.EncodeToString(v))
}
}
if p, err := json.Marshal(e); err != nil {
wsLog.Error(err)
ctx.WriteHeader(httpBad)
ctx.Write([]byte(err.Error()))
return
} else {
ctx.Write(p)
}
}
示例9: handleDirectoryBlockHead
func handleDirectoryBlockHead(ctx *web.Context) {
type dbhead struct {
KeyMR string
}
h := new(dbhead)
if block, err := factomapi.DBlockHead(); err != nil {
wsLog.Error(err)
ctx.WriteHeader(httpBad)
ctx.Write([]byte(err.Error()))
return
} else {
h.KeyMR = block.KeyMR.String()
}
if p, err := json.Marshal(h); err != nil {
wsLog.Error(err)
ctx.WriteHeader(httpBad)
ctx.Write([]byte(err.Error()))
return
} else {
ctx.Write(p)
}
// ctx.WriteHeader(httpOK)
}
示例10: handleEntryCreditBalance
func handleEntryCreditBalance(ctx *web.Context, eckey string) {
type ecbal struct {
Response string
Success bool
}
var b ecbal
adr, err := hex.DecodeString(eckey)
if err == nil && len(adr) != common.HASH_LENGTH {
b = ecbal{Response: "Invalid Address", Success: false}
}
if err == nil {
if bal, err := factomapi.ECBalance(eckey); err != nil {
wsLog.Error(err)
return
} else {
str := fmt.Sprintf("%d", bal)
b = ecbal{Response: str, Success: true}
}
} else {
b = ecbal{Response: err.Error(), Success: false}
}
if p, err := json.Marshal(b); err != nil {
wsLog.Error(err)
return
} else {
ctx.Write(p)
}
}
示例11: serveLinkWithExtras
/*
serve a link with extras (a path relative to the short-link and/or GET parameters)
Parameters:
ctx: the context of the http request
hash: the short-hash of the link
extras: the extra path component
*/
func serveLinkWithExtras(ctx *web.Context, hash string, extras string) {
//make the hash all uppercase
upperHash := strings.ToUpper(hash)
//Check to see if a link exists for the given hash
link, numReports, exists, err := db_linkForHash(upperHash)
if err != nil {
//There was an error in the database
internalError(ctx, errors.New("Database Error: "+err.Error()))
} else if exists {
//Check to see if the link has been flagged for review
if numReports >= NUM_REPORTS_TO_FLAG {
redir := link
//If there were any path extras passed to us, append them to the redir link
if extras != "" {
redir += "/" + extras
}
//If there are any GET parameters being passed to us, append them to the redir link
if len(ctx.Params) > 0 {
params := "?"
for k, v := range ctx.Params {
params += k + "=" + v + "&"
}
//remove the trailing ampersand and append to the redir link
redir += strings.TrimSuffix(params, "&")
}
flaggedLink(ctx, hash, redir)
return
} else {
//The hash=>link exists
redir := link
//If there were any path extras passed to us, append them to the redir link
if extras != "" {
redir += "/" + extras
}
//If there are any GET parameters being passed to us, append them to the redir link
if len(ctx.Params) > 0 {
params := "?"
for k, v := range ctx.Params {
params += k + "=" + v + "&"
}
//remove the trailing ampersand and append to the redir link
redir += strings.TrimSuffix(params, "&")
}
//if the hash exists in the link table, issue a '302 Found' to the client with the link URL
ctx.Redirect(302, redir)
}
} else {
//No link exists for the hash, so serve a '404 Not Found' error page
error404(ctx, hash)
}
}
示例12: handleFactoidBalance
func handleFactoidBalance(ctx *web.Context, eckey string) {
type fbal struct {
Response string
Success bool
}
var b fbal
adr, err := hex.DecodeString(eckey)
if err == nil && len(adr) != common.HASH_LENGTH {
b = fbal{Response: "Invalid Address", Success: false}
}
if err == nil {
v := int64(common.FactoidState.GetBalance(fct.NewAddress(adr)))
str := fmt.Sprintf("%d", v)
b = fbal{Response: str, Success: true}
} else {
b = fbal{Response: err.Error(), Success: false}
}
if p, err := json.Marshal(b); err != nil {
wsLog.Error(err)
return
} else {
ctx.Write(p)
}
}
示例13: PostPaths
func (server *Server) PostPaths(ctx *web.Context) string {
var input struct {
Paths []geotypes.NodeEdge
Country string
SpeedProfile int
}
var (
computed []geotypes.Path
)
if err := json.NewDecoder(ctx.Request.Body).Decode(&input); err != nil {
content, _ := ioutil.ReadAll(ctx.Request.Body)
ctx.Abort(400, "Couldn't parse JSON: "+err.Error()+" in '"+string(content)+"'")
return ""
} else {
var err error
computed, err = server.Via.CalculatePaths(input.Paths, input.Country, input.SpeedProfile)
if err != nil {
ctx.Abort(422, "Couldn't resolve addresses: "+err.Error())
return ""
}
}
res, err := json.Marshal(computed)
if err != nil {
ctx.Abort(500, "Couldn't serialize paths: "+err.Error())
return ""
}
ctx.Header().Set("Access-Control-Allow-Origin", "*")
ctx.ContentType("application/json")
return string(res)
}
示例14: getFile
//Handles file retrieval. It uses getURL to send a hash to the urlHandler, and listens on
//sendURL for the proper filename.
func getFile(ctx *web.Context, file string) string {
dir := file[0:3]
fname := file[3:]
path := "files/" + dir + "/" + fname
//Open the file
f, err := os.Open(path)
if err != nil {
return "Error reading file!\n"
}
//Get MIME
r, err := ioutil.ReadAll(f)
if err != nil {
return "Error reading file!\n"
}
mime := http.DetectContentType(r)
_, err = f.Seek(0, 0)
if err != nil {
return "Error reading the file\n"
}
//This is weird - ServeContent supposedly handles MIME setting
//But the Webgo content setter needs to be used too
//In addition, ServeFile doesn't work, ServeContent has to be used
ctx.ContentType(mime)
http.ServeContent(ctx.ResponseWriter, ctx.Request, path, time.Now(), f)
return ""
}
示例15: Put
func (h *RestQueueHandler) Put(ctx *web.Context, val string) {
queue := redisq.NewRedisQueue(h.redis, val)
if !queue.Exists() {
h.logger.Printf("Queue [%s] didn't existst, will be ceated.", val)
}
if mesg, ok := ctx.Params["value"]; ok {
var i interface{}
err := json.Unmarshal([]byte(mesg), &i)
if err != nil {
writeError(ctx, 400, JsonDecodeError)
return
}
err = queue.Put(i)
if err != nil {
writeError(ctx, 500, PostError)
if Settings.Debug {
debug := fmt.Sprintf("Debug: %s", err)
ctx.WriteString(debug)
}
h.logger.Printf("Put message into [%s] Error:%s", val, err)
return
}
h.logger.Printf("Put message into queue [%s]", val)
} else {
writeError(ctx, 400, LackPostValue)
}
}