Golang:终止或中止HTTP请求 [英] Golang: terminating or aborting an HTTP request

查看:884
本文介绍了Golang:终止或中止HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



链接到我的服务电话:

  http://creative.test.spoti.io/api/getVastPlayer?add= 
{Json:Json}& host = api0.spoti.io& domain = domain& userAgent = userAgent& mobile = true

要打电话给我服务客户端需要发送一个Json和一些参数。



我想测试我得到的参数是否正确,如果不是我想发送错误消息。 / p>

响应应该是一个Json代码 {Result:Result,Error:error message}



我尝试过 log.fatal os.Exit(1) code>他们停止服务,而不仅仅是呼叫请求。 panic 中止呼叫,但是它阻止我发送一个 http.ResponseWriter 这是我的错误消息。



我读了一些关于恐慌,延迟,恢复的内容,但我真的不知道如何使用它们来解决这个问题。



返回作品:

 手机:= query.Get(mobile)
if mobile ==mobile{
str:=`{Resultt:,Error:No valide Var}`
fmt.Fprint(w,str)
fmt.Println(No successfulfull Operation !!)
return}

但是我可以在主函数中使用它,因为在其他函数中,它只会退出func而不是调用者函数(请求)。

解决方案

终止HTTP请求的提供只不过是从 ServeHTTP()方法,例如:

  http.HandleFunc(/,f unc(w http.ResponseWriter,r * http.Request){
//检查传入参数
if!ok {
str:=`{Result:,Error :no valide var}`
fmt.Fprint(w,str)
return
}

//正常的API服务
})

panic(http.ListenAndServe(:8080,nil))

注意:



如果您的API服务的输入参数无效,您应该考虑返回一个HTTP错误代码,而不是隐含的默认 200 OK 。为此,您可以使用 http.Error() 函数,例如:

  http.HandleFunc(/,func(w http.ResponseWriter ,r * http.Request){
//检查传入参数
if!ok {
http.Error(w,`Invalid input params!`,http.StatusBadRequest)
返回
}

//正常的API服务
})

对于更复杂的示例,您可以将JSON数据与错误代码一起发回:

  http.HandleFunc /,func(w http.ResponseWriter,r * http.Request){
//检查传入参数
if!ok {
w.Header()。Set(Content-类型,application / json)
w.WriteHeader(http.StatusBadRequest)
str:=`{Result:,Error:No valide Var}`
fmt.Fprint(w,str)
return
}

//执行普通API这个例子显示如何传播返回

>



如果在 ServeHTTP()之外检测到错误,例如在 ServeHTTP()中调用的函数中,您必须返回此错误状态,以便 ServeHTTP()可以返回。



我们假设您具有以下自定义类型,用于所需的参数和负责从请求中解码的功能:

 键入params struct {
//您的参数的字段
}

func decodeParams(r * http。请求)(*参数,错误){
p:= new(params)
//解码参数,如果它们无效,返回错误:

if!ok {
return nil,errors.New(Invalid params)
}

//如果一切顺利:
return p,nil
}

使用这些:

  http.HandleFunc(/,func(w http.ResponseWriter,r * http.Request){
p,err:= decodeParams(r)
如果err!= nil {
http.Error(w,`Invalid input params!`,http.StatusBadRequest)
返回
}

//正常的API服务
})

另请参阅相关问题:高隆,如何从另一个功能中返回func?


What's the way to abort my API serving with some error message?

Link to call my service:

http://creative.test.spoti.io/api/getVastPlayer?add=
    {"Json":Json}&host=api0.spoti.io&domain=domain&userAgent=userAgent&mobile=true

To call my service the client need to send a Json and some params.

I want to test if the params that I get are correct, if not I want send a error message.

The response should be a Json Code {"Result":"Result","Error":"error message"}

I tried log.fatal and os.Exit(1) they stop the service, not just the call request. panic aborts the call but it prevents me to send a http.ResponseWriter which is my error message.

I read something about panic, defer, recover but I don't really know how can I use them to solve this problem.

return works:

mobile :=query.Get("mobile")
if mobile=="mobile" {
            str:=`{"Resultt":"","Error":"No valide Var"}`
            fmt.Fprint(w, str)      
            fmt.Println("No successfull Operation!!")
            return}  

But I can use it just in the main function, because in the other functions it exits just the func not the caller function (request).

解决方案

Terminating the serving of an HTTP request is nothing more than to return from the ServeHTTP() method, e.g.:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // examine incoming params
    if !ok {
        str := `{"Result":"","Error":"No valide Var"}`
        fmt.Fprint(w, str)
        return
    }

    // Do normal API serving
})

panic(http.ListenAndServe(":8080", nil))

Notes:

If the input params of your API service are invalid, you should consider returning an HTTP error code instead of the implied default 200 OK. For this you can use the http.Error() function, for example:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // examine incoming params
    if !ok {
        http.Error(w, `Invalid input params!`, http.StatusBadRequest) 
        return
    }

    // Do normal API serving
})

For a more sophisticated example where you send back JSON data along with the error code:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // examine incoming params
    if !ok {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusBadRequest)
        str := `{"Result":"","Error":"No valide Var"}`
        fmt.Fprint(w, str)
        return
    }

    // Do normal API serving
})

Example showing how to propagate "returning"

If the error is detected outside of ServeHTTP(), e.g. in a function that is called from ServeHTTP(), you have to return this error state so that ServeHTTP() can return.

Let's assume you have the following custom type for your required parameters and a function which is responsible to decode them from a request:

type params struct {
    // fields for your params 
}

func decodeParams(r *http.Request) (*params, error) {
    p := new(params)
    // decode params, if they are invalid, return an error:

    if !ok {
        return nil, errors.New("Invalid params")
    }

    // If everything goes well:
    return p, nil
}

Using these:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    p, err := decodeParams(r)
    if err != nil {
        http.Error(w, `Invalid input params!`, http.StatusBadRequest)
        return
    }

    // Do normal API serving
})

Also see this related question: Golang, how to return in func FROM another func?

这篇关于Golang:终止或中止HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆