Пример #1
0
func appHandler(w http.ResponseWriter, r *http.Request) {
	appName := r.URL.Path[len("/app/"):]
	if appName == "" {
		http.NotFound(w, r)
		return
	}

	safeApp, exists := g.RealState.GetSafeApp(appName)
	if !exists {
		http.NotFound(w, r)
		return
	}

	cs := safeApp.Containers()
	vs := make([]*model.Container, len(cs))
	idx := 0
	for _, v := range cs {
		vs[idx] = v
		idx++
	}

	js, err := json.Marshal(vs)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(js)
}
Пример #2
0
// iframeHandler handles the GET and POST of the main page.
func iframeHandler(w http.ResponseWriter, r *http.Request) {
	log.Printf("IFrame Handler: %q\n", r.URL.Path)
	if r.Method != "GET" {
		http.NotFound(w, r)
		return
	}
	match := iframeLink.FindStringSubmatch(r.URL.Path)
	if len(match) != 2 {
		http.NotFound(w, r)
		return
	}
	hash := match[1]
	if db == nil {
		http.NotFound(w, r)
		return
	}
	var code string
	code, source, err := getCode(hash)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	// Expand the template.
	w.Header().Set("Content-Type", "text/html")
	if err := iframeTemplate.Execute(w, userCode{Code: code, Hash: hash, Source: source}); err != nil {
		log.Printf("ERROR: Failed to expand template: %q\n", err)
	}
}
Пример #3
0
func (self *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	route, params, matched := self.rt.Match(r.URL.Path)
	if !matched {
		http.NotFound(w, r)
		return
	}
	ctx := NewContext(w, r)
	ctx.UrlParams = params
	if !route.Resource.OnHandleBegin(ctx) {
		return
	}
	switch r.Method {
	case GET:
		route.Resource.Get(ctx)
	case POST:
		route.Resource.Post(ctx)
	case PUT:
		route.Resource.Put(ctx)
	case DELETE:
		route.Resource.Delete(ctx)
	case PATCH:
		route.Resource.Patch(ctx)
	case OPTIONS:
		route.Resource.Options(ctx)
	case HEAD:
		route.Resource.Head(ctx)
	default:
		http.NotFound(w, r)
	}
	route.Resource.OnHandleEnd(ctx)
}
Пример #4
0
// showcutHandler handles the POST requests of the shortcut page.
//
// Shortcuts are of the form:
//
//    {
//       "scale": 0,
//       "tiles": [-1],
//       "hash": "a1092123890...",
//       "ids": [
//            "x86:...",
//            "x86:...",
//            "x86:...",
//       ]
//    }
//
// hash - The git hash of where a step was detected. Can be null.
//
func shortcutHandler(w http.ResponseWriter, r *http.Request) {
	// TODO(jcgregorio): Add unit tests.
	match := shortcutHandlerPath.FindStringSubmatch(r.URL.Path)
	if match == nil {
		http.NotFound(w, r)
		return
	}
	if r.Method == "POST" {
		// check header
		if ct := r.Header.Get("Content-Type"); ct != "application/json" {
			util.ReportError(w, r, fmt.Errorf("Error: received %s", ct), "Invalid content type.")
			return
		}
		defer util.Close(r.Body)
		id, err := shortcut.Insert(r.Body)
		if err != nil {
			util.ReportError(w, r, err, "Error inserting shortcut.")
			return
		}
		w.Header().Set("Content-Type", "application/json")
		enc := json.NewEncoder(w)
		if err := enc.Encode(map[string]string{"id": id}); err != nil {
			glog.Errorf("Failed to write or encode output: %s", err)
		}
	} else {
		http.NotFound(w, r)
	}
}
Пример #5
0
func ArticleDeleteHandler(w http.ResponseWriter, r *http.Request, action string) {
	if r.Method != "POST" {
		http.NotFound(w, r)
		return
	}

	w.Header().Set("content-type", "application/json")

	defer r.Body.Close()
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.NotFound(w, r)
		return
	}

	var dat map[string]interface{}
	err = json.Unmarshal(body, &dat)
	if err != nil {
		http.NotFound(w, r)
		return
	}

	id := fmt.Sprint(dat["id"])
	service.DeleteArticle(id)

	http.Redirect(w, r, "/articles", http.StatusFound)
}
Пример #6
0
func GetPost(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	postID := GetRequestVar(r, "id", c)

	post, err := FetchPost(postID, c)
	if err != nil {
		c.Infof("Could not fetch post %v: %v", postID, err.Error())
		http.NotFound(w, r)
		return
	}

	postUser, err := FetchAppUser(post.UserID, c)
	if err != nil {
		c.Infof("User %v who created post %v could not be found: %v", post.UserID, postID, err)
		http.NotFound(w, r)
		return
	}

	postView := &PostView{
		Username: postUser.Username,
		ID:       post.ID,
		EventID:  post.EventID,
		Image:    post.Image,
		Text:     post.Text,
		Created:  post.Created,
		Modified: post.Modified,
	}

	sendJsonResponse(w, postView)
}
Пример #7
0
func ViewHandler(w http.ResponseWriter, r *http.Request) {
	url := r.URL.Path[len("/blog/"):]
	if !dateTime.MatchString(url) {
		http.NotFound(w, r)
		return
	}
	year := url[0:4]
	month := url[5:7]
	day := url[8:10]
	title := url[11:]
	postTime, _ := time.Parse("2006-01-02", year+"-"+month+"-"+day)
	updateTime := postTime.AddDate(0, 0, 1)
	article := &Article{Title: title, PostTime: postTime, UpdateTime: updateTime}
	err := article.FindOne()
	if err != nil {
		http.NotFound(w, r)
		return
	}

	vars := make(map[string]interface{})
	vars["article"] = article
	vars["sidebar"] = GetSideBar()
	data := Data{}
	data.Flags.Single = true
	data.Flags.Sidebar = true
	data.Vars = vars
	mainTPL.ExecuteTemplate(w, "main", &data)
}
Пример #8
0
func (f *appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	target := expandPath(f.root, r.URL.Path)
	// if the file exists, just serve it.
	if _, err := os.Stat(target); err == nil {
		f.server.ServeHTTP(w, r)
		return
	}

	// if the missing file isn't a special one, 404.
	if !strings.HasSuffix(r.URL.Path, scriptFileExtension) {
		http.NotFound(w, r)
		return
	}

	source := target[0:len(target)-len(scriptFileExtension)] + ".c.js"

	// Make sure the source exists.
	if _, err := os.Stat(source); err != nil {
		http.NotFound(w, r)
		return
	}

	// handle the special file.
	err := expandSource(w, source)
	if err != nil {
		panic(err)
	}
}
Пример #9
0
func toggleHandler(w http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	id := vars["id"]
	if id == "" {
		http.NotFound(w, req)
		return
	}

	// Check that the item exists
	res, err := r.Table("items").Get(id).Run(session)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if res.IsNil() {
		http.NotFound(w, req)
		return
	}

	// Toggle the item
	_, err = r.Table("items").Get(id).Update(map[string]interface{}{"Status": r.Branch(
		r.Row.Field("Status").Eq("active"),
		"complete",
		"active",
	)}).RunWrite(session)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, req, "/", http.StatusFound)
}
Пример #10
0
func orbitHandler(w http.ResponseWriter, r *http.Request, user userView) {
	id := r.URL.Query().Get("id")
	if id == "" {
		http.Error(w, "'id' param missing", http.StatusBadRequest)
		return
	}

	sat := db.GlobalSatelliteDB().Map[id]
	if sat == nil {
		http.NotFound(w, r)
		return
	}

	if sat.Tle == nil || *sat.Tle == "" {
		http.NotFound(w, r)
		return
	}

	points, err := scheduler.PassDetails(
		time.Now(),
		5*time.Hour,
		0.0, 0.0, 0.0, // Observer is irrelevant.
		*sat.Tle,
		25.0)
	if err != nil {
		log.Printf("Error getting PassDetails: %s", err.Error())
		http.Error(w, "", http.StatusInternalServerError)
		return
	}

	png.Encode(w, orbitMap(points))
}
Пример #11
0
func stringPage(req *StatusRequest, key string) {
	if req.s.snapshot == nil {
		http.NotFound(req.w, req.r)
		return
	}
	fcs, ok := req.s.snapshot.stringCounts[key]
	if !ok {
		http.NotFound(req.w, req.r)
		return
	}
	items := fcs.SortedItems()
	levels := []string{"minute", "hour"}
	data := make([]map[string]interface{}, len(items))
	for i, item := range items {
		data[i] = map[string]interface{}{
			"key":  item.key,
			"rank": i + 1,
		}
		for j, level := range levels {
			c := (*(item.count))[j+1]
			data[i][level] = map[string]interface{}{
				"rate":  c.RatePer(time.Second),
				"total": c.Current,
			}
		}
	}
	req.data = map[string]interface{}{
		"str":   key,
		"items": data,
	}
}
func EffectPutHandler(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	vars := mux.Vars(req)
	deviceId := vars["id"]
	_, ok := dm.Device(deviceId)
	if !ok {
		log.Println("Did not find", deviceId)
		http.NotFound(w, req)
		return
	}
	put := &EffectPut{}
	decoder := json.NewDecoder(req.Body)
	err := decoder.Decode(put)
	if err != nil {
		log.Println(err)
		http.Error(w, "darn f**k it", http.StatusInternalServerError)
		return
	}
	config := deviceapi.DefaultRegistry.Config(put.Name)
	if config == nil {
		log.Println("Did not find", deviceId)
		http.NotFound(w, req)
		return
	}
	err = json.Unmarshal(put.Config, config)
	if err != nil {
		log.Println(err)
		http.Error(w, "darn f**k it config broken", http.StatusInternalServerError)
		return
	}

	err = dm.SetEffect(deviceId, put.Name, config)
	writeStatusResult(w, err)
}
Пример #13
0
// Serves files relative to the webDir
// Only safe if you use with PathPrefix() or similar functions
func RequestPathHandler(w http.ResponseWriter, req *http.Request) {

	path := filepath.Join(webDir, req.URL.Path)

	log.Println("Serving file:", path)

	//do not show directories
	fi, err := os.Stat(path)
	if os.IsNotExist(err) {
		log.Println("[FileHandler] error path does not exist:", err)
		http.NotFound(w, req)
		return
	} else if err != nil {
		http.NotFound(w, req)
		log.Println("[FileHandler] error checking if file is dir:", err)
		http.NotFound(w, req)
		return
	}
	if fi.IsDir() {
		http.NotFound(w, req)
		return
	}

	http.ServeFile(w, req, path)
}
Пример #14
0
func (server *Server) handler() func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		d := server.Config.GetDomain(r.Host)
		if d == nil {
			http.NotFound(w, r)
			return
		}

		if d.HasSSL == true && r.TLS == nil {
			http.Redirect(w, r, fmt.Sprintf("https://%s/%s", r.Host, r.URL.Path), 301)
			return
		}

		glog.Info("[web] Request: ", r.Host, " ", r.URL.Path)

		// TODO: optimize this monster! ;)
		fp := path.Join(server.Config.Web.Path, r.Host, "public_html", r.URL.Path)
		_, err := os.Stat(fp)
		if err != nil {
			fp = path.Join(server.Config.Web.Path, "default", "public_html", r.URL.Path)
			_, err = os.Stat(fp)
			if err != nil {
				if os.IsNotExist(err) {
					glog.Error("[web] Not found: ", fp)
					http.NotFound(w, r)
					return
				}
			}
		}

		http.ServeFile(w, r, fp)
	}
}
Пример #15
0
func qrHandler(w http.ResponseWriter, r *http.Request) {

	uri := r.RequestURI

	// TODO(dgryski): handle /qr/ssid for an html page that renders the QR code with also instructions

	if !strings.HasPrefix(uri, "/qr/") || !strings.HasSuffix(uri, ".png") {
		http.NotFound(w, r)
		return
	}

	ssid := uri[len("/qr/") : len(uri)-len(".png")]

	dbmu.RLock()
	wifi, ok := db[ssid]
	dbmu.RUnlock()

	if !ok {
		http.NotFound(w, r)
		return
	}

	text := wifi.QRText()

	code, err := qr.Encode(text, qr.Q)
	if err != nil {
		log.Printf("error encoding: %q: %v", text, err)
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}

	w.Header().Set("Content-type", "image/png")
	w.Write(code.PNG())
}
Пример #16
0
func deleteHandler(w http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	id := vars["id"]
	if id == "" {
		http.NotFound(w, req)
		return
	}

	// Check that the item exists
	res, err := r.Table("items").Get(id).Run(session)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if res.IsNil() {
		http.NotFound(w, req)
		return
	}

	// Delete the item
	_, err = r.Table("items").Get(id).Delete().RunWrite(session)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, req, "/", http.StatusFound)
}
Пример #17
0
func handleCommand(w http.ResponseWriter, r *http.Request) {

	idAndNumber := r.URL.Path[config.LenCommandPath:]
	var cmd, serialNumber int
	fmt.Sscanf(idAndNumber, "%d/%d", &cmd, &serialNumber)

	if !state.AmILeader() {
		if state.GetLeader() != nil {
			str := fmt.Sprintf("http://%s:%d%s%d/%d",
				state.GetLeader().Ip, state.GetLeader().Port, config.CommandPath, cmd, serialNumber)
			log.Print(str)
			http.Redirect(w, r, str, http.StatusSeeOther)
		} else {
			http.NotFound(w, r)
		}
		return
	}
	resp, err := processCommand(cmd, serialNumber)

	if err != nil {
		http.NotFound(w, r)
	} else {
		fmt.Fprintf(w, "Response: %d\n", resp)
	}
}
Пример #18
0
func serveTemplate(w http.ResponseWriter, r *http.Request) {
	lp := path.Join("templates", "layout.html")
	fp := path.Join("templates", r.URL.Path)

	// request template is 404
	info, err := os.Stat(fp)
	if err != nil {
		if os.IsNotExist(err) {
			http.NotFound(w, r)
			return
		}
	}

	// Req is a directory, 404
	if info.IsDir() {
		http.NotFound(w, r)
		return
	}

	tmpl, err := template.ParseFiles(lp, fp)
	if err != nil {
		log.Println(err.Error())
		http.Error(w, http.StatusText(500), 500)
		return
	}

	if err := tmpl.ExecuteTemplate(w, "layout", nil); err != nil {
		log.Println(err.Error())
		http.Error(w, http.StatusText(500), 500)
	}
}
Пример #19
0
func indexTemplate(w http.ResponseWriter, r *http.Request, todos []*Todo) {
	lp := path.Join("templates", "layout.html")
	fp := path.Join("templates", "index.html")

	// Return a 404 if the template doesn't exist
	info, err := os.Stat(fp)
	if err != nil {
		if os.IsNotExist(err) {
			http.NotFound(w, r)
			return
		}
	}

	// Return a 404 if the request is for a directory
	if info.IsDir() {
		http.NotFound(w, r)
		return
	}

	tmpl, err := template.ParseFiles(lp, fp)
	if err != nil {
		// Log the detailed error
		log.Println(err.Error())
		// Return a generic "Internal Server Error" message
		http.Error(w, http.StatusText(500), 500)
		return
	}

	if err := tmpl.ExecuteTemplate(w, "layout", todos); err != nil {
		log.Println(err.Error())
		http.Error(w, http.StatusText(500), 500)
	}
}
Пример #20
0
func (s *srvdoc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path[:5] != "/doc/" {
		http.NotFound(w, r)
		return
	}
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	path := r.URL.Path[5:]
	pkg := s.src.Find(path)
	if pkg == nil {
		http.NotFound(w, r)
		return
	}
	pkg.Lock()
	dir := pkg.Dir
	pkg.Unlock()
	raw, err := gosrc.LoadHtmlDoc(path, false)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// fix source links
	regex, err := regexp.Compile(fmt.Sprintf(`<a href="(/src/pkg/%s)(.*?\.go)(\?s=\d+:\d+(#L\d+))?"`, path))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	raw = regex.ReplaceAll(raw, []byte(fmt.Sprintf(`<a href="#file%s$2$4"`, dir)))
	w.Write(raw)
}
Пример #21
0
func (h *rootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	urlPath := r.URL.Path
	path, err := filepath.Rel("./", "."+urlPath)
	if err != nil {
		log.Fatalf("error:%v", err)
	}
	_, err = os.Stat(path)
	if err == nil {
		data, err := ioutil.ReadFile(path)
		if err == nil {
			w = setResponse(w, path, data)
			return
		}
	}

	data, err := Asset("assets/templates/slide.html")
	if err != nil {
		log.Printf("error:%v", err)
		http.NotFound(w, r)
		return
	}
	tmpl := template.New("slide template")
	tmpl.Parse(string(data))
	if err != nil {
		log.Printf("error:%v", err)
		http.NotFound(w, r)
		return
	}
	err = tmpl.Execute(w, h.param)
	if err != nil {
		log.Fatalf("error:%v", err)
	}
}
Пример #22
0
func (ui *UIHandler) serveNewUI(rw http.ResponseWriter, req *http.Request) {
	suffix := req.Header.Get("X-PrefixHandler-PathSuffix")
	if ui.closureHandler == nil {
		log.Printf("%v not served: handler is nil", suffix)
		http.NotFound(rw, req)
		return
	}
	suffix = path.Clean(suffix)

	m := closurePattern.FindStringSubmatch(suffix)
	if m != nil {
		req.URL.Path = "/" + m[1]
		ui.closureHandler.ServeHTTP(rw, req)
		return
	}

	var file string
	if suffix == "new" {
		file = "index.html"
	} else {
		m := static2FilePattern.FindStringSubmatch(suffix)
		if m != nil {
			file = m[1]
		}
	}
	if file == "" {
		http.NotFound(rw, req)
		return
	}
	if file == "/deps.js" {
		ui.serveDepsJS(rw, req)
		return
	}
	serveStaticFile(rw, req, newuiFiles, file)
}
Пример #23
0
// ServeHTTP serves:
//   http://host/importer/
//   http://host/importer/twitter/
//   http://host/importer/twitter/callback
//   http://host/importer/twitter/sha1-abcabcabcabcabc (single account)
func (h *Host) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	suffix := httputil.PathSuffix(r)
	seg := strings.Split(suffix, "/")
	if suffix == "" || len(seg) == 0 {
		h.serveImportersRoot(w, r)
		return
	}
	impName := seg[0]

	imp, ok := h.imp[impName]
	if !ok {
		http.NotFound(w, r)
		return
	}

	if len(seg) == 1 || seg[1] == "" {
		h.serveImporter(w, r, imp)
		return
	}
	if seg[1] == "callback" {
		h.serveImporterAcctCallback(w, r, imp)
		return
	}
	acctRef, ok := blob.Parse(seg[1])
	if !ok {
		http.NotFound(w, r)
		return
	}
	h.serveImporterAccount(w, r, imp, acctRef)
}
Пример #24
0
// Handles all HTTP requests.
func (h *Handler) HandleRequest(w http.ResponseWriter, r *http.Request) {
	var (
		err  error
		path string
		info os.FileInfo
	)
	log.Printf("[roomanna] Served path: %q", r.URL.Path)
	path = filepath.Join(h.Path, r.URL.Path)
	if info, err = os.Stat(path); err != nil {
		http.NotFound(w, r)
		return
	}
	if info.IsDir() {
		path = filepath.Join(path, "index.html")
		if info, err = os.Stat(path); err != nil {
			http.NotFound(w, r)
			return
		}
	}
	var (
		maxage   = 3600
		expires  = time.Now().Add(time.Second * time.Duration(maxage))
		ccontrol = fmt.Sprintf("max-age=%v, public", maxage)
	)
	w.Header().Set("Last-Modified", h.LastModified)
	w.Header().Set("Cache-Control", ccontrol)
	w.Header().Set("Expires", expires.Format(time.RFC1123))
	w.Header().Del("Set-Cookie")
	http.ServeFile(w, r, path)
}
Пример #25
0
func handleFile(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var key *cafs.SKey
	if k, err := cafs.ParseKey(r.URL.Path[6:]); err != nil {
		http.NotFound(w, r)
		log.Printf("Error parsing key from URL %v: %v", r.URL, err)
		return
	} else {
		key = k
	}

	var reader io.ReadCloser
	if f, err := client.GetActivityManager().GetStorage().Get(key); err != nil {
		http.NotFound(w, r)
		log.Printf("Error retrieving key %v: %v", key, err)
		return
	} else {
		reader = f.Open()
		f.Dispose()
	}
	defer func() {
		if err := reader.Close(); err != nil {
			log.Printf("Error closing file: %v", err)
		}
	}()

	if _, err := io.Copy(w, reader); err != nil {
		log.Printf("Error sending file contents to client: %v", err)
	}
}
Пример #26
0
// PhishTracker tracks emails as they are opened, updating the status for the given Result
func PhishTracker(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	id := r.Form.Get("rid")
	if id == "" {
		http.NotFound(w, r)
		return
	}
	rs, err := models.GetResult(id)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	c, err := models.GetCampaign(rs.CampaignId, rs.UserId)
	if err != nil {
		Logger.Println(err)
	}
	c.AddEvent(models.Event{Email: rs.Email, Message: models.EVENT_OPENED})
	err = rs.UpdateStatus(models.EVENT_OPENED)
	if err != nil {
		Logger.Println(err)
	}
	// Update the GeoIP information
	ip, _, err := net.SplitHostPort(r.RemoteAddr)
	if err == nil {
		err = rs.UpdateGeo(ip)
		if err != nil {
			Logger.Println(err)
		}
	} else {
		Logger.Println(err)
	}
	w.Write([]byte(""))
}
Пример #27
0
// tryInfoHandler returns information about a specific try.
func tryInfoHandler(w http.ResponseWriter, r *http.Request) {
	log.Printf("Try Info Handler: %q\n", r.URL.Path)
	if r.Method != "GET" {
		http.NotFound(w, r)
		return
	}
	match := tryInfoLink.FindStringSubmatch(r.URL.Path)
	if len(match) != 2 {
		http.NotFound(w, r)
		return
	}
	hash := match[1]
	code, source, err := getCode(hash)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	m := TryInfo{
		Hash:   hash,
		Code:   code,
		Source: source,
	}
	resp, err := json.Marshal(m)
	if err != nil {
		reportError(w, r, err, "Failed to serialize a response.")
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write(resp)
}
Пример #28
0
func GetUser(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	username := GetRequestVar(r, "username", c)
	username = strings.ToLower(username)

	c.Infof("Getting user %v", username)
	userID, err := getUserID(username, c)
	if err != nil {
		c.Infof("Could not find user with username '%v': %v", username, err.Error())
		http.NotFound(w, r)
		return
	}

	c.Infof("User ID is %v", userID)

	appUser, err := FetchAppUser(userID, c)
	if err != nil {
		c.Infof("Could not fetch user '%v': %v", userID, err.Error())
		http.NotFound(w, r)
		return
	}

	resp := UserResponse{true, *appUser}
	sendJsonResponse(w, resp)
}
Пример #29
0
func (s *httpServer) embeddedAssetHandler(w http.ResponseWriter, req *http.Request) {
	var urlRegex = regexp.MustCompile(`^/static/(.+)$`)
	matches := urlRegex.FindStringSubmatch(req.URL.Path)
	if len(matches) == 0 {
		s.ctx.nsqadmin.logf("ERROR:  No embedded asset name for url - %s", req.URL.Path)
		http.NotFound(w, req)
		return
	}
	assetName := matches[1]
	s.ctx.nsqadmin.logf("INFO: Requesting embedded asset - %s", assetName)

	asset, error := templates.Asset(assetName)
	if error != nil {
		s.ctx.nsqadmin.logf("ERROR: embedded asset access - %s : %s", assetName, error)
		http.NotFound(w, req)
		return
	}
	assetLen := len(asset)

	if strings.HasSuffix(assetName, ".js") {
		w.Header().Set("Content-Type", "text/javascript")
	} else if strings.HasSuffix(assetName, ".css") {
		w.Header().Set("Content-Type", "text/css")
	}
	w.Header().Set("Content-Length", fmt.Sprintf("%d", assetLen))
	w.Write(asset)
}
Пример #30
0
// MaybeExtractQ extracts proto from HTTP request and returns it.
// Nil indicates failure, and appropriate status / description is written
// to response.
func MaybeExtractQ(w http.ResponseWriter, r *http.Request, defaultQ proto.Message) *proto.Message {
	q := proto.Clone(defaultQ)
	if r.Method == "POST" {
		reqBody, err := ioutil.ReadAll(r.Body)
		if err != nil {
			fmt.Fprintf(w, "Failed to read POST body %v", err)
			return nil
		}
		err = proto.Unmarshal(reqBody, q)
		if err != nil {
			fmt.Fprintf(w, "Failed to parse POST body as binary proto: %v", err)
			return nil
		}
	} else {
		err := r.ParseForm()
		if err != nil {
			http.NotFound(w, r)
			fmt.Fprintf(w, "strange query %v", err)
			return nil
		}
		pb := r.Form.Get("pb")
		if pb == "" {
			http.NotFound(w, r)
			fmt.Fprintf(w, "Non-empty jsonpb-encoded pb param required for GET")
			return nil
		}
		err = jsonpb.UnmarshalString(pb, q)
		if err != nil {
			fmt.Fprintf(w, "Failed to parse pb param %v", err)
			return nil
		}
	}
	return &q
}