本文整理汇总了Golang中net/http.NotFoundHandler函数的典型用法代码示例。如果您正苦于以下问题:Golang NotFoundHandler函数的具体用法?Golang NotFoundHandler怎么用?Golang NotFoundHandler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NotFoundHandler函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServeHTTP
// ServeHTTP dispatches the handler registered in the matched route.
//
// When there is a match, the route variables can be retrieved calling
// mux.Vars(request).
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Clean path to canonical form and redirect.
if p := cleanPath(req.URL.Path); p != req.URL.Path {
// Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
// This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
// http://code.google.com/p/go/issues/detail?id=5252
url := *req.URL
url.Path = p
p = url.String()
w.Header().Set("Location", p)
w.WriteHeader(http.StatusMovedPermanently)
return
}
var match RouteMatch
var handler http.Handler
if r.Match(req, &match) {
handler = match.Handler
setVars(req, match.Vars)
setCurrentRoute(req, match.Route)
}
if handler == nil {
handler = r.NotFoundHandler
if handler == nil {
handler = http.NotFoundHandler()
}
}
if !r.KeepContext {
defer context.Clear(req)
}
handler.ServeHTTP(w, req)
}
示例2: createHandler
// Creates a GorillaMux router containing the HTTP handlers for a server.
func createHandler(sc *serverContext) http.Handler {
r := mux.NewRouter()
r.StrictSlash(true)
// Global operations:
r.Handle("/", makeHandler(sc, (*handler).handleRoot)).Methods("GET", "HEAD")
r.Handle("/_all_dbs", makeHandler(sc, (*handler).handleAllDbs)).Methods("GET", "HEAD")
if len(sc.databases) == 1 {
// If there is exactly one database we can handle the standard /_session by just redirecting
// it to that database's _session handler.
for _, db := range sc.databases {
path := "/" + db.dbcontext.Name
r.Handle("/_session", http.RedirectHandler(path+"/_session", http.StatusTemporaryRedirect))
r.Handle("/_persona", http.RedirectHandler(path+"/_persona", http.StatusTemporaryRedirect))
}
} else {
r.Handle("/_session", http.NotFoundHandler())
r.Handle("/_persona", http.NotFoundHandler())
}
// Operations on databases:
r.Handle("/{newdb}/", makeHandler(sc, (*handler).handleCreateDB)).Methods("PUT")
r.Handle("/{db}/", makeHandler(sc, (*handler).handleGetDB)).Methods("GET", "HEAD")
r.Handle("/{db}/", makeHandler(sc, (*handler).handleDeleteDB)).Methods("DELETE")
r.Handle("/{db}/", makeHandler(sc, (*handler).handlePostDoc)).Methods("POST")
// Special database URLs:
dbr := r.PathPrefix("/{db}/").Subrouter()
dbr.Handle("/_all_docs", makeHandler(sc, (*handler).handleAllDocs)).Methods("GET", "HEAD", "POST")
dbr.Handle("/_bulk_docs", makeHandler(sc, (*handler).handleBulkDocs)).Methods("POST")
dbr.Handle("/_bulk_get", makeHandler(sc, (*handler).handleBulkGet)).Methods("GET", "HEAD")
dbr.Handle("/_changes", makeHandler(sc, (*handler).handleChanges)).Methods("GET", "HEAD")
dbr.Handle("/_design/sync_gateway", makeHandler(sc, (*handler).handleDesign)).Methods("GET", "HEAD")
dbr.Handle("/_ensure_full_commit", makeHandler(sc, (*handler).handleEFC)).Methods("POST")
dbr.Handle("/_revs_diff", makeHandler(sc, (*handler).handleRevsDiff)).Methods("POST")
// Session/login URLs are per-database (unlike in CouchDB)
dbr.Handle("/_session", makeAdminHandler(sc, (*handler).handleSessionGET)).Methods("GET", "HEAD")
dbr.Handle("/_session", makeAdminHandler(sc, (*handler).handleSessionPOST)).Methods("POST")
if sc.config.Persona != nil {
dbr.Handle("/_persona", makeAdminHandler(sc, (*handler).handlePersonaPOST)).Methods("POST")
}
// Document URLs:
dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handleGetLocalDoc)).Methods("GET", "HEAD")
dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handlePutLocalDoc)).Methods("PUT")
dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handleDelLocalDoc)).Methods("DELETE")
dbr.Handle("/{docid}", makeHandler(sc, (*handler).handleGetDoc)).Methods("GET", "HEAD")
dbr.Handle("/{docid}", makeHandler(sc, (*handler).handlePutDoc)).Methods("PUT")
dbr.Handle("/{docid}", makeHandler(sc, (*handler).handleDeleteDoc)).Methods("DELETE")
dbr.Handle("/{docid}/{attach}", makeHandler(sc, (*handler).handleGetAttachment)).Methods("GET", "HEAD")
// Fallbacks that have to be added last:
r.PathPrefix("/").Methods("OPTIONS").Handler(makeHandler(sc, (*handler).handleOptions))
r.PathPrefix("/").Handler(makeHandler(sc, (*handler).handleBadRoute))
return r
}
示例3: nodeHandler
// nodeHandler handles requests for '/api/<version>/nodes/<system_id>/'.
func nodeHandler(server *TestServer, w http.ResponseWriter, r *http.Request, systemId string, operation string) {
node, ok := server.nodes[systemId]
if !ok {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
UUID, UUIDError := node.values["system_id"].GetString()
if r.Method == "GET" {
if operation == "" {
w.WriteHeader(http.StatusOK)
if UUIDError == nil {
i, err := JSONObjectFromStruct(server.client, server.nodeMetadata[UUID].Interfaces)
checkError(err)
if err == nil {
node.values["interface_set"] = i
}
}
fmt.Fprint(w, marshalNode(node))
return
} else if operation == "details" {
if UUIDError == nil {
i, err := JSONObjectFromStruct(server.client, server.nodeMetadata[UUID].Interfaces)
if err == nil {
node.values["interface_set"] = i
}
}
nodeDetailsHandler(server, w, r, systemId)
return
} else {
w.WriteHeader(http.StatusBadRequest)
return
}
}
if r.Method == "POST" {
// The only operations supported are "start", "stop" and "release".
if operation == "start" || operation == "stop" || operation == "release" {
// Record operation on node.
server.addNodeOperation(systemId, operation, r)
if operation == "release" {
delete(server.OwnedNodes(), systemId)
}
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, marshalNode(node))
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
if r.Method == "DELETE" {
delete(server.nodes, systemId)
w.WriteHeader(http.StatusOK)
return
}
http.NotFoundHandler().ServeHTTP(w, r)
}
示例4: spacesHandler
// spacesHandler handles requests for '/api/<version>/spaces/'.
func spacesHandler(server *TestServer, w http.ResponseWriter, r *http.Request) {
var err error
spacesURLRE := regexp.MustCompile(`/spaces/(.+?)/`)
spacesURLMatch := spacesURLRE.FindStringSubmatch(r.URL.Path)
spacesURL := getSpacesEndpoint(server.version)
var ID uint
var gotID bool
if spacesURLMatch != nil {
ID, err = NameOrIDToID(spacesURLMatch[1], server.spaceNameToID, 1, uint(len(server.spaces)))
if err != nil {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
gotID = true
}
switch r.Method {
case "GET":
w.Header().Set("Content-Type", "application/vnd.api+json")
if len(server.spaces) == 0 {
// Until a space is registered, behave as if the endpoint
// does not exist. This way we can simulate older MAAS
// servers that do not support spaces.
http.NotFoundHandler().ServeHTTP(w, r)
return
}
if r.URL.Path == spacesURL {
var spaces []Space
for i := uint(1); i < server.nextSpace; i++ {
s, ok := server.spaces[i]
if ok {
spaces = append(spaces, s)
}
}
err = json.NewEncoder(w).Encode(spaces)
} else if gotID == false {
w.WriteHeader(http.StatusBadRequest)
} else {
err = json.NewEncoder(w).Encode(server.spaces[ID])
}
checkError(err)
case "POST":
//server.NewSpace(r.Body)
case "PUT":
//server.UpdateSpace(r.Body)
case "DELETE":
delete(server.spaces, ID)
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusBadRequest)
}
}
示例5: TestRouterEventHandler
func TestRouterEventHandler(t *testing.T) {
routes := make(map[string]bool)
routes["GET /api/v1/settings"] = false
routes["GET /api/v1/group1/hello"] = false
routes["GET /api/v1/group1/group2/hello"] = false
routes["GET /api/v1/apps/:app/clients/users/:userid/info"] = false
routes["OPTIONS /api/v1/settings"] = false
routes["HEAD /api/v1/settings"] = false
routes["DELETE /api/v1/settings"] = false
routes["POST /api/v1/settings"] = false
routes["PUT /api/v1/settings"] = false
routes["PATCH /api/v1/settings"] = false
routes["NotFound"] = false
routes["MethodNotAllowed"] = false
r := New()
r.EventHandler(func(evt Event) {
switch e := evt.(type) {
case AddHandlerEvent:
routes[e.Method+" "+e.Path] = true
// t.Logf("%s %s", e.Method, e.Path)
case NotFoundHandlerEvent:
routes["NotFound"] = true
case MethodNotAllowedHandlerEvent:
routes["MethodNotAllowed"] = true
}
})
r.NotFound(http.NotFoundHandler())
r.MethodNotAllowed(http.NotFoundHandler())
// api group
api := r.Group("/api/v1")
api.GET("/settings", GetTest)
api.OPTIONS("/settings", OptionsTest)
api.HEAD("/settings", HeadTest)
api.DELETE("/settings", DeleteTest)
api.POST("/settings", PostTest)
api.PUT("/settings", PutTest)
api.PATCH("/settings", PatchTest)
// Create router group and handler
group1 := api.Group("/group1")
group1.GET("/hello", GetTest)
// Create nested group and route
group2 := group1.Group("/group2")
group2.GET("/hello", GetTest)
appGroup := api.Group("/apps/:app")
clientGroup := appGroup.Group("/clients")
clientGroup.GET("/users/:userid/info", GetTest)
for k, v := range routes {
assert.True(t, v, "%s should be true", k)
}
}
示例6: releaseIPAddressHandler
func releaseIPAddressHandler(server *TestServer, w http.ResponseWriter, r *http.Request, ip string) {
if netIP := net.ParseIP(ip); netIP == nil {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
if server.RemoveIPAddress(ip) {
w.WriteHeader(http.StatusOK)
return
}
http.NotFoundHandler().ServeHTTP(w, r)
}
示例7: deviceHandler
// deviceHandler handles requests for '/api/<version>/devices/<system_id>/'.
func deviceHandler(server *TestServer, w http.ResponseWriter, r *http.Request, systemId string, operation string) {
device, ok := server.devices[systemId]
if !ok {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
if r.Method == "GET" {
deviceJSON := renderDevice(device)
if operation == "" {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, deviceJSON)
return
} else {
w.WriteHeader(http.StatusBadRequest)
return
}
}
if r.Method == "POST" {
if operation == "claim_sticky_ip_address" {
err := r.ParseForm()
checkError(err)
values := r.PostForm
// TODO(mfoord): support optional mac_address parameter
// TODO(mfoord): requested_address should be optional
// and we should generate one if it isn't provided.
address, hasAddress := getValue(values, "requested_address")
if !hasAddress {
w.WriteHeader(http.StatusBadRequest)
return
}
checkError(err)
device.IPAddresses = append(device.IPAddresses, address)
deviceJSON := renderDevice(device)
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, deviceJSON)
return
} else {
w.WriteHeader(http.StatusBadRequest)
return
}
} else if r.Method == "DELETE" {
delete(server.devices, systemId)
w.WriteHeader(http.StatusNoContent)
return
}
// TODO(mfoord): support PUT method for updating device
http.NotFoundHandler().ServeHTTP(w, r)
}
示例8: main
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/login", login)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":8000", nil)
}
示例9: main
func main(){
http.Handle("/favicon.ico",http.NotFoundHandler())
http.HandleFunc("/",func(res http.ResponseWriter,req *http.Request){
cookie, err := req.Cookie("session-id")
if err == http.ErrNoCookie{
id, _ := uuid.NewV4()
cookie = &http.Cookie{
Name: "session-id",
Value: id.String(),
HttpOnly:true,
}
}
if(req.FormValue("name") != "" && !strings.Contains(cookie.Value, "name")){
cookie.Value = cookie.Value + `name= ` + req.FormValue("name")
}
http.SetCookie(res, cookie)
io.WriteString(res,`<!DOCTYPE html>
<html>
<body>
<form method="POST">
`+cookie.Value+`
<br/>
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>`)
})
http.ListenAndServe(":8080",nil)
}
示例10: init
func init() {
http.HandleFunc("/", handleIndex)
http.HandleFunc("/put", handlePut)
http.HandleFunc("/get", handleGet)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public/"))))
}
示例11: main
func main() {
http.Handle("/favicon.ico", http.NotFoundHandler())
http.HandleFunc("/", homepage)
http.HandleFunc("/show", show)
http.ListenAndServe("localhost:8080", nil)
}
示例12: main
func main() {
http.HandleFunc("/", serve)
http.Handle("/favicon.ico", http.NotFoundHandler())
log.Println("Listening...")
http.ListenAndServe(":8080", nil)
}
示例13: Example
func Example() {
// Set up an HTTP server
listener, err := net.Listen("tcp", ":80")
if err != nil {
os.Exit(1)
}
// app.Serve is a shortcut for using the listener as a closer and calling Serve()
app.Serve(listener, &http.Server{
Handler: http.NotFoundHandler(), //example, use real handler
})
// You can run one-time tasks too with app.Go
app.Go(func() error {
if !registerMyselfSomewhere() {
return errors.New("Registration failed. Shutting down...")
}
return nil
})
setupHeartbeat()
// main will wait for all goroutines to complete and then run closers.
app.Main()
}
示例14: jsonflowsAPIRequest
func jsonflowsAPIRequest(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.NotFoundHandler().ServeHTTP(w, r)
}
flowIDStr := r.FormValue("flowID")
if flowIDStr == "" {
x := jsonflowsSendAll()
fmt.Fprintf(w, "%s", x)
return
}
flowID, err := strconv.ParseUint(flowIDStr, 10, 64)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Invalid flowID")
return
}
fi, err := flowTracker.GetFlow(flowID)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Invalid flowID")
return
}
fmt.Fprintf(w, "{%s}", fi.JSON())
}
示例15: init
func init() {
r := httprouter.New()
http.Handle("/", r)
r.GET("/", home)
r.GET("/following", fing)
r.GET("/followingme", fingme)
r.GET("/user/:user", user)
r.GET("/form/login", login)
r.GET("/form/signup", signup)
r.POST("/api/checkusername", checkUserName)
r.POST("/api/createuser", createUser)
r.POST("/api/login", loginProcess)
r.POST("/api/tweet", tweetProcess)
r.GET("/api/logout", logout)
r.GET("/api/follow/:user", follow)
r.GET("/api/unfollow/:user", unfollow)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public/"))))
tpl = template.New("roottemplate")
tpl = tpl.Funcs(template.FuncMap{
"humanize_time": humanize.Time,
})
tpl = template.Must(tpl.ParseGlob("templates/html/*.html"))
}