0
这是我的代码。我预计404没有找到,但
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"}}
}
,我通过邮递员
发送http://localhost:3000/hello我收到
{
"Name": "Alex",
"Hobbies": [
"/hello",
"programming"
]
}
我预计404没有发现,因为我使用HandleFunc()仅适用于“/”
但我收到正常结果。
........................... env。 去1.6 最大OSX
...........................
并且您可以添加一个'r.URL'检查,然后使用'http.Error'返回一个404 –