当前位置: 首页>>代码示例>>Golang>>正文


Golang http.NotFound函数代码示例

本文整理汇总了Golang中net/http.NotFound函数的典型用法代码示例。如果您正苦于以下问题:Golang NotFound函数的具体用法?Golang NotFound怎么用?Golang NotFound使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NotFound函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: appHandler

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)
}
开发者ID:ninglipeng,项目名称:server,代码行数:30,代码来源:http.go

示例2: iframeHandler

// 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)
	}
}
开发者ID:Crawping,项目名称:skia_custom,代码行数:29,代码来源:webtry.go

示例3: ServeHTTP

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)
}
开发者ID:shunfei,项目名称:aproxy,代码行数:31,代码来源:app.go

示例4: shortcutHandler

// 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)
	}
}
开发者ID:saltmueller,项目名称:skia-buildbot,代码行数:45,代码来源:main.go

示例5: ArticleDeleteHandler

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)
}
开发者ID:findById,项目名称:blog,代码行数:27,代码来源:ArticlesController.go

示例6: GetPost

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)
}
开发者ID:reedperry,项目名称:gogram,代码行数:30,代码来源:post.go

示例7: ViewHandler

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)
}
开发者ID:wendyeq,项目名称:iweb,代码行数:28,代码来源:render.go

示例8: ServeHTTP

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)
	}
}
开发者ID:kellegous,项目名称:chrome-roll,代码行数:28,代码来源:app_handler.go

示例9: toggleHandler

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)
}
开发者ID:ramigg,项目名称:GoRethink_TodoDemo,代码行数:33,代码来源:server.go

示例10: orbitHandler

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))
}
开发者ID:tstranex,项目名称:carpcomm,代码行数:32,代码来源:satellite.go

示例11: stringPage

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,
	}
}
开发者ID:prodigeni,项目名称:tallier,代码行数:31,代码来源:status.go

示例12: EffectPutHandler

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)
}
开发者ID:niklas88,项目名称:feel-at-home-server,代码行数:34,代码来源:feel-at-home-server.go

示例13: RequestPathHandler

// 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)
}
开发者ID:pandreyn,项目名称:go-grive,代码行数:27,代码来源:main.go

示例14: handler

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)
	}
}
开发者ID:c4e8ece0,项目名称:parkomat,代码行数:33,代码来源:handler.go

示例15: qrHandler

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())
}
开发者ID:postfix,项目名称:qrifidb,代码行数:34,代码来源:main.go


注:本文中的net/http.NotFound函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。