github.com/jhump/golang-x-tools@v0.0.0-20220218190644-4958d6d39439/internal/lsp/command/util.go (about) 1 // Copyright 2021 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package command 6 7 import ( 8 "encoding/json" 9 "fmt" 10 ) 11 12 // ID returns the command name for use in the LSP. 13 func ID(name string) string { 14 return "gopls." + name 15 } 16 17 type Command string 18 19 func (c Command) ID() string { 20 return ID(string(c)) 21 } 22 23 // MarshalArgs encodes the given arguments to json.RawMessages. This function 24 // is used to construct arguments to a protocol.Command. 25 // 26 // Example usage: 27 // 28 // jsonArgs, err := MarshalArgs(1, "hello", true, StructuredArg{42, 12.6}) 29 // 30 func MarshalArgs(args ...interface{}) ([]json.RawMessage, error) { 31 var out []json.RawMessage 32 for _, arg := range args { 33 argJSON, err := json.Marshal(arg) 34 if err != nil { 35 return nil, err 36 } 37 out = append(out, argJSON) 38 } 39 return out, nil 40 } 41 42 // UnmarshalArgs decodes the given json.RawMessages to the variables provided 43 // by args. Each element of args should be a pointer. 44 // 45 // Example usage: 46 // 47 // var ( 48 // num int 49 // str string 50 // bul bool 51 // structured StructuredArg 52 // ) 53 // err := UnmarshalArgs(args, &num, &str, &bul, &structured) 54 // 55 func UnmarshalArgs(jsonArgs []json.RawMessage, args ...interface{}) error { 56 if len(args) != len(jsonArgs) { 57 return fmt.Errorf("DecodeArgs: expected %d input arguments, got %d JSON arguments", len(args), len(jsonArgs)) 58 } 59 for i, arg := range args { 60 if err := json.Unmarshal(jsonArgs[i], arg); err != nil { 61 return err 62 } 63 } 64 return nil 65 }