Terminating or aborting an HTTP request

时光总嘲笑我的痴心妄想 提交于 2019-12-30 22:52:35

问题


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).


回答1:


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?



来源:https://stackoverflow.com/questions/31293314/terminating-or-aborting-an-http-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!