-1

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 i.e. 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.

MRA1412
  • 57
  • 8

3 Answers3

1

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
}
Hymns For Disco
  • 7,530
  • 2
  • 17
  • 33
0

If considering compatibility, my suggestion is to use json.Number. This way, both int and string can be passed by the requesting side, and it can also determine whether the requesting side has passed the parameter.

For example:

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Param struct {
    Level json.Number `json:"level"`
}

func main() {
    var p Param

    if err := json.Unmarshal([]byte(`{"level": 30}`), &p); err != nil {
        log.Fatalf("Unmarshal err: %v", err)
    }

    if p.Level == "" {
        log.Fatal("level not pass")
    }

    level, err := p.Level.Int64()
    if err != nil {
        log.Fatalf("level is not integer")
    }

    fmt.Printf("level: %d", level)
}
-2

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

Para
  • 1,299
  • 4
  • 11