Golang NotFound示例

说明

golang notfound示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http

示例#1
文件: http.go 项目: ninglipeng/server

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
文件: webtry.go 项目: Crawping/skia_custom

// 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
文件: app.go 项目: shunfei/aproxy

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
文件: main.go 项目: saltmueller/skia-buildbot

// 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
文件: ArticlesController.go 项目: findById/blog

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
文件: post.go 项目: reedperry/gogram

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
文件: render.go 项目: wendyeq/iweb

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
文件: app_handler.go 项目: kellegous/chrome-roll

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
文件: server.go 项目: ramigg/GoRethink_TodoDemo

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
文件: satellite.go 项目: tstranex/carpcomm

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
文件: status.go 项目: prodigeni/tallier

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,
	}
}

示例#12
文件: feel-at-home-server.go 项目: niklas88/feel-at-home-server

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 fuck 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 fuck it config broken", http.StatusInternalServerError)
		return
	}

	err = dm.SetEffect(deviceId, put.Name, config)
	writeStatusResult(w, err)
}

示例#13
文件: main.go 项目: pandreyn/go-grive

// 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
文件: handler.go 项目: c4e8ece0/parkomat

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
文件: main.go 项目: postfix/qrifidb

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
文件: server.go 项目: ramigg/GoRethink_TodoDemo

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
文件: handler.go 项目: pooya/craft

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
文件: server.go 项目: yongzhihuang/go-web-server

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
文件: todo.go 项目: tthanh/gotodo

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
文件: content.go 项目: napsy/lab

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
文件: server.go 项目: yusukebe/revealgo

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
文件: ui.go 项目: t3rm1n4l/camlistore

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
文件: importer.go 项目: peterwatts/camlistore

// 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
文件: roomanna.go 项目: kurrik/roomanna

// 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
文件: client_main.go 项目: TimSylvester/bitwrk

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
文件: route.go 项目: 666jfox777/gophish

// 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
文件: webtry.go 项目: Crawping/skia_custom

// 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
文件: user.go 项目: reedperry/gogram

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
文件: http.go 项目: zhangyuchen0411/nsq

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
文件: main.go 项目: xanxys/bonsai

// 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
}

展开阅读全文