Skip to content

Commit 8aa25c8

Browse files
wangchaodeyuzhou王荣昌
andauthored
refactor(utils): The generic helper function asType[T any] replaces repetitive type assertion logic (#52)
Co-authored-by: 王荣昌 <[email protected]>
1 parent 04c98f0 commit 8aa25c8

File tree

1 file changed

+13
-24
lines changed

1 file changed

+13
-24
lines changed

mcp/utils.go

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -57,49 +57,38 @@ var _ ServerResult = &ListToolsResult{}
5757

5858
// Helper functions for type assertions
5959

60-
// AsTextContent attempts to cast the given interface to TextContent
61-
func AsTextContent(content interface{}) (*TextContent, bool) {
62-
tc, ok := content.(TextContent)
60+
// asType attempts to cast the given interface to the given type
61+
func asType[T any](content interface{}) (*T, bool) {
62+
tc, ok := content.(T)
6363
if !ok {
6464
return nil, false
6565
}
6666
return &tc, true
6767
}
6868

69+
// AsTextContent attempts to cast the given interface to TextContent
70+
func AsTextContent(content interface{}) (*TextContent, bool) {
71+
return asType[TextContent](content)
72+
}
73+
6974
// AsImageContent attempts to cast the given interface to ImageContent
7075
func AsImageContent(content interface{}) (*ImageContent, bool) {
71-
ic, ok := content.(ImageContent)
72-
if !ok {
73-
return nil, false
74-
}
75-
return &ic, true
76+
return asType[ImageContent](content)
7677
}
7778

7879
// AsEmbeddedResource attempts to cast the given interface to EmbeddedResource
7980
func AsEmbeddedResource(content interface{}) (*EmbeddedResource, bool) {
80-
er, ok := content.(EmbeddedResource)
81-
if !ok {
82-
return nil, false
83-
}
84-
return &er, true
81+
return asType[EmbeddedResource](content)
8582
}
8683

8784
// AsTextResourceContents attempts to cast the given interface to TextResourceContents
8885
func AsTextResourceContents(content interface{}) (*TextResourceContents, bool) {
89-
trc, ok := content.(TextResourceContents)
90-
if !ok {
91-
return nil, false
92-
}
93-
return &trc, true
86+
return asType[TextResourceContents](content)
9487
}
9588

9689
// AsBlobResourceContents attempts to cast the given interface to BlobResourceContents
9790
func AsBlobResourceContents(content interface{}) (*BlobResourceContents, bool) {
98-
brc, ok := content.(BlobResourceContents)
99-
if !ok {
100-
return nil, false
101-
}
102-
return &brc, true
91+
return asType[BlobResourceContents](content)
10392
}
10493

10594
// Helper function for JSON-RPC
@@ -603,4 +592,4 @@ func ParseReadResourceResult(rawMessage *json.RawMessage) (*ReadResourceResult,
603592
}
604593

605594
return &result, nil
606-
}
595+
}

0 commit comments

Comments
 (0)