简体   繁体   中英

how to send http request in golang to my own server

I'm writing a simple webserver in golang that gets/creates/edits/deletes a simple text file. I've written the function handlers and I'd like to test them by sending a request to the appropriate url and checking to see what happens. My code is as below:

func createHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    name := vars["name"]
    body, _ := ioutil.ReadAll(r.Body)
    fmt.Fprint(w, name)
    ioutil.WriteFile(name, []byte(body), 0644)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/textFiles/{name}", createHandler).Methods("POST")
    log.Fatal(http.ListenAndServe(":8080", r))

    var url = "http://localhost:8080/textFiles/testFile.txt"
    var text = []byte(`{"title":"this is an example."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(text))
    if err != nil {
        panic(err)
    }

    client := &http.Client{}
    client.Do(req)
}

Once this code is run, however, no new file is created. I've been googling but I can't find anything on this type of problem, where I'm sending a request to the server that I'm building within the same file. Help appreciated.

The client code is not executed. The call http.ListenAndServe(":8080", r) runs the server. The function only returns when there was an error running the server. If the function does return, then log.Fatal will exit the process.

One fix is to run the server in a goroutine. This will allow main goroutine to continue executing to the client code.

go func() {
    log.Fatal(http.ListenAndServe(":8080", r))
}()

This may not fix the problem because there's no guarantee that server will run before the client makes the request. Fix this issue by creating the listening socket in the main function and running the server in a goroutine.

ln, err := net.Listen("tcp", ":8080")
if err != nil {
    log.Fatal(err)
}
go func() {
    log.Fatal(http.Serve(ln, r))
}()
... client code as before

If the goal if this code is testing, then use httptest.Server . The example in the documentation show show to use the test server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM