简体   繁体   中英

Checking for Empty Integer in Golang

I am designing an API where a user sends integer values and some operation is performed depending on the value sent. During the validation check that whether this value exists in the request, I have to equate it to 0 ie if intValue == 0 .

However, I also have to perform a different operation in case the value is 0. Is there any way I can check that the integer does not exist or is empty without equating to 0?

Note: The requirements are set by the client and I cannot change them.

When decoding JSON data into a struct, you can differentiate optional fields by declaring them as a pointer type.

For example:

type requestFormat struct {
    AlwaysPresent int
    OptionalValue *int
}

Now when the value is decoded, you can check if the value was supplied at all:

var data requestFormat

err := json.NewDecoder(request.Body).Decode(&data)
if err != nil { ... }

if data.OptionalValue == nil {
    // OptionalValue was not defined in the JSON data
} else {
    // OptionalValue was defined, but it still may have been 0
    val := *data.OptionalValue
}

in production as @phuclv say

there's no such thing as an "empty integer"

inelegant implementation

check if it is required:

like

@Hymns For Disco use json.NewDecoder or validators

but it is being abandoned : Why required and optional is removed in Protocol Buffers 3

another way:

use map but struct,which can tell if a field exists

follow is a example

package main

import (
    "encoding/json"
    "io/ioutil"
    "net/http"
)

type Test struct {
    Name string
    Age  int
}

func testJson(w http.ResponseWriter, r *http.Request) {
    aMap := make(map[string]interface{})
    data, _ := ioutil.ReadAll(r.Body)
    json.Unmarshal(data, &aMap)
    test := Test{}
    json.Unmarshal(data, &test)
}
func main() {
    http.HandleFunc("/", testJson)    
    http.ListenAndServe(":8080", nil)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM