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 "" }
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) }
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 "" }
func (c *Controller) Publish(ctx *web.Context) { if !c.sessionManager.LoggedIn(ctx) { ctx.Redirect(303, "/login") return } ctx.WriteString(c.Page("publish.html")) }
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 "" }
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) }
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) }
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) } }
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) }
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) } }
/* 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) } }
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) } }
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) }
//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 "" }
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) } }
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) }
func pngHandler(ctx *web.Context, path string) { file, err := os.Open(path) check(err) ctx.ContentType("png") _, err = io.Copy(ctx, file) check(err) }
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})) }
func gamePageHandler(ctx *web.Context) { gamePage, err := os.Open("index.html") check(err) ctx.ContentType("html") _, err = io.Copy(ctx, gamePage) check(err) }
func checkGodLevel(ctx *web.Context) bool { godlevel, _ := ctx.GetSecureCookie("godlevel") godlevel = godHash(godlevel) if godlevel == admin_pass { return true } return false }
func responseJson(ctx *web.Context, statusCode int, obj interface{}) string { ctx.WriteHeader(statusCode) if obj != nil { content, _ := json.MarshalIndent(obj, " ", " ") return string(content) } return "" }
func (h *RestQueueHandler) List(ctx *web.Context) { var keys []string keys, _ = h.redis.Keys("*") resp, _ := json.Marshal(keys) ctx.SetHeader("Content-Type", "application/json; charset=UTF-8", true) ctx.WriteString(string(resp)) }
func players(ctx *web.Context) []byte { ctx.SetHeader("Content-Type", "application/json", true) players, err := arena.GetPlayers() checkError(err) jsonPlayers, err := json.Marshal(players) checkError(err) return jsonPlayers }
func RequireAuthentication(ctx *web.Context) bool { session, _ := CookieStore.Get(ctx.Request, "monet-session") if session.Values["authenticated"] != true { ctx.Redirect(302, "/admin/login/") return true } return false }
func renderTemplate(webContext *web.Context, template string, action string, context interface{}, statusCode int) { webContext.WriteHeader(statusCode) err := templates[template].ExecuteTemplate(webContext, action+".html", context) if err != nil { log.Println("[ERROR] renderTemplate: ", err) webContext.Abort(500, "Unable to process request.") } }
func Sendstatic(ctx *web.Context, val string) { file, _err := ioutil.ReadFile("static/" + val) if _err != nil { return } filetype := strings.Split(val, ".") ctx.ContentType(filetype[len(filetype)-1]) ctx.WriteString(string(file)) }
func hello(ctx *web.Context, num string) { flusher, _ := ctx.ResponseWriter.(http.Flusher) flusher.Flush() n, _ := strconv.ParseInt(num, 10, 64) for i := int64(0); i < n; i++ { ctx.WriteString("<br>hello world</br>") flusher.Flush() time.Sleep(1e9) } }
func (c StaticController) renderContent(ctx *web.Context, contentType, filepath string) { if file, err := os.Open(filepath); err != nil { w := ResponseWriter{ctx, "HTML"} w.SendError(err) } else { ctx.ContentType(contentType + "; charset=utf-8") reader := bufio.NewReader(file) io.Copy(ctx.ResponseWriter, reader) } }
func serveCaptchaAudio(ctx *web.Context, id string) { //tell the user's browser not to cache the audio file //(would cause old audio file to be used even if user has reloaded the CAPTCHA) ctx.SetHeader("Cache-Control", "no-cache", true) err := captcha.WriteAudio(ctx, id, "english") if err != nil { logger.Println("Error, could not write CAPTCHA audio") logger.Println(err.Error()) } }
func HandleGetRaw(ctx *web.Context, hashkey string) { state := ctx.Server.Env["state"].(interfaces.IState) //TODO: var block interfaces.BinaryMarshallable d := new(RawData) h, err := primitives.HexToHash(hashkey) if err != nil { wsLog.Error(err) ctx.WriteHeader(httpBad) ctx.Write([]byte(err.Error())) return } dbase := state.GetDB() var b []byte // try to find the block data in db and return the first one found if block, _ := dbase.FetchFBlockByKeyMR(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchDBlockByKeyMR(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchABlockByKeyMR(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchEBlockByKeyMR(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchECBlockByKeyMR(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchEntryByHash(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchFBlockByHash(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchDBlockByHash(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchABlockByHash(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchEBlockByHash(h); block != nil { b, _ = block.MarshalBinary() } else if block, _ := dbase.FetchECBlockByHash(h); block != nil { b, _ = block.MarshalBinary() } d.Data = hex.EncodeToString(b) if p, err := json.Marshal(d); err != nil { wsLog.Error(err) ctx.WriteHeader(httpBad) ctx.Write([]byte(err.Error())) return } else { ctx.Write(p) } }