Completing or aborting an HTTP request

How to abort my API with some error message?

Link to my service call:

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 needs to send Json and some parameters.

I want to check if the parameters are received correctly if I do not want to send an error message.

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

I tried log.fataland os.Exit(1), they stop the service, not just the call request. panicinterrupts the call, but it does not allow me to send http.ResponseWriter, which is my error message.

I read something about panic, procrastination, recovery , but I really don't know how I can 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}  

, func, ().

+4
1

HTTP- - , ServeHTTP(), :

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

:

API , HTTP 200 OK. http.Error(), :

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

, JSON :

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

, , ""

ServeHTTP(), . , ServeHTTP(), , ServeHTTP() .

, , :

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
}

:

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

. : Golang, func func?

+6

All Articles