Reputation: 79
this is my code
package main
import "encoding/json"
import "net/http"
import "time"
import "fmt"
import "os"
type Profile struct {
Name string
Hobbies []string
}
func main() {
http.HandleFunc("/", rootFunc)//routeSet()
err :=http.ListenAndServe(":3000", nil)
checkError(err)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal Error", err.Error())
os.Exit(1)
}
}
func rootFunc(w http.ResponseWriter, r *http.Request) {
//fmt.Println("Request url : " + r.RequestURI)
userProfile := make(chan Profile)
go goFun(userProfile, w, r)
profile := <-userProfile
js, err := json.Marshal(profile)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func goFun(u chan Profile, w http.ResponseWriter, r *http.Request) {
// time.Sleep(1 * time.Second)
u <- Profile{"Alex", []string{r.RequestURI, "programming"}}
}
and I send http://localhost:3000/hello by postman
and I recieve
{
"Name": "Alex",
"Hobbies": [
"/hello",
"programming"
]
}
I expected 404 not found, because I use HandleFunc() only for "/"
but i received normal result.
........................... env. go 1.6 max osx
...........................
Upvotes: 0
Views: 162
Reputation: 42413
"/"
is a rooted subtree and matches basically everything. See https://golang.org/pkg/net/http/#ServeMux . (Always consult the documentation before making any assumptions.)
Upvotes: 3