Go quickstart
In about 10 minutes you create a Go program that logs in to an M-Files vault, lists its 10 most
recently modified documents and logs out. The program uses the M-Files gRPC client module
github.com/M-Files/mfiles-grpc-go, which builds on the official google.golang.org/grpc and
google.golang.org/protobuf modules.
Prerequisites
- Go 1.26 or later:
google.golang.org/grpcv1.85.0 requires it. - A vault you can reach over gRPC:
- M-Files Cloud: the vault's host name; the endpoint is
<vault host>:443with TLS. - On-premises: the server's host name and gRPC port,
7766by default; plain HTTP/2 unless the administrator has enabled TLS.
- M-Files Cloud: the vault's host name; the endpoint is
- A way to log in: single sign-on through M-Files Login Service, or an M-Files user name and
password. With a password you also need the vault's GUID, for example
{7BBEA0BC-40D8-4BCB-A67D-8A3ACFBDB575}; Find the vault by its name lists the vaults you can log in to.
Cloud and on-premises and Connecting to the server explain the endpoints in detail.
Create the module
mkdir mfiles-quickstart
cd mfiles-quickstart
go mod init example.com/mfiles-quickstart
go get github.com/M-Files/mfiles-grpc-go@latest
The module github.com/M-Files/mfiles-grpc-go
has two packages:
mfiles: the code generated from the M-Files protos, all services, messages and enums in one package (mfiles.NewIRPCSearchClient,mfiles.SearchObjectsRequest). It is large: the first build takes a while, later builds come from the cache.mfilesclient: what the protos cannot express: the connection, login, call metadata and errors (mfilesclient.Connect,mfilesclient.Error), and builders for common values.
Versions. There is one module version per M-Files release: v0.2611.0 has the API of
M-Files 26.11, and v0.2611.1 is a revision of it; 27.1 is v0.2701.0. A version works with its
release and later ones; with an older server, the methods that the server does not have fail
with Unimplemented. To get the version of a release, name it:
go get github.com/M-Files/mfiles-grpc-go@v0.2611. The module is a preview (major version 0):
its helpers can still change between releases.
Write the program
Save this as main.go:
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/M-Files/mfiles-grpc-go/mfiles"
"github.com/M-Files/mfiles-grpc-go/mfilesclient"
)
// main runs the quickstart and exits non-zero if it fails.
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
// run logs in, lists the 10 most recently modified documents and logs out.
func run() error {
// The whole run has one minute.
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
// Connect and log in with the settings in the MFILES_* environment variables.
cfg, err := mfilesclient.ConfigFromEnv()
if err != nil {
return err
}
cfg.ClientName = "M-Files gRPC quickstart"
client, err := mfilesclient.Connect(ctx, cfg)
if err != nil {
return err
}
defer client.Close() // logs out and closes the channel
// Documents (object type 0) that are not deleted, sorted by "Last modified" (property 21),
// newest first. The server sorts before it applies the limit.
search := mfiles.NewIRPCSearchClient(client.Conn)
response, err := search.SearchObjects(ctx, &mfiles.SearchObjectsRequest{
Conditions: mfilesclient.AllOf(mfilesclient.IsObjectType(0), mfilesclient.IsNotDeleted()),
Sorting: mfilesclient.SortBy(21, true),
Limit: 10,
})
if err != nil {
return err
}
// One line per document: title, ID, version and modification time.
for _, item := range response.GetResults() {
object := item.GetObject()
version := object.GetVersionInfo()
fmt.Printf("%s (ID %d, version %d, modified %s UTC)\n",
version.GetTitle(),
object.GetObjectInfo().GetObjId().GetItemId().GetInternalId(),
version.GetVersion().GetInternalVersion(),
version.GetLastModifiedAtUtc().AsTime().Format(time.DateTime))
}
return nil
}
Full source: mfiles-grpc-go/examples/quickstart/main.go
Configure
The helper reads its settings from environment variables:
| Variable | Value |
|---|---|
MFILES_ADDRESS |
host:port, for example contoso.cloudvault.m-files.com:443 or mfserver:7766 |
MFILES_TLS |
true (default), or false for a server without TLS |
MFILES_CA_CERT |
Optional: a PEM file of root certificates to trust, for a server whose certificate comes from a private CA |
MFILES_VAULT |
The vault GUID, with braces |
MFILES_AUTH |
browser for single sign-on in the browser; then MFILES_VAULT is optional |
MFILES_REMEMBER_SIGN_IN |
Optional, with MFILES_AUTH=browser: true keeps the sign-in in Windows Credential Manager |
MFILES_USERNAME, MFILES_PASSWORD |
An M-Files user account (M-Files authentication) |
MFILES_TOKEN |
Instead of a password, for single sign-on: an access token from the vault's identity provider |
MFILES_AUTH_PLUGIN, MFILES_AUTH_SCOPE |
Optional, with MFILES_TOKEN: the authentication plugin and its configuration scope. Without them the helper asks the vault and uses its plugin, if the vault has one or one marked as the default |
M-Files Cloud with single sign-on (PowerShell):
$env:MFILES_ADDRESS = 'contoso.cloudvault.m-files.com:443'
$env:MFILES_AUTH = 'browser'
On-premises without TLS, with a user name and password (bash):
export MFILES_ADDRESS=mfserver:7766 MFILES_TLS=false
export MFILES_VAULT='{7BBEA0BC-40D8-4BCB-A67D-8A3ACFBDB575}'
export MFILES_USERNAME=alice
read -rs MFILES_PASSWORD && export MFILES_PASSWORD
Use MFILES_TLS=false only for a server that has no certificate, such as a lab installation.
Single sign-on. A vault that signs users in through M-Files Login Service, as is typical on
M-Files Cloud, refuses a password login with "Authentication failed.". With
MFILES_AUTH=browser the helper signs you in through the browser, as M-Files' own clients do,
and logs in with the token (see
M-Files Login Service). The vault comes
from the sign-in configuration, so MFILES_VAULT is not needed. With
MFILES_REMEMBER_SIGN_IN=true, the next run signs in without the browser (Windows only). A
token that you get elsewhere goes into MFILES_TOKEN.
Run
go run .
The output lists the documents, newest first. In the M-Files Sample Vault it starts like this:
Project Plan (template) (ID 445, version 1, modified 2012-06-07 12:01:57 UTC)
Project Tasks - CRM Development (ID 444, version 1, modified 2012-06-07 11:54:29 UTC)
Corporate Presentation (ID 443, version 1, modified 2012-06-07 11:40:14 UTC)
...
The code
mfilesclient.Connectcreates the channel and logs in.client.Closelogs out and closes the channel.cfg.ClientNameis your application's name. The server shows it in its list of sessions, so that administrators can tell your program's sessions apart; any name that identifies the program works. Without it the helper uses the program's file name.- Every service has a generated client, created on the channel:
mfiles.NewIRPCSearchClient(client.Conn). - The search has one array of conditions; all conditions in an array must match. Without the "not deleted" condition, users who may see deleted objects get them too.
Limit: 10with a sort order returns the first 10 of all matches in that order.- A failed call returns an
*mfilesclient.Errorthat names the M-Files error code.
IsObjectType and IsNotDeleted are small builders from the helper. They show the message
shapes of the two conditions:
// StatusCondition compares a status value of the object, such as its object type or whether
// it is deleted.
// - status: the status value, such as STATUS_TYPE_OBJECT_TYPE.
// - condition: the comparison, such as CONDITION_TYPE_EQUAL.
// - value: the value to compare with.
func StatusCondition(status mfiles.StatusType, condition mfiles.ConditionType,
value *mfiles.TypedValue) *mfiles.SearchCondition {
return &mfiles.SearchCondition{
Expression: &mfiles.Expression{
Type: mfiles.ExpressionType_EXPRESSION_TYPE_STATUS_VALUE,
Data: &mfiles.ExpressionUnion{Data: &mfiles.ExpressionUnion_StatusValue{
StatusValue: &mfiles.ExpressionUnion_StatusValueData{Type: status},
}},
},
Type: condition,
Value: value,
}
}
// PropertyCondition compares a property value of the object, such as its class (property 100)
// or "Last modified" (property 21).
// - propertyDef: the property definition ID.
// - condition: the comparison, such as CONDITION_TYPE_EQUAL.
// - value: the value to compare with.
func PropertyCondition(propertyDef int32, condition mfiles.ConditionType,
value *mfiles.TypedValue) *mfiles.SearchCondition {
return &mfiles.SearchCondition{
Expression: &mfiles.Expression{
Type: mfiles.ExpressionType_EXPRESSION_TYPE_PROPERTY_VALUE,
Data: &mfiles.ExpressionUnion{Data: &mfiles.ExpressionUnion_PropertyValue{
PropertyValue: &mfiles.ExpressionUnion_PropertyValueData{PropertyDef: propertyDef},
}},
},
Type: condition,
Value: value,
}
}
// IsObjectType matches objects of one object type. Value list -11 lists the object types.
// - objectType: the object type's ID, such as 0 for documents.
func IsObjectType(objectType int32) *mfiles.SearchCondition {
return StatusCondition(mfiles.StatusType_STATUS_TYPE_OBJECT_TYPE,
mfiles.ConditionType_CONDITION_TYPE_EQUAL, Lookup(-11, objectType))
}
// IsNotDeleted matches objects that are not deleted.
func IsNotDeleted() *mfiles.SearchCondition {
return StatusCondition(mfiles.StatusType_STATUS_TYPE_IS_DELETED,
mfiles.ConditionType_CONDITION_TYPE_EQUAL, Boolean(false))
}
Full source: mfiles-grpc-go/mfilesclient/search.go
Go and the generated code
- Enum values carry their type's name:
DATATYPE_TEXTof the enumDatatypeismfiles.Datatype_DATATYPE_TEXT. - Each member of a
oneofis a wrapper type. A text value is&mfiles.TypedValueUnion{Data: &mfiles.TypedValueUnion_Text{Text: "..."}}. Read one with a type switch onGetData(). - Use the getters (
GetObject(),GetVersionInfo(), ...) to read responses: they return zero values instead of panicking when a message field is unset.
The helper has constructors for the common values:
// Text is a single-line text value.
// - value: the text.
func Text(value string) *mfiles.TypedValue {
return &mfiles.TypedValue{
Type: mfiles.Datatype_DATATYPE_TEXT,
Data: &mfiles.TypedValueUnion{Data: &mfiles.TypedValueUnion_Text{Text: value}},
}
}
// Integer is an integer value.
// - value: the number.
func Integer(value int32) *mfiles.TypedValue {
return &mfiles.TypedValue{
Type: mfiles.Datatype_DATATYPE_INTEGER,
Data: &mfiles.TypedValueUnion{Data: &mfiles.TypedValueUnion_Integer{Integer: value}},
}
}
// Boolean is a yes/no value.
// - value: true for yes.
func Boolean(value bool) *mfiles.TypedValue {
return &mfiles.TypedValue{
Type: mfiles.Datatype_DATATYPE_BOOLEAN,
Data: &mfiles.TypedValueUnion{Data: &mfiles.TypedValueUnion_Boolean{Boolean: value}},
}
}
// Timestamp is a date and time value, such as "Last modified" (property 21).
// - value: the date and time, in any time zone.
func Timestamp(value time.Time) *mfiles.TypedValue {
return &mfiles.TypedValue{
Type: mfiles.Datatype_DATATYPE_TIMESTAMP,
Data: &mfiles.TypedValueUnion{Data: &mfiles.TypedValueUnion_Timestamp{
Timestamp: timestamppb.New(value),
}},
}
}
// Lookup is a single-select lookup value: the item with the given ID in a value list (or an
// object of the object type with that ID).
// - valueList: the value list's ID, or the object type's ID.
// - item: the item's ID.
func Lookup(valueList, item int32) *mfiles.TypedValue {
return &mfiles.TypedValue{
Type: mfiles.Datatype_DATATYPE_LOOKUP,
Data: &mfiles.TypedValueUnion{Data: &mfiles.TypedValueUnion_Lookup{
Lookup: lookupItem(valueList, item),
}},
}
}
// MultiSelectLookup is a multi-select lookup value.
// - valueList: the value list's ID, or the object type's ID.
// - items: the items' IDs.
func MultiSelectLookup(valueList int32, items ...int32) *mfiles.TypedValue {
lookups := make([]*mfiles.Lookup, 0, len(items))
for _, item := range items {
lookups = append(lookups, lookupItem(valueList, item))
}
return &mfiles.TypedValue{
Type: mfiles.Datatype_DATATYPE_MULTI_SELECT_LOOKUP,
Data: &mfiles.TypedValueUnion{Data: &mfiles.TypedValueUnion_MultiSelectLookup{
MultiSelectLookup: &mfiles.MultiSelectLookup{Values: lookups},
}},
}
}
// lookupItem refers to the latest version of an item in a value list.
// - valueList: the value list's ID, or the object type's ID.
// - item: the item's ID.
func lookupItem(valueList, item int32) *mfiles.Lookup {
return &mfiles.Lookup{
ValueListItemInfo: &mfiles.ItemInfo{ObjId: ObjID(valueList, item)},
Version: &mfiles.ObjVerVersion{
Type: mfiles.ObjVerVersionType_OBJ_VER_VERSION_TYPE_LATEST,
InternalVersion: -1,
},
}
}
Full source: mfiles-grpc-go/mfilesclient/values.go
What the helper does
gRPC alone is not enough to talk to M-Files: part of the contract travels in call metadata, and
errors arrive in trailers. mfilesclient takes care of that.
The channel. TLS with the system's root certificates plus an optional PEM file, or no TLS at all, and the message size limits that M-Files' own client uses: responses of any size instead of gRPC's default 4 MiB, requests up to 48 MiB (the server's default limit). Two interceptors handle every call:
// Dial creates the channel to cfg.Address. It does not log in and does not contact the server
// yet: the first call does.
// - cfg: the server's address and TLS settings; the login settings are not used yet.
func Dial(cfg Config) (*Client, error) {
// TLS or plaintext, as the configuration says.
transport, err := transportCredentials(cfg)
if err != nil {
return nil, err
}
// The channel, with M-Files' message size limits and the client's interceptors.
client := &Client{host: cfg.host()}
client.Conn, err = grpc.NewClient(cfg.Address,
grpc.WithTransportCredentials(transport),
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(MaxReceiveMessageSize),
grpc.MaxCallSendMsgSize(MaxSendMessageSize)),
// Every call carries the M-Files metadata; failed calls return *Error.
grpc.WithChainUnaryInterceptor(client.unaryInterceptor),
grpc.WithChainStreamInterceptor(client.streamInterceptor))
if err != nil {
return nil, err
}
return client, nil
}
// transportCredentials is TLS with the system's root certificates, plus cfg.CACertFile when set;
// or no TLS at all when cfg.TLS is false.
// - cfg: TLS and CACertFile select the credentials.
func transportCredentials(cfg Config) (credentials.TransportCredentials, error) {
// A server without TLS (lab use) takes plaintext connections.
if !cfg.TLS {
return insecure.NewCredentials(), nil
}
// Trust the system's root certificates (none if the system pool cannot be read) and the
// ones in cfg.CACertFile; require TLS 1.2 or later.
roots, err := x509.SystemCertPool()
if err != nil {
roots = x509.NewCertPool()
}
if cfg.CACertFile != "" {
pem, err := os.ReadFile(cfg.CACertFile)
if err != nil {
return nil, err
}
if !roots.AppendCertsFromPEM(pem) {
return nil, fmt.Errorf("%s: no PEM certificates found", cfg.CACertFile)
}
}
return credentials.NewTLS(&tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}), nil
}
Full source: mfiles-grpc-go/mfilesclient/client.go
Call metadata. Every call carries mfiles-is-remote-call: true and a new random 16-byte
mfiles-activity-id-bin; after login also the session ID in mfiles-session-id-bin. In Go the
value of a -bin key is the raw bytes in a string; gRPC base64-encodes it on the wire. M-Files
Cloud sets the cookie mfilesmsm to keep a client on one server instance; gRPC does not keep
cookies, so the interceptor stores set-cookie values and sends them back in a cookie header
(see Call metadata):
// withMetadata adds the M-Files call metadata to an outgoing call: the remote-call flag, a new
// activity ID, the session ID once logged in, and the cookies the server has set.
// - ctx: the call's context.
func (c *Client) withMetadata(ctx context.Context) context.Context {
// Every call is a remote call and has an activity ID of its own.
activityID := make([]byte, 16)
_, _ = rand.Read(activityID)
pairs := []string{headerRemoteCall, "true", headerActivityID, string(activityID)}
// The session and the cookies, once there are any.
if session := c.sessionID(); len(session) > 0 {
pairs = append(pairs, headerSessionID, string(session))
}
if cookies := c.cookieHeader(); cookies != "" {
pairs = append(pairs, headerCookie, cookies)
}
return metadata.AppendToOutgoingContext(ctx, pairs...)
}
// unaryInterceptor adds the metadata to every unary call, keeps the cookies and the metadata
// version the server returns, and turns a failure into *Error.
// - ctx: the call's context.
// - method: the full name of the called method.
// - req, reply: the request message and the response message to fill.
// - cc: the channel.
// - invoker: makes the call.
// - opts: the call's options; the interceptor adds the ones that capture the metadata.
func (c *Client) unaryInterceptor(ctx context.Context, method string, req, reply any,
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
var header, trailer metadata.MD
opts = append(opts, grpc.Header(&header), grpc.Trailer(&trailer))
err := invoker(c.withMetadata(ctx), method, req, reply, cc, opts...)
c.readResponseMetadata(header, trailer)
return decodeError(err, trailer)
}
Full source: mfiles-grpc-go/mfilesclient/metadata.go
Login. LogIn binds the session to the vault in
login_data.vault_guid. Its response's session_data.session_id (48 bytes) goes into
mfiles-session-id-bin from then on:
// LogInWith logs in to a vault. From then on every call carries the session. It returns the
// session.
// - ctx: cancels the call.
// - vault: the vault GUID, with braces.
// - auth: the authentication data, e.g. from PasswordAuth or TokenAuth.
// - clientName: shown in the server's session list; "" for the program's name.
func (c *Client) LogInWith(ctx context.Context, vault string, auth *mfiles.AuthDataClient,
clientName string) (*mfiles.SessionData, error) {
// Without a client name, the program's file name.
if clientName == "" {
clientName = filepath.Base(os.Args[0])
}
// Log in as a server API client.
response, err := mfiles.NewIRPCLoginClient(c.Conn).LogIn(ctx, &mfiles.LogInRequest{
EnvironmentData: &mfiles.EnvironmentData{ClientName: clientName, HostPlatform: "Go"},
ClientData: &mfiles.ClientData{
Type: mfiles.ClientType_CLIENT_TYPE_SERVER_API,
Language: "en",
// A plugin (token) login uses the 32-byte form of the attempt identifier.
Capabilities: &mfiles.ClientCapabilities{LongAuthenticationAttemptIdentifier: true},
},
LoginData: &mfiles.LoginData{ServerHostname: c.host, VaultGuid: vault},
AuthenticationData: auth,
})
if err != nil {
return nil, err
}
// A completed login returns a session ID.
session := response.GetSessionData()
if len(session.GetSessionId()) == 0 {
// A plugin that needs more than one round trip answers without a session.
return nil, errors.New("LogIn returned no session: multi-step authentication is not supported")
}
// From now on the interceptor sends session_id in mfiles-session-id-bin on every call.
c.mu.Lock()
c.session = session
c.mu.Unlock()
return session, nil
}
Full source: mfiles-grpc-go/mfilesclient/client.go
With a user name and password, authentication_data is:
// PasswordAuth is the authentication data of an M-Files user name and password.
// - username, password: the credentials of an M-Files user account.
func PasswordAuth(username, password string) *mfiles.AuthDataClient {
return &mfiles.AuthDataClient{
Type: mfiles.AuthDataType_AUTH_DATA_TYPE_CREDENTIALS,
Data: &mfiles.AuthDataClientUnion{Data: &mfiles.AuthDataClientUnion_Credentials{
Credentials: &mfiles.Credentials{
Type: mfiles.CredentialsType_CREDENTIALS_TYPE_MFILES,
Username: username,
Password: password,
},
}},
}
}
Full source: mfiles-grpc-go/mfilesclient/client.go
Errors. A failed call returns *mfilesclient.Error, decoded from the
mfiles-error-serialized-bin and mfiles-error-text-bin trailers: the gRPC status (Status),
the message, the M-Files error code of the top-level error (HResult, such as 0x8004000B
"Not found."; the last entry of the error stack that is not the generic 0x80040001), every
code of the stack (Codes) and Has(code). It keeps the gRPC status, so status.Code(err)
still works:
// Error is a failed M-Files call. Test for it with errors.As; status.Code(err) still gives the
// gRPC status code.
type Error struct {
Status *status.Status // the gRPC status: Unknown for M-Files errors
HResult uint32 // the M-Files error code, e.g. 0x8004000B; 0 when unknown
Codes []uint32 // the codes of the error stack, the original error first
Message string // the error message (the gRPC status message)
Details string // the long error message with the server's error stack
Stack []*mfiles.RPCErrorInfo // the server's error stack, the original error first
}
// Error is the message with the gRPC status code and, when known, the M-Files error code.
func (e *Error) Error() string {
if len(e.Codes) == 0 {
return fmt.Sprintf("gRPC error %s: %s", e.Status.Code(), e.Message)
}
return fmt.Sprintf("M-Files error 0x%08X (%s): %s", e.HResult, e.Status.Code(), e.Message)
}
// SignedHResult is the error code as a signed 32-bit integer, e.g. -2147221493.
func (e *Error) SignedHResult() int32 { return int32(e.HResult) }
// GRPCStatus lets status.Code and status.FromError see through the *Error.
func (e *Error) GRPCStatus() *status.Status { return e.Status }
// Has reports whether code is anywhere in the error stack.
// - code: an M-Files error code, such as CodeNotFound.
func (e *Error) Has(code uint32) bool {
for _, c := range e.Codes {
if c == code {
return true
}
}
return false
}
// AsError returns the *Error in err's chain, if there is one.
// - err: any error, such as one a call through the Client returned.
func AsError(err error) (*Error, bool) {
var mfilesErr *Error
ok := errors.As(err, &mfilesErr)
return mfilesErr, ok
}
// decodeError turns a failed call into *Error, using the error trailers when present.
// - err: the error the call returned, or nil.
// - trailer: the call's trailers; nil or empty when there are none.
func decodeError(err error, trailer metadata.MD) error {
// Only a gRPC status other than OK becomes *Error; other errors pass through unchanged.
if err == nil {
return nil
}
st, ok := status.FromError(err)
if !ok || st.Code() == codes.OK {
return err
}
// The status message, and from the trailers the long message and the error stack.
result := &Error{Status: st, Message: st.Message()}
if values := trailer.Get(headerErrorText); len(values) > 0 {
result.Details = values[0]
}
if values := trailer.Get(headerErrorStack); len(values) > 0 {
stack := &mfiles.RPCErrorInfoArray{}
if proto.Unmarshal([]byte(values[0]), stack) == nil {
result.Stack = stack.GetValue()
}
}
// The codes of the stack, and the code of the error the message describes.
for _, info := range result.Stack {
result.Codes = append(result.Codes, uint32(info.GetErrorCode()))
}
result.HResult = errorCode(result.Codes)
return result
}
// errorPassThrough is the generic code of an error that is only passed up the stack; it does
// not say what went wrong.
const errorPassThrough = 0x80040001
// errorCode is the code of the top-level error, the last entry of the stack: the error the
// status message describes, such as 0x800407E4 for "Access denied." Entries with the generic
// code 0x80040001 are skipped, unless all are; an empty stack gives 0.
// - stack: the codes of the error stack, the original error first.
func errorCode(stack []uint32) uint32 {
for i := len(stack) - 1; i >= 0; i-- {
if stack[i] != errorPassThrough {
return stack[i]
}
}
if len(stack) > 0 {
return stack[len(stack)-1]
}
return 0
}
Full source: mfiles-grpc-go/mfilesclient/errors.go
Handle it like this:
_, err := objects.GetObjectInfoAndProperties(ctx, request)
if mfilesErr, ok := mfilesclient.AsError(err); ok && mfilesErr.Has(mfilesclient.CodeNotFound) {
fmt.Printf("0x%08X: %s\n", mfilesErr.HResult, mfilesErr.Message)
}
Errors lists the common codes and what to do about each.
The metadata structure version. Calls that report the vault's metadata structure version return it in
the mfiles-metadata-version-bin trailer; client.MetadataStructureVersion() has the latest one. See
Metadata structure version and caching.
Troubleshooting
| Symptom | Cause |
|---|---|
Unavailable, "tls: first record does not look like a TLS handshake" |
TLS against a server without TLS: set MFILES_TLS=false, only for a lab server on a trusted network. |
Unimplemented, "unexpected HTTP status code received from server: 404" |
A call without TLS to a TLS endpoint, such as M-Files Cloud: remove MFILES_TLS=false. |
Unimplemented for one method, other calls work |
The server is older than the module and does not have the method. |
Unavailable, "connection error" ... "Error while dialing" |
Wrong host or port, or a firewall in between. |
| "M-Files error 0x8004001A (Unknown): Authentication failed." | Wrong user name or password, or the vault uses single sign-on (see the configuration step). |
| "M-Files error 0x80040020 (Unknown): The specified document vault does not exist." | Wrong MFILES_VAULT. |
| "gRPC error Unauthenticated: The current session with M-Files Server is no longer valid." | No session or an expired one: log in again. |
The connect recipe (see the next steps) calls QueryVersion before it logs in, so it tells
connection problems from login problems.
Next steps
- The module's repository, M-Files/mfiles-grpc-go,
has one runnable program per task. Clone it and run one with
go run ./examples/recipes/<name>, withconnect,vault_structure,search,read_object,download_file,create_document,update_properties,workflow_state,paging,errorsorlogin_service. ItsREADME.mdlists their arguments. - The recipes explained: Connect, Vault structure, Search, Read an object, Download a file, Create a document, Update properties, Change the workflow state, Page through results and Handle errors.
- Learn the model: Vault and metadata structure, Objects and versions, Properties and values and Search.
- Keep a session healthy in a long-running program: Authentication and sessions.
- Find any method in the reference, starting with SearchObjects and GetObjectInfoAndProperties.
Generate the code yourself
The module is the easiest way to the client code. To generate it yourself, for example into a
package path of your own, use the proto files of the
gRPC API bundle, protoc and its Go plugins:
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.36.12
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.6.2
protoc -I proto --go_out=. --go-grpc_out=. \
--go_opt=module=github.com/M-Files/mfiles-grpc-go \
--go-grpc_opt=module=github.com/M-Files/mfiles-grpc-go \
proto/mfiles/*.proto proto/mfiles/api/*.proto
The bundle's go_package option puts all services, messages and enums into one package,
github.com/M-Files/mfiles-grpc-go/mfiles, which this writes into mfiles/. For another import
path, change the go_package option of the files. Python's grpcio-tools package includes a
protoc (python -m grpc_tools.protoc); the module repository's generate.ps1 and
generate.sh use it when protoc is not on PATH.
An M-Files Server installation also has the API definition, in
<installation folder>\Common\Web\GRPC\proto, as one combined legacy file without
documentation. It describes the same wire contract, but it does not produce the package path
that the module and the documentation use. Prefer the bundle.