Skip to content
This repository has been archived by the owner on Sep 16, 2022. It is now read-only.

Field tags

Francesc Campoy edited this page Jul 29, 2015 · 2 revisions

Go Endpoints has its own field tag endpoints which you can use to let your clients know what a service method data constraints are (on input):

  • req, means "required". Validation will fail if the value equals the zero value of the type.
  • d, default value, cannot be used together with req.
  • min and max constraints. Can be used only on int and uint (8/16/32/64 bits) and strings.
  • desc, a field description. Cannot contain a , (comma) for now.

Let's see an example:

type TaggedStruct struct {
    A int    `endpoints:"req,min=0,max=100,desc=An int field"`
    B int    `endpoints:"d=10,min=1,max=200"`
    C string `endpoints:"req,d=Hello gopher,desc=A string field"`
}
  • A field is required and has min & max constrains, is described as "An int field"
  • B field is not required, defaults to 10 and has min & max constrains
  • C field is required, defaults to "Hello gopher", is described as "A string field"

JSON tag and path templates

You can use JSON tags to shape your service method's response (the output).

Endpoints will honor Go's encoding/json marshaling rules, which means having this struct:

type TaggedStruct struct {
    A       int
    B       int    `json:"myB"`
    C       string `json:"c"`
    Skipped int    `json:"-"`
}

a service method path template could then look like:

some/path/{A}/other/{c}/{myB}

Notice, the names are case-sensitive.

Naturally, you can combine json and endpoints tags to use a struct for both input and output:

type TaggedStruct struct {
    A       int    `endpoints:"req,min=0,max=100,desc=An int field"`
    B       int    `json:"myB" endpoints:"d=10,min=1,max=200"`
    C       string `json:"c" endpoints:"req,d=Hello gopher,desc=A string field"`
    Skipped int    `json:"-"`
}

Long integers (int64, uint64)

As per Type and Format Summary:

a 64-bit integer cannot be represented in JSON (since JavaScript and JSON support integers up to 2^53). Therefore, a 64-bit integer must be represented as a string in JSON requests/responses

In this case, it is sufficient to append ,string to the json tag:

type Int64Struct struct {
  Id int64 `json:",string"`
}
Clone this wiki locally