为什么 Golang 将我的 POST 请求当作 GET 请求处理?

huangapple go评论115阅读模式
英文:

Why Golang treats my POST request as a GET one?

问题

我的服务器代码如下:

// 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
    // ...
}

客户端代码如下:

// 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);
}];

当我在 iPhone 模拟器上运行这段 iOS 代码时,服务器端显示:

method: GET
content length: 0

将客户端代码更改为 [req setHTTPMethod:@"HEAD"];,服务器端工作正常:

method: HEAD
content length: <some length>

我不知道客户端的 POST 代码有什么问题,或者服务器端应该如何获取客户端发送的数据作为 []byte

另外,我的 Go 版本是:

$ go version
go version go1.2.1 darwin/amd64
英文:

My server code like:

// golang
type SomeHandler struct{}

func (*SomeHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    fmt.Println(&quot;method:&quot;, req.Method)
    fmt.Println(&quot;content length:&quot;, 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:@&quot;POST&quot;];
[req setValue:@&quot;application/json; charset=utf-8&quot; forHTTPHeaderField:@&quot;Content-Type&quot;];

id obj = @{
             @&quot;username&quot; : @&quot;myname&quot;,
             @&quot;password&quot; : @&quot;mypwd&quot;,
          };
NSError *error;
NSData *inputJson = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&amp;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(@&quot;ERROR: %@&quot;, error.localizedDescription);
        return;
    }

    NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
    NSString *outputText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@&quot;response (%d):\n%@&quot;, (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:@&quot;HEAD&quot;];, the server works:

method: HEAD
content length: &lt;some length&gt;

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

答案1

得分: 8

我解决了!如此奇怪的行为。我不知道为什么会发生这种情况。

我注册了我的处理程序,像这样:

// addr := ...
r := mux.NewRouter()
r.Handle("/abc", new(SomeHandler))
http.Handle("/", r)
// 这里的mux是github.com/gorilla/mux
// 这些代码行与下面的代码行做的事情是一样的:
//   http.handle("/abc", new(SomeHandler))

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

然后我的客户端发送了一个请求,说

http://addr:9999//abc

但正确的URL应该是

http://addr:9999/abc

在调用-stringByAppendingString:方法时产生了多余的/

英文:

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(&quot;/abc&quot;, new(SomeHandler))
http.Handle(&quot;/&quot;, r)
// here mux is github.com/gorilla/mux
// these lines of code do the same thing as wrote:
//   http.handle(&quot;/abc&quot;, 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.

huangapple
  • 本文由 发表于 2014年5月5日 09:38:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/23463601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定