diff --git a/defaultcookiename.go b/defaultcookiename.go index 5f13003..e30c5fc 100644 --- a/defaultcookiename.go +++ b/defaultcookiename.go @@ -11,18 +11,22 @@ import ( var DefaultCookieName string func init() { - DefaultCookieName = "jaws" - if s, err := os.Executable(); err == nil { - s = filepath.Base(s) - s = strings.TrimSuffix(s, filepath.Ext(s)) - var b []byte - for _, ch := range s { - if ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') { - b = append(b, byte(ch)) - } - } - if len(b) > 0 { - DefaultCookieName = s + exename, _ := os.Executable() + DefaultCookieName = makeCookieName(exename) +} + +func makeCookieName(exename string) (cookie string) { + cookie = "jaws" + exename = filepath.Base(exename) + exename = strings.TrimSuffix(exename, filepath.Ext(exename)) + var b []byte + for _, ch := range exename { + if ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') { + b = append(b, byte(ch)) } } + if len(b) > 0 { + cookie = string(b) + } + return } diff --git a/defaultcookiename_test.go b/defaultcookiename_test.go new file mode 100644 index 0000000..584be92 --- /dev/null +++ b/defaultcookiename_test.go @@ -0,0 +1,27 @@ +package jaws + +import ( + "path" + "testing" +) + +func Test_makeCookieName(t *testing.T) { + tests := []struct { + name string + exename string + wantCookie string + }{ + {"empty string", "", "jaws"}, + {"Simple", "Simple", "Simple"}, + {"suffix.ed", "suffix.ed", "suffix"}, + {"path", path.Join("c:", "path", "file.ext"), "file"}, + {"invalid chars", " !??_", "jaws"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if gotCookie := makeCookieName(tt.exename); gotCookie != tt.wantCookie { + t.Errorf("makeCookieName() = %v, want %v", gotCookie, tt.wantCookie) + } + }) + } +}