Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Golang treats my POST request as a GET one?

Tags:

http

ios

go

My server code like:

// golang
type SomeHandler struct{}

func (*SomeHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    fmt.Println("method:", req.Method)
    fmt.Println("content length:", req.ContentLength)

    // read request body as []byte
    content, err := ioutil.ReadAll(req.Body)
    if err != nil {
        // do sth.
        return
    }

    // decode JSON
    // ...
}

Client side:

// Objective-C on iOS 6/7
// NSURL *myUrl = ...
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:myUrl];
[req setHTTPMethod:@"POST"];
[req setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

id obj = @{
             @"username" : @"myname",
             @"password" : @"mypwd",
          };
NSError *error;
NSData *inputJson = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&error];
if (error) {
    // no error here
}
[req setHTTPBody:inputJson];

[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    if (error) {
        NSLog(@"ERROR: %@", error.localizedDescription);
        return;
    }

    NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
    NSString *outputText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"response (%d):\n%@", (int)resp.statusCode, outputText);
}

When I run this iOS code in iPhone simulator the server side shows:

method: GET
content length: 0

Chage my client side code: [req setHTTPMethod:@"HEAD"];, the server works:

method: HEAD
content length: <some length>

I don't know what's wrong with my POST code on the client or what should I do on the server to retrieve data as []byte my client just sent.

btw, my go version:

$ go version
go version go1.2.1 darwin/amd64
like image 926
Eric Chai Avatar asked Mar 19 '23 17:03

Eric Chai


1 Answers

I solved this! So strange behavior. I don't know why this could happen.

I register my handler like:

// addr := ...
r := mux.NewRouter()
r.Handle("/abc", new(SomeHandler))
http.Handle("/", r)
// here mux is github.com/gorilla/mux
// these lines of code do the same thing as wrote:
//   http.handle("/abc", new(SomeHandler))

err := http.ListenAndServe(addr, nil)
// ...

Then my client sends a request to say

http://addr:9999//abc

But the correct URL should be

http://addr:9999/abc

The redundant / generated when call -stringByAppendingString: method.

like image 164
Eric Chai Avatar answered Mar 22 '23 12:03

Eric Chai