nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: elm-tooling/elm-language-server
Pull request #387 (2020-12-04 17:28:50)

Fix case of unused value constructor when used with pattern args


Patch:
diff --git a/src/providers/diagnostics/elmLsDiagnostics.ts b/src/providers/diagnostics/elmLsDiagnostics.ts
index 13f25ef..7d9a94e 100644
--- a/src/providers/diagnostics/elmLsDiagnostics.ts
+++ b/src/providers/diagnostics/elmLsDiagnostics.ts
@@ -972,7 +972,9 @@ export class ElmLsDiagnostics {
             (#eq? @type.reference "${unionVariant.text}")
           )
           ((case_of_branch
-            (pattern) @variant.reference)
+            (pattern
+              (union_pattern
+                (upper_case_qid) @variant.reference)))
             (#eq? @variant.reference "${unionVariant.text}")
           )
           `,


Test patch:
diff --git a/test/diagnosticTests/elmLsDiagnostics.test.ts b/test/diagnosticTests/elmLsDiagnostics.test.ts
index a34ca75..498e2d6 100644
--- a/test/diagnosticTests/elmLsDiagnostics.test.ts
+++ b/test/diagnosticTests/elmLsDiagnostics.test.ts
@@ -1613,5 +1613,28 @@ text en it language =
 
       await testDiagnostics(source, "unused_value_constructor", []);
     });
+
+    it("used in case expr with pattern", async () => {
+      const source = `
+module Bar exposing (text)
+
+type Language
+    = Italian (List String)
+    | English (List String)
+
+
+text : String -> String -> Html msg
+text en it language =
+    Html.text <|
+        case language of
+            English items ->
+                en
+
+            Italian items ->
+                it
+			`;
+
+      await testDiagnostics(source, "unused_value_constructor", []);
+    });
   });
 });
Repository: elm-tooling/elm-language-server
Pull request #564 (2021-03-24 22:55:27)

Reword remove all unused code action


Patch:
diff --git a/src/providers/codeActionLs/removeUnusedCodeAction.ts b/src/providers/codeActionLs/removeUnusedCodeAction.ts
index d8e001d..e4f27e6 100644
--- a/src/providers/codeActionLs/removeUnusedCodeAction.ts
+++ b/src/providers/codeActionLs/removeUnusedCodeAction.ts
@@ -39,7 +39,7 @@ CodeActionProvider.registerCodeAction({
   getFixAllCodeAction: (params) => {
     const importsMap = new Map<string, Set<string>>();
     return CodeActionProvider.getFixAllCodeAction(
-      "Remove all unused code",
+      "Remove all reported unused code",
       params,
       errorCodes,
       fixId,


Test patch:
diff --git a/test/codeActionTests/removeUnusedCodeAction.test.ts b/test/codeActionTests/removeUnusedCodeAction.test.ts
index cd49cc9..3b9d64d 100644
--- a/test/codeActionTests/removeUnusedCodeAction.test.ts
+++ b/test/codeActionTests/removeUnusedCodeAction.test.ts
@@ -104,7 +104,7 @@ func = ""
 
     await testCodeAction(
       source,
-      [{ title: "Remove all unused code" }],
+      [{ title: "Remove all reported unused code" }],
       expectedSource,
       true,
     );
@@ -132,7 +132,7 @@ func = foo
 
     await testCodeAction(
       source,
-      [{ title: "Remove all unused code" }],
+      [{ title: "Remove all reported unused code" }],
       expectedSource,
       true,
     );
@@ -160,7 +160,7 @@ func = foo
 
     await testCodeAction(
       source,
-      [{ title: "Remove all unused code" }],
+      [{ title: "Remove all reported unused code" }],
       expectedSource,
       true,
     );
@@ -188,7 +188,7 @@ func = foo
 
     await testCodeAction(
       source,
-      [{ title: "Remove all unused code" }],
+      [{ title: "Remove all reported unused code" }],
       expectedSource,
       true,
     );
@@ -216,7 +216,7 @@ func = foo + bar
 
     await testCodeAction(
       source,
-      [{ title: "Remove all unused code" }],
+      [{ title: "Remove all reported unused code" }],
       expectedSource,
       true,
     );
@@ -244,7 +244,7 @@ func = foo + bar
 
     await testCodeAction(
       source,
-      [{ title: "Remove all unused code" }],
+      [{ title: "Remove all reported unused code" }],
       expectedSource,
       true,
     );
@@ -272,7 +272,7 @@ func = foo + bar
 
     await testCodeAction(
       source,
-      [{ title: "Remove all unused code" }],
+      [{ title: "Remove all reported unused code" }],
       expectedSource,
       true,
     );
@@ -300,7 +300,7 @@ func = foo + bar
 
     await testCodeAction(
       source,
-      [{ title: "Remove all unused code" }],
+      [{ title: "Remove all reported unused code" }],
       expectedSource,
       true,
     );
Repository: elm-tooling/elm-language-server
Pull request #565 (2021-03-24 23:17:29)

Add testcase for unused type alias
Test case taken from https://github.com/elm-tooling/elm-language-server/issues/563

Fixes https://github.com/elm-tooling/elm-language-server/issues/563


Patch:
diff --git a/src/providers/diagnostics/elmLsDiagnostics.ts b/src/providers/diagnostics/elmLsDiagnostics.ts
index f7df28b..271fd26 100644
--- a/src/providers/diagnostics/elmLsDiagnostics.ts
+++ b/src/providers/diagnostics/elmLsDiagnostics.ts
@@ -970,6 +970,19 @@ export class ElmLsDiagnostics {
   private getUnusedTypeAliasDiagnostics(tree: Tree): IDiagnostic[] {
     const diagnostics: IDiagnostic[] = [];
 
+    // Currently if the file exports the variant, either through an explicit
+    // reference to the type, or through a '(..)' to expose everything, then
+    // we won't mark the value constructor as unused. Ideally this should take
+    // multiple files into account, then these conditions can be removed.
+    const exposingAll = !!tree.rootNode
+      .childForFieldName("moduleDeclaration")
+      ?.childForFieldName("exposing")
+      ?.childForFieldName("doubleDot");
+
+    if (exposingAll) {
+      return diagnostics;
+    }
+
     const typeAliases = this.typeAliasesQuery
       .matches(tree.rootNode)
       .map((match) => match.captures[0].node)


Test patch:
diff --git a/test/diagnosticTests/elmLsDiagnostics.test.ts b/test/diagnosticTests/elmLsDiagnostics.test.ts
index 0d07d4e..efece76 100644
--- a/test/diagnosticTests/elmLsDiagnostics.test.ts
+++ b/test/diagnosticTests/elmLsDiagnostics.test.ts
@@ -1511,6 +1511,49 @@ type Patch
       await testDiagnostics(source, "unused_type_alias", []);
     });
 
+    it("used type alias in different file", async () => {
+      const source = `
+--@ Model.elm
+module Model exposing (..)
+
+
+type alias IAmUsed =
+    { used : Bool
+    , optional : Bool
+    }
+
+--@ Main.elm
+module Main exposing (main)
+
+import Html
+import Model
+
+
+main : Html.Html msg
+main =
+    view example
+
+
+example : Model.IAmUsed
+example =
+    { used = True
+    , optional = False
+    }
+
+
+view : Model.IAmUsed -> Html.Html msg
+view blah =
+    Html.text <|
+        if blah.used then
+            "used"
+
+        else
+            "not used"
+			`;
+
+      await testDiagnostics(source, "unused_type_alias", []);
+    });
+
     it("unused type alias", async () => {
       const source = `
 module Foo exposing (foo)
Repository: colinhacks/zod
Pull request #4554 (2025-05-28 22:22:51)

Abort further processing when transform is skipped
Port of #4266 to the v4 codebase

Closes https://github.com/colinhacks/zod/issues/2243
Closes https://github.com/colinhacks/zod/issues/2192
Closes https://github.com/colinhacks/zod/issues/2113


Patch:
diff --git a/packages/zod/src/v3/types.ts b/packages/zod/src/v3/types.ts
index 2b3efe02..82d66375 100644
--- a/packages/zod/src/v3/types.ts
+++ b/packages/zod/src/v3/types.ts
@@ -4411,7 +4411,7 @@ export class ZodEffects<T extends ZodTypeAny, Output = output<T>, Input = input<
           parent: ctx,
         });
 
-        if (!isValid(base)) return base;
+        if (!isValid(base)) return INVALID;
 
         const result = effect.transform(base.value, checkCtx);
         if (result instanceof Promise) {
@@ -4423,7 +4423,7 @@ export class ZodEffects<T extends ZodTypeAny, Output = output<T>, Input = input<
         return { status: status.value, value: result };
       } else {
         return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
-          if (!isValid(base)) return base;
+          if (!isValid(base)) return INVALID;
 
           return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
             status: status.value,
diff --git a/play.ts b/play.ts
index 41eb006b..23bdd10a 100644
--- a/play.ts
+++ b/play.ts
@@ -1,3 +1,21 @@
-import { z } from "zod/v4";
+import { z } from "zod/v3";
 
-z;
+// import * as z from "zod";
+
+const parseResult = z
+  .string()
+  .refine((x) => false) // force anything/everything to fail
+  .transform((x) => {
+    console.log("I don't get called"); // correct
+    return x.length;
+  })
+  .refine((x) => {
+    console.log("I shouldn't get called!!!!!!");
+    console.log(typeof x); // number
+    console.log(x);
+  })
+  .safeParse("123");
+
+console.log(`succeeded:  ${parseResult.success}`); // false (correct behavior)
+
+// z.string().min(1234, { abort: true });


Test patch:
diff --git a/packages/zod/src/v3/tests/refine.test.ts b/packages/zod/src/v3/tests/refine.test.ts
index 8a7165cd..55c27fea 100644
--- a/packages/zod/src/v3/tests/refine.test.ts
+++ b/packages/zod/src/v3/tests/refine.test.ts
@@ -295,3 +295,19 @@ test("fatal superRefine", () => {
   expect(result.success).toEqual(false);
   if (!result.success) expect(result.error.issues.length).toEqual(1);
 });
+
+test("superRefine after skipped transform", () => {
+  const schema = z
+    .string()
+    .regex(/^\d+$/)
+    .transform((val) => Number(val))
+    .superRefine((val) => {
+      if (typeof val !== "number") {
+        throw new Error("Called without transform");
+      }
+    });
+
+  const result = schema.safeParse("");
+
+  expect(result.success).toEqual(false);
+});
Repository: colinhacks/zod
Pull request #4870 (2025-07-11 04:51:34)

Unwiden catch input type
Closes https://github.com/colinhacks/zod/issues/4851


Patch:
diff --git a/packages/zod/src/v4/core/schemas.ts b/packages/zod/src/v4/core/schemas.ts
index 91de6c30..d95afdeb 100644
--- a/packages/zod/src/v4/core/schemas.ts
+++ b/packages/zod/src/v4/core/schemas.ts
@@ -3315,11 +3315,8 @@ export interface $ZodCatchDef<T extends SomeType = $ZodType> extends $ZodTypeDef
 }
 
 export interface $ZodCatchInternals<T extends SomeType = $ZodType>
-  extends $ZodTypeInternals<core.output<T>, core.input<T> | util.Whatever> {
+  extends $ZodTypeInternals<core.output<T>, core.input<T>> {
   def: $ZodCatchDef<T>;
-  // qin: T["_zod"]["qin"];
-  // qout: T["_zod"]["qout"];
-
   optin: T["_zod"]["optin"];
   optout: T["_zod"]["optout"];
   isst: never;
diff --git a/play.ts b/play.ts
index 92940a52..a9bd3b86 100644
--- a/play.ts
+++ b/play.ts
@@ -1,3 +1,5 @@
 import { z } from "zod";
 
 z;
+
+z.string().catch("asdf");


Test patch:
diff --git a/packages/zod/src/v4/classic/tests/catch.test.ts b/packages/zod/src/v4/classic/tests/catch.test.ts
index d8ad85a6..db93ede8 100644
--- a/packages/zod/src/v4/classic/tests/catch.test.ts
+++ b/packages/zod/src/v4/classic/tests/catch.test.ts
@@ -1,6 +1,5 @@
 import { expect, expectTypeOf, test } from "vitest";
 import { z } from "zod/v4";
-import type { util } from "zod/v4/core";
 
 test("basic catch", () => {
   expect(z.string().catch("default").parse(undefined)).toBe("default");
@@ -45,7 +44,7 @@ test("catch with transform", () => {
   expect(stringWithDefault.unwrap().out).toBeInstanceOf(z.ZodTransform);
 
   type inp = z.input<typeof stringWithDefault>;
-  expectTypeOf<inp>().toEqualTypeOf<string | util.Whatever>();
+  expectTypeOf<inp>().toEqualTypeOf<string>();
   type out = z.output<typeof stringWithDefault>;
   expectTypeOf<out>().toEqualTypeOf<string>();
 });
@@ -59,7 +58,7 @@ test("catch on existing optional", () => {
   expect(stringWithDefault.unwrap().unwrap()).toBeInstanceOf(z.ZodString);
 
   type inp = z.input<typeof stringWithDefault>;
-  expectTypeOf<inp>().toEqualTypeOf<string | undefined | util.Whatever>();
+  expectTypeOf<inp>().toEqualTypeOf<string | undefined>();
   type out = z.output<typeof stringWithDefault>;
   expectTypeOf<out>().toEqualTypeOf<string | undefined>();
 });
@@ -68,7 +67,7 @@ test("optional on catch", () => {
   const stringWithDefault = z.string().catch("asdf").optional();
 
   type inp = z.input<typeof stringWithDefault>;
-  expectTypeOf<inp>().toEqualTypeOf<string | util.Whatever>();
+  expectTypeOf<inp>().toEqualTypeOf<string | undefined>();
   type out = z.output<typeof stringWithDefault>;
   expectTypeOf<out>().toEqualTypeOf<string | undefined>();
 });
@@ -102,7 +101,7 @@ test("nested", () => {
     inner: "asdf",
   });
   type input = z.input<typeof outer>;
-  expectTypeOf<input>().toEqualTypeOf<{ inner: string | util.Whatever } | util.Whatever>();
+  expectTypeOf<input>().toEqualTypeOf<{ inner: string }>();
   type out = z.output<typeof outer>;
 
   expectTypeOf<out>().toEqualTypeOf<{ inner: string }>();
Repository: zeromicro/go-zero
Pull request #1586 (2022-02-28 01:58:29)

build: update goctl dependency ddl-parser to v1.0.3
Resolves: #1576


Patch:
diff --git a/core/logx/logs.go b/core/logx/logs.go
index 34bb1112..81ee4e3e 100644
--- a/core/logx/logs.go
+++ b/core/logx/logs.go
@@ -33,7 +33,7 @@ const (
 )
 
 const (
-	jsonEncodingType = iota
+	jsonEncodingType uint32 = iota
 	plainEncodingType
 
 	jsonEncoding     = "json"
@@ -137,9 +137,9 @@ func SetUp(c LogConf) error {
 	}
 	switch c.Encoding {
 	case plainEncoding:
-		encoding = plainEncodingType
+		setEncoding(plainEncodingType)
 	default:
-		encoding = jsonEncodingType
+		setEncoding(jsonEncodingType)
 	}
 
 	switch c.Mode {
@@ -666,3 +666,7 @@ func (lw logWriter) Write(data []byte) (int, error) {
 	lw.logger.Print(string(data))
 	return len(data), nil
 }
+
+func setEncoding(encodingType uint32) {
+	atomic.StoreUint32(&encoding, encodingType)
+}
diff --git a/tools/goctl/go.mod b/tools/goctl/go.mod
index 5e4ffd7f..9adc3c44 100644
--- a/tools/goctl/go.mod
+++ b/tools/goctl/go.mod
@@ -12,6 +12,6 @@ require (
 	github.com/stretchr/testify v1.7.0
 	github.com/urfave/cli v1.22.5
 	github.com/zeromicro/antlr v0.0.1
-	github.com/zeromicro/ddl-parser v1.0.2
+	github.com/zeromicro/ddl-parser v1.0.3
 	github.com/zeromicro/go-zero v1.3.0
 )


Test patch:
diff --git a/core/collection/fifo_test.go b/core/collection/fifo_test.go
index 3e58afef..6f1acfdf 100644
--- a/core/collection/fifo_test.go
+++ b/core/collection/fifo_test.go
@@ -61,3 +61,41 @@ func TestPutMore(t *testing.T) {
 		assert.Equal(t, string(element), string(body.([]byte)))
 	}
 }
+
+func TestPutMoreWithHeaderNotZero(t *testing.T) {
+	elements := [][]byte{
+		[]byte("hello"),
+		[]byte("world"),
+		[]byte("again"),
+	}
+	queue := NewQueue(4)
+	for i := range elements {
+		queue.Put(elements[i])
+	}
+
+	// take 1
+	body, ok := queue.Take()
+	assert.True(t, ok)
+	element, ok := body.([]byte)
+	assert.True(t, ok)
+	assert.Equal(t, element, []byte("hello"))
+
+	// put more
+	queue.Put([]byte("b4"))
+	queue.Put([]byte("b5")) // will store in elements[0]
+	queue.Put([]byte("b6")) // cause expansion
+
+	results := [][]byte{
+		[]byte("world"),
+		[]byte("again"),
+		[]byte("b4"),
+		[]byte("b5"),
+		[]byte("b6"),
+	}
+
+	for _, element := range results {
+		body, ok := queue.Take()
+		assert.True(t, ok)
+		assert.Equal(t, string(element), string(body.([]byte)))
+	}
+}
diff --git a/core/logx/tracelogger_test.go b/core/logx/tracelogger_test.go
index 7da8d0dd..1427e736 100644
--- a/core/logx/tracelogger_test.go
+++ b/core/logx/tracelogger_test.go
@@ -84,9 +84,9 @@ func TestTraceInfo(t *testing.T) {
 
 func TestTraceInfoConsole(t *testing.T) {
 	old := encoding
-	encoding = plainEncodingType
+	setEncoding(jsonEncodingType)
 	defer func() {
-		encoding = old
+		setEncoding(old)
 	}()
 
 	var buf mockWriter
Repository: zeromicro/go-zero
Pull request #1616 (2022-03-05 13:29:08)

fix: Fix issue #1614


Patch:
diff --git a/tools/goctl/util/pathx/file.go b/tools/goctl/util/pathx/file.go
index 4fe25283..5858ec51 100644
--- a/tools/goctl/util/pathx/file.go
+++ b/tools/goctl/util/pathx/file.go
@@ -75,12 +75,23 @@ func FileNameWithoutExt(file string) string {
 
 // GetGoctlHome returns the path value of the goctl, the default path is ~/.goctl, if the path has
 // been set by calling the RegisterGoctlHome method, the user-defined path refers to.
-func GetGoctlHome() (string, error) {
+func GetGoctlHome() (home string, err error) {
+	defer func() {
+		if err != nil {
+			return
+		}
+		info, err := os.Stat(home)
+		if err == nil && !info.IsDir() {
+			os.Rename(home, home+".old")
+			MkdirIfNotExist(home)
+		}
+	}()
 	if len(goctlHome) != 0 {
-		return goctlHome, nil
+		home = goctlHome
+		return
 	}
-
-	return GetDefaultGoctlHome()
+	home, err = GetDefaultGoctlHome()
+	return
 }
 
 // GetDefaultGoctlHome returns the path value of the goctl home where Join $HOME with .goctl.


Test patch:
diff --git a/tools/goctl/util/pathx/file_test.go b/tools/goctl/util/pathx/file_test.go
index 7aa81642..00690a17 100644
--- a/tools/goctl/util/pathx/file_test.go
+++ b/tools/goctl/util/pathx/file_test.go
@@ -74,3 +74,35 @@ func TestGetGitHome(t *testing.T) {
 	expected := filepath.Join(homeDir, goctlDir, gitDir)
 	assert.Equal(t, expected, actual)
 }
+
+func TestGetGoctlHome(t *testing.T) {
+	t.Run("goctl_is_file", func(t *testing.T) {
+		tmpFile := filepath.Join(t.TempDir(), "a.tmp")
+		backupTempFile := tmpFile + ".old"
+		err := ioutil.WriteFile(tmpFile, nil, 0666)
+		if err != nil {
+			return
+		}
+		RegisterGoctlHome(tmpFile)
+		home, err := GetGoctlHome()
+		if err != nil {
+			return
+		}
+		info, err := os.Stat(home)
+		assert.Nil(t, err)
+		assert.True(t, info.IsDir())
+
+		_, err = os.Stat(backupTempFile)
+		assert.Nil(t, err)
+	})
+
+	t.Run("goctl_is_dir", func(t *testing.T) {
+		RegisterGoctlHome("")
+		dir := t.TempDir()
+		RegisterGoctlHome(dir)
+		home, err := GetGoctlHome()
+		assert.Nil(t, err)
+		assert.Equal(t, dir, home)
+	})
+
+}
Repository: zeromicro/go-zero
Pull request #1620 (2022-03-07 04:26:44)

fix(goctl): dart gen user defined struct array
`user-defined-struct` array in api file, such as `[]Bars` below
``` golang
	type Foo {
		Bars  []Bar   `json:"bars"`
	}
```
dart_gen should return `List<Bar>`


Patch:
diff --git a/tools/goctl/api/dartgen/gendata.go b/tools/goctl/api/dartgen/gendata.go
index 49c5f0a6..90d97ab2 100644
--- a/tools/goctl/api/dartgen/gendata.go
+++ b/tools/goctl/api/dartgen/gendata.go
@@ -43,7 +43,9 @@ class {{.Name}} {
 	{{end}}}{{end}});
 	factory {{.Name}}.fromJson(Map<String,dynamic> m) {
 		return {{.Name}}({{range .Members}}
-			{{lowCamelCase .Name}}: {{if isDirectType .Type.Name}}m['{{getPropertyFromMember .}}']{{else if isClassListType .Type.Name}}(m['{{getPropertyFromMember .}}'] as List<dynamic>).map((i) => {{getCoreType .Type.Name}}.fromJson(i)){{else}}{{.Type.Name}}.fromJson(m['{{getPropertyFromMember .}}']){{end}},{{end}}
+			{{lowCamelCase .Name}}: {{if isDirectType .Type.Name}}m['{{getPropertyFromMember .}}']
+			{{else if isClassListType .Type.Name}}(m['{{getPropertyFromMember .}}'] as List<dynamic>).map((i) => {{getCoreType .Type.Name}}.fromJson(i)).toList()
+			{{else}}{{.Type.Name}}.fromJson(m['{{getPropertyFromMember .}}']){{end}},{{end}}
 		);
 	}
 	Map<String,dynamic> toJson() {
diff --git a/tools/goctl/api/dartgen/util.go b/tools/goctl/api/dartgen/util.go
index 0cccf36d..b6a52f15 100644
--- a/tools/goctl/api/dartgen/util.go
+++ b/tools/goctl/api/dartgen/util.go
@@ -128,11 +128,10 @@ func specTypeToDart(tp spec.Type) (string, error) {
 		}
 
 		s := getBaseType(valueType)
-		if len(s) == 0 {
-			return s, errors.New("unsupported primitive type " + tp.Name())
+		if len(s) != 0 {
+			return s, nil
 		}
-
-		return s, nil
+		return fmt.Sprintf("List<%s>", valueType), nil
 	case spec.InterfaceType:
 		return "Object", nil
 	case spec.PointerType:


Test patch:
diff --git a/tools/goctl/api/dartgen/util_test.go b/tools/goctl/api/dartgen/util_test.go
index 68a221fd..437b1960 100644
--- a/tools/goctl/api/dartgen/util_test.go
+++ b/tools/goctl/api/dartgen/util_test.go
@@ -37,3 +37,35 @@ func Test_getPropertyFromMember(t *testing.T) {
 		})
 	}
 }
+
+func Test_specTypeToDart(t *testing.T) {
+	tests := []struct {
+		name     string
+		specType spec.Type
+		want     string
+		wantErr  bool
+	}{
+		{
+			name:     "[]string should return List<String>",
+			specType: spec.ArrayType{RawName: "[]string", Value: spec.PrimitiveType{RawName: "string"}},
+			want:     "List<String>",
+		},
+		{
+			name:     "[]Foo should return List<Foo>",
+			specType: spec.ArrayType{RawName: "[]Foo", Value: spec.DefineStruct{RawName: "Foo"}},
+			want:     "List<Foo>",
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := specTypeToDart(tt.specType)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("specTypeToDart() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if got != tt.want {
+				t.Errorf("specTypeToDart() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
Repository: zeromicro/go-zero
Pull request #1640 (2022-03-13 06:32:34)

feat: add httpc/Get httpc/Post


Patch:
diff --git a/rest/httpc/requests.go b/rest/httpc/requests.go
index 05460745..a01aaaf4 100644
--- a/rest/httpc/requests.go
+++ b/rest/httpc/requests.go
@@ -1,6 +1,7 @@
 package httpc
 
 import (
+	"io"
 	"net/http"
 
 	"github.com/zeromicro/go-zero/core/breaker"
@@ -36,6 +37,26 @@ func Do(key string, r *http.Request, opts ...Option) (resp *http.Response, err e
 	return
 }
 
+// Get sends an HTTP GET request to the service assocated with the given key.
+func Get(key, url string, opts ...Option) (*http.Response, error) {
+	r, err := http.NewRequest(http.MethodGet, url, nil)
+	if err != nil {
+		return nil, err
+	}
+
+	return Do(key, r, opts...)
+}
+
+// Post sends an HTTP POST request to the service assocated with the given key.
+func Post(key, url, contentType string, body io.Reader, opts ...Option) (*http.Response, error) {
+	r, err := http.NewRequest(http.MethodPost, url, body)
+	if err != nil {
+		return nil, err
+	}
+
+	return Do(key, r, opts...)
+}
+
 func doRequest(key string, r *http.Request, opts ...Option) (resp *http.Response, err error) {
 	brk := breaker.GetBreaker(key)
 	err = brk.DoWithAcceptable(func() error {


Test patch:
diff --git a/rest/httpc/requests_test.go b/rest/httpc/requests_test.go
index 151dac62..0062c492 100644
--- a/rest/httpc/requests_test.go
+++ b/rest/httpc/requests_test.go
@@ -11,9 +11,9 @@ import (
 func TestDo(t *testing.T) {
 	svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 	}))
-	req, err := http.NewRequest(http.MethodGet, svr.URL, nil)
-	assert.Nil(t, err)
-	resp, err := Do("foo", req, func(cli *http.Client) {
+	_, err := Get("foo", "tcp://bad request")
+	assert.NotNil(t, err)
+	resp, err := Get("foo", svr.URL, func(cli *http.Client) {
 		cli.Transport = http.DefaultTransport
 	})
 	assert.Nil(t, err)
@@ -22,9 +22,9 @@ func TestDo(t *testing.T) {
 
 func TestDoNotFound(t *testing.T) {
 	svr := httptest.NewServer(http.NotFoundHandler())
-	req, err := http.NewRequest(http.MethodGet, svr.URL, nil)
-	assert.Nil(t, err)
-	resp, err := Do("foo", req)
+	_, err := Post("foo", "tcp://bad request", "application/json", nil)
+	assert.NotNil(t, err)
+	resp, err := Post("foo", svr.URL, "application/json", nil)
 	assert.Nil(t, err)
 	assert.Equal(t, http.StatusNotFound, resp.StatusCode)
 }