Skip to content

net/url: add JoinPath, URL.JoinPath #47005

@wanglong001

Description

@wanglong001

Url Join is often used

Unsatisfactory using path.Join: http://www -> http:/www

I want to add Join method to url package

// Join  concatenates baseUrl and the elements
// - check baseUrl format
// - concatenates baseUrl and the elements
func Join(baseUrl string, elem ...string) (result string, err error) {
	url, err := Parse(baseUrl)
	if err != nil {
		return
	}
	if len(elem) > 0 {
		elem = append([]string{url.Path}, elem...)
		url.Path = path.Join(elem...)
	}
	result = url.String()
	return
}

unit test

func TestJoin(t *testing.T) {
	type args struct {
		baseUrl string
		elem    []string
	}
	tests := []struct {
		name       string
		args       args
		wantResult string
		wantErr    bool
	}{
		{
			name: "test normal url",
			args: args{
				baseUrl: "https://go.googlesource.com",
				elem:    []string{"go"},
			},
			wantResult: "https://go.googlesource.com/go",
			wantErr:    false,
		},
		{
			name: "test .. parent url",
			args: args{
				baseUrl: "https://go.googlesource.com/a/b/c",
				elem:    []string{"../../../go"},
			},
			wantResult: "https://go.googlesource.com/go",
			wantErr:    false,
		},
		{
			name: "test . cul path",
			args: args{
				baseUrl: "https://go.googlesource.com/",
				elem:    []string{"./go"},
			},
			wantResult: "https://go.googlesource.com/go",
			wantErr:    false,
		},
		{
			name: "test multiple Separator",
			args: args{
				baseUrl: "https://go.googlesource.com//",
				elem:    []string{"/go"},
			},
			wantResult: "https://go.googlesource.com/go",
			wantErr:    false,
		},
		{
			name: "test more elems",
			args: args{
				baseUrl: "https://go.googlesource.com//",
				elem:    []string{"/go", "a", "b", "c"},
			},
			wantResult: "https://go.googlesource.com/go/a/b/c",
			wantErr:    false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			gotResult, err := Join(tt.args.baseUrl, tt.args.elem...)
			if (err != nil) != tt.wantErr {
				t.Errorf("Join() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if gotResult != tt.wantResult {
				t.Errorf("Join() = %v, want %v", gotResult, tt.wantResult)
			}
		})
	}
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions