duanmie9682 2019-02-15 19:57 采纳率: 100%
浏览 91

用户存在时服务器返回400

I'm working on some tests in Go and I have spent the past 2 days trying to make it work but I couldn't. My problem is that the test returns 400 even when the user does exist.

This is my getUser function

func (handler *UserHandler) getUser(w http.ResponseWriter, ID int) {
    logfile, err := os.OpenFile("events.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("Error opening file: %v", err)
    }
    defer logfile.Close()
    log.SetOutput(logfile)

    user := db.Fetch(ID)

    userJSON, err := json.Marshal(user)
    if err != nil {
        log.Printf("Error while marshaling the user into JSON: %v", err)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)

    // userJSON is sent as http Response
    w.Write(userJSON)
}

This is my UserHandler

type UserHandler struct{}

func (handle *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    var head string
    head, r.URL.Path = ShiftPath(r.URL.Path)
    id, err := strconv.Atoi(head)
    if err != nil {
        http.Error(w, fmt.Sprintf("Invalid user ID %q", head), http.StatusBadRequest)
        return
    }
    switch r.Method {
    case "GET":
        handle.getUser(w, id)
    default:
        http.Error(w, "Only GET is allowed", http.StatusMethodNotAllowed)
    }
}

func ShiftPath(p string) (head, tail string) {
    p = path.Clean("/" + p)
    i := strings.Index(p[1:], "/") + 1
    if i <= 0 {
        return p[1:], "/"
    }
    return p[1:i], p[i:]
}

And this is my test

func TestGetUser(t *testing.T) {
    handler := new(UserHandler)
    mux := http.NewServeMux()
    mux.HandleFunc("/user/", handler.ServeHTTP)

    writer := httptest.NewRecorder()
    request, _ := http.NewRequest("GET", "/user/12", nil)
    mux.ServeHTTP(writer, request)

    if writer.Code != 200 {
        t.Errorf("Response code is %v", writer.Code)
    }
}
  • 写回答

1条回答 默认 最新

  • duanjuan1103 2019-02-16 07:59
    关注

    Issue with code ====> id, err := strconv.Atoi(head) Due to error you see a return and hence you see 400 error.

    Have your server code fully functional with valid logic.

    Suggestion: Always print or debug line by line. You can find the issue and root cause.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向