本文整理汇总了Golang中github.com/hoisie/web.Context类的典型用法代码示例。如果您正苦于以下问题:Golang Context类的具体用法?Golang Context怎么用?Golang Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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 ""
}
开发者ID:Luminarys,项目名称:tenshi,代码行数:32,代码来源:main.go
示例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)
}
开发者ID:stevenleeg,项目名称:goblog,代码行数:26,代码来源:remove.go
示例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 ""
}
开发者ID:elimisteve,项目名称:monet,代码行数:7,代码来源:admin.go
示例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"))
}
开发者ID:JanSichula,项目名称:coconut,代码行数:7,代码来源:controller.go
示例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 ""
}
开发者ID:Luminarys,项目名称:patchy,代码行数:25,代码来源:getHandling.go
示例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)
}
开发者ID:johnpmayer,项目名称:commissar,代码行数:7,代码来源:game.go
示例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)
}
开发者ID:kevinburke,项目名称:snapchat-friends,代码行数:26,代码来源:hello.go
示例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)
}
}
开发者ID:Kalipsol,项目名称:factomd,代码行数:30,代码来源:wsapi.go
示例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)
}
开发者ID:Kalipsol,项目名称:factomd,代码行数:26,代码来源:wsapi.go
示例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)
}
}
开发者ID:Kalipsol,项目名称:factomd,代码行数:30,代码来源:wsapi.go
示例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)
}
}
开发者ID:JGets,项目名称:reduse,代码行数:67,代码来源:pageFunc.go
示例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)
}
}
开发者ID:Kalipsol,项目名称:factomd,代码行数:26,代码来源:wsapi.go
示例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)
}
开发者ID:nfleet,项目名称:via,代码行数:34,代码来源:api.go
示例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 ""
}
开发者ID:Luminarys,项目名称:Sto,代码行数:30,代码来源:getHandling.go
示例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)
}
}
开发者ID:kenshinx,项目名称:restmq.go,代码行数:30,代码来源:web.go
示例16: vnstat
func vnstat(ctx *web.Context, iface string, debug string) string {
app := "vnstat"
arg0 := "-i"
arg2 := "--xml"
ctx.SetHeader("Content-Type", "application/json", true)
rawxml := runcmd(app, arg0, iface, arg2)
var q Vnstat
xml.Unmarshal([]byte(rawxml), &q)
var jsondata []byte
var err error
if debug == "debug" {
jsondata, err = json.MarshalIndent(q, "", " ")
} else {
jsondata, err = json.Marshal(q)
}
if err != nil {
return "Error"
}
return string(jsondata)
}
开发者ID:orvice,项目名称:iVnstat,代码行数:27,代码来源:server.go
示例17: pngHandler
func pngHandler(ctx *web.Context, path string) {
file, err := os.Open(path)
check(err)
ctx.ContentType("png")
_, err = io.Copy(ctx, file)
check(err)
}
开发者ID:johnpmayer,项目名称:commissar,代码行数:7,代码来源:game.go
示例18: Render
func Render(ctx *web.Context, tmpl string, config *Config, name string, data interface{}) {
tmpl = filepath.Join(config.Get("datadir"), tmpl)
ctx.WriteString(mustache.RenderFile(tmpl,
map[string]interface{}{
"config": config,
name: data}))
}
开发者ID:fjj596894378,项目名称:blogo,代码行数:7,代码来源:blogo.go
示例19: gamePageHandler
func gamePageHandler(ctx *web.Context) {
gamePage, err := os.Open("index.html")
check(err)
ctx.ContentType("html")
_, err = io.Copy(ctx, gamePage)
check(err)
}
开发者ID:johnpmayer,项目名称:commissar,代码行数:7,代码来源:game.go
示例20: checkGodLevel
func checkGodLevel(ctx *web.Context) bool {
godlevel, _ := ctx.GetSecureCookie("godlevel")
godlevel = godHash(godlevel)
if godlevel == admin_pass {
return true
}
return false
}
开发者ID:youngking,项目名称:fettemama,代码行数:8,代码来源:admin.go
注:本文中的github.com/hoisie/web.Context类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论