本文整理汇总了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)
}
示例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)
}
}
示例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)
}
示例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)
}
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
}
示例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)
}
示例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))
}
示例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,
}
}
示例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)
}
示例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)
}
示例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)
}
}
示例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())
}