ronantakizawa/codereview-bench huggingface dataset:
Repository: danielmiessler/fabric
File: restapi/auth.go (Go)

Code before:
package restapi

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

func ApiKeyMiddleware(apiKey string) gin.HandlerFunc {
	return func(c *gin.Context) {
		headerApiKey := c.GetHeader("X-API-Key")

		if headerApiKey != apiKey {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": fmt.Sprintf("Wrong or missing API Key")})
			return
		}

		c.Next()
	}
}


Review comment (security):
I suggest adding this snippet here:

```go
if headerAPIKey == "" {
       c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Missing API Key"})
            return
}
```

Code after:
package restapi

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

const APIKeyHeader = "X-API-Key"

func APIKeyMiddleware(apiKey string) gin.HandlerFunc {
	return func(c *gin.Context) {
		headerApiKey := c.GetHeader(APIKeyHeader)

		if headerApiKey == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Missing API Key"})
			return
		}

		if headerApiKey != apiKey {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Wrong API Key"})
			return
		}

		c.Next()
	}
}
Repository: danielmiessler/fabric
File: restapi/serve.go (Go)

Code before:
package restapi

import (
	"github.com/danielmiessler/fabric/core"
	"github.com/gin-gonic/gin"
)

func Serve(registry *core.PluginRegistry, address string, apiKey string) (err error) {
	r := gin.New()

	// Middleware
	r.Use(gin.Logger())
	r.Use(gin.Recovery())

	if apiKey != "" {
		r.Use(ApiKeyMiddleware(apiKey))
	}

	// Register routes
	fabricDb := registry.Db
	NewPatternsHandler(r, fabricDb.Patterns)
	NewContextsHandler(r, fabricDb.Contexts)
	NewSessionsHandler(r, fabricDb.Sessions)
	NewChatHandler(r, registry, fabricDb)
	NewConfigHandler(r, fabricDb)
	NewModelsHandler(r, registry.VendorManager)

	// Start server
	err = r.Run(address)
	if err != nil {
		return err
	}

	return
}


Review comment (security):
Maybe we should add a warning here if the API key is not set?

```go
if apiKey != "" {
        r.Use(APIKeyMiddleware(apiKey))
} else {
        log.Warn("Starting REST API server without API key authentication. This may pose security risks.")
}
```

Code after:
package restapi

import (
	"log/slog"

	"github.com/danielmiessler/fabric/core"
	"github.com/gin-gonic/gin"
)

func Serve(registry *core.PluginRegistry, address string, apiKey string) (err error) {
	r := gin.New()

	// Middleware
	r.Use(gin.Logger())
	r.Use(gin.Recovery())

	if apiKey != "" {
		r.Use(APIKeyMiddleware(apiKey))
	} else {
		slog.Warn("Starting REST API server without API key authentication. This may pose security risks.")
	}

	// Register routes
	fabricDb := registry.Db
	NewPatternsHandler(r, fabricDb.Patterns)
	NewContextsHandler(r, fabricDb.Contexts)
	NewSessionsHandler(r, fabricDb.Sessions)
	NewChatHandler(r, registry, fabricDb)
	NewConfigHandler(r, fabricDb)
	NewModelsHandler(r, registry.VendorManager)

	// Start server
	err = r.Run(address)
	if err != nil {
		return err
	}

	return
}
Repository: danielmiessler/fabric
File: plugins/plugin.go (Go)

Code before:
	err = o.IsValidErr()
	return
}

type Settings []*Setting

func (o Settings) IsConfigured() (ret bool) {
	ret = true
	for _, setting := range o {
		if ret = setting.IsValid(); !ret {
			break
		}
	}
	return
}

func (o Settings) Configure() (err error) {
	for _, setting := range o {
		if err = setting.Configure(); err != nil {
			break
		}
	}
	return
}

func (o Settings) FillEnvFileContent(buffer *bytes.Buffer) {
	for _, setting := range o {
		setting.FillEnvFileContent(buffer)
	}
	return
}

type SetupQuestions []*SetupQuestion

func (o SetupQuestions) Ask(label string) (err error) {
	fmt.Println()
	fmt.Printf("[%v]\n", label)
	for _, question := range o {
		if err = question.Ask(""); err != nil {
			break
		}
	}
	return
}

func BuildEnvVariablePrefix(name string) (ret string) {
	ret = BuildEnvVariable(name)
	if ret != "" {
		ret += "_"
	}
	return

Review comment (suggestion):
Could we consider saving the parsed value from here?

```go
func (o *SetupQuestion) OnAnswer(answer string) (err error) {
    if o.Type == SettingTypeBool {
        if answer == "" {
            o.Value = ""
        } else {
            parsed, err := ParseBool(answer)
            if err != nil {
                return fmt.Errorf("invalid boolean value %q: %w", answer, err)
            }
            // Store normalized boolean value
            o.Value = fmt.Sprintf("%t", parsed)
        }
    }
```

Code after:
		fmt.Printf("%v%v (true/false, leave empty for '%s' or type '%v' to remove the value):\n",
			prefix, o.Question, current, AnswerReset)
	} else if o.Value != "" {
		fmt.Printf("%v%v (leave empty for '%s' or type '%v' to remove the value):\n",
			prefix, o.Question, o.Value, AnswerReset)
	} else {
		fmt.Printf("%v%v (leave empty to skip):\n", prefix, o.Question)
	}
	var answer string
	fmt.Scanln(&answer)
	answer = strings.TrimRight(answer, "\n")
	if answer == "" {
		answer = o.Value
	} else if strings.ToLower(answer) == AnswerReset {
		answer = ""
	}
	err = o.OnAnswer(answer)
	return
}

func (o *SetupQuestion) OnAnswer(answer string) (err error) {
	if o.Type == SettingTypeBool {
		if answer == "" {
			o.Value = ""
		} else {
			_, err := ParseBool(answer)
			if err != nil {
				return fmt.Errorf("invalid boolean value: %v", answer)
			}
			o.Value = strings.ToLower(answer)
		}
	} else {
		o.Value = answer
	}
	if o.EnvVariable != "" {
		if err = os.Setenv(o.EnvVariable, o.Value); err != nil {
			return
		}
	}
	err = o.IsValidErr()
	return
}

func (o *Setting) IsValidErr() (err error) {
	if !o.IsValid() {
		err = fmt.Errorf("%v=%v, is not valid", o.EnvVariable, o.Value)
	}
	return
}

func (o *Setting) IsDefined() bool {
Repository: danielmiessler/fabric
File: internal/plugins/ai/anthropic/anthropic.go (Go)

Code before:
	mimeType = strings.TrimSpace(metaParts[0])
	if mimeType == "" {
		return "", "", false
	}
	hasBase64 := false
	for _, part := range metaParts[1:] {
		if strings.EqualFold(strings.TrimSpace(part), "base64") {
			hasBase64 = true
			break
		}
	}
	if !hasBase64 {
		return "", "", false
	}
	return mimeType, data, true
}

func normalizeImageMimeType(mimeType string) string {
	normalized := strings.ToLower(strings.TrimSpace(mimeType))
	switch normalized {
	case "image/jpg":
		normalized = "image/jpeg"
	}
	switch normalized {
	case "image/jpeg", "image/png", "image/gif", "image/webp":
		return normalized
	default:
		return ""
	}
}

func isPDFURL(url string) bool {
	parsedURL, err := neturl.Parse(url)
	if err != nil {
		return false
	}
	return strings.EqualFold(path.Ext(parsedURL.Path), ".pdf")
}

func (an *Client) NeedsRawMode(modelName string) bool {
	return false
}


Review comment (bug):
Good suggestion! Added a debug log message to help users understand when their data URL lacks base64 encoding. This follows the existing debug logging pattern in this file.

Code after:
	if !strings.HasPrefix(value, "data:") {
		return "", "", false
	}
	withoutPrefix := strings.TrimPrefix(value, "data:")
	parts := strings.SplitN(withoutPrefix, ",", 2)
	if len(parts) != 2 {
		return "", "", false
	}
	meta := strings.TrimSpace(parts[0])
	data = strings.TrimSpace(parts[1])
	if data == "" {
		return "", "", false
	}
	metaParts := strings.Split(meta, ";")
	mimeType = strings.TrimSpace(metaParts[0])
	if mimeType == "" {
		return "", "", false
	}
	hasBase64 := false
	for _, part := range metaParts[1:] {
		if strings.EqualFold(strings.TrimSpace(part), "base64") {
			hasBase64 = true
			break
		}
	}
	if !hasBase64 {
		debuglog.Debug(debuglog.Basic, "parseDataURL: data URL without base64 encoding is not supported")
		return "", "", false
	}
	return mimeType, data, true
}

// normalizeImageMimeType validates and normalizes image MIME types to those supported
// by the Anthropic API. Supported formats: image/jpeg, image/png, image/gif, image/webp.
// See: https://docs.anthropic.com/en/docs/build-with-claude/vision
func normalizeImageMimeType(mimeType string) string {
	switch strings.ToLower(strings.TrimSpace(mimeType)) {
	case "image/jpg", "image/jpeg":
		return "image/jpeg"
	case "image/png":
		return "image/png"
	case "image/gif":
		return "image/gif"
	case "image/webp":
		return "image/webp"
	default:
		return ""
	}
}

// isPDFURL checks if a URL appears to point to a PDF based on its path extension.
Repository: davidfowl/TodoApi
File: TodoApi/Program.cs (C#)

Code before:
builder.Services.AddIdentityCore<TodoUser>()
                .AddEntityFrameworkStores<TodoDbContext>();

// State that represents the current user from the database *and* the request
builder.Services.AddCurrentUser();

// Configure Open API
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.Configure<SwaggerGeneratorOptions>(o => o.InferSecuritySchemes = true);

// Configure rate limiting
builder.Services.AddRateLimiting();

// Configure OpenTelemetry
builder.AddOpenTelemetry();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// Ass Serilog requests logging
app.UseSerilogRequestLogging();

app.UseRateLimiter();

app.Map("/", () => Results.Redirect("/swagger"));

// Configure the APIs
app.MapTodos();
app.MapUsers();

// Configure the prometheus endpoint for scraping metrics
app.MapPrometheusScrapingEndpoint();
// NOTE: This should only be exposed on an internal port!
// .RequireHost("*:9100");

app.Run();


Review comment (suggestion):
```suggestion
// Add Serilog requests logging
```

Code after:
builder.Services.AddIdentityCore<TodoUser>()
                .AddEntityFrameworkStores<TodoDbContext>();

// State that represents the current user from the database *and* the request
builder.Services.AddCurrentUser();

// Configure Open API
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.Configure<SwaggerGeneratorOptions>(o => o.InferSecuritySchemes = true);

// Configure rate limiting
builder.Services.AddRateLimiting();

// Configure OpenTelemetry
builder.AddOpenTelemetry();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// Add Serilog requests logging
app.UseSerilogRequestLogging();

app.UseRateLimiter();

app.Map("/", () => Results.Redirect("/swagger"));

// Configure the APIs
app.MapTodos();
app.MapUsers();

// Configure the prometheus endpoint for scraping metrics
app.MapPrometheusScrapingEndpoint();
// NOTE: This should only be exposed on an internal port!
// .RequireHost("*:9100");

app.Run();
Repository: derailed/k9s
File: internal/model/yaml_test.go (Go)

Code before:
	uu := map[string]struct {
		q     string
		lines []string
		e     fuzzy.Matches
	}{
		"empty-lines": {
			q:     "foo",
			lines: []string{},
			e:     fuzzy.Matches{},
		},
		"no-match": {
			q:     "foo",
			lines: []string{"bar"},
			e:     fuzzy.Matches{},
		},
		"single-match": {
			q:     "foo",
			lines: []string{"foo", "bar", "baz"},
			e: fuzzy.Matches{
				{
					Str:            "foo",
					Index:          0,
					MatchedIndexes: []int{0, 3},
				},
			},
		},
		"multiple-matches": {
			q:     "foo",
			lines: []string{"foo", "bar", "foo bar foo", "baz"},
			e: fuzzy.Matches{
				{
					Str:            "foo",
					Index:          0,
					MatchedIndexes: []int{0, 3},
				},
				{
					Str:            "foo",
					Index:          2,
					MatchedIndexes: []int{0, 3},
				},
				{
					Str:            "foo",
					Index:          2,
					MatchedIndexes: []int{8, 11},
				},
			},
		},
	}

	for k := range uu {
		u := uu[k]

Review comment (suggestion):
Might be a good idea to add a use cases where the match is contained multiple time in the line and not necessarily space delimited ie "thefoobar fobarbarfofool barfoofo"...

Code after:
	uu := map[string]struct {
		q     string
		lines []string
		e     fuzzy.Matches
	}{
		"empty-lines": {
			q: "foo",
			e: fuzzy.Matches{},
		},
		"no-match": {
			q:     "foo",
			lines: []string{"bar"},
			e:     fuzzy.Matches{},
		},
		"single-match": {
			q:     "foo",
			lines: []string{"foo", "bar", "baz"},
			e: fuzzy.Matches{
				{
					Str:            "foo",
					Index:          0,
					MatchedIndexes: []int{0, 3},
				},
			},
		},
		"multiple-matches": {
			q:     "foo",
			lines: []string{"foo", "bar", "foo bar foo", "baz"},
			e: fuzzy.Matches{
				{
					Str:            "foo",
					Index:          0,
					MatchedIndexes: []int{0, 3},
				},
				{
					Str:            "foo",
					Index:          2,
					MatchedIndexes: []int{0, 3},
				},
				{
					Str:            "foo",
					Index:          2,
					MatchedIndexes: []int{8, 11},
				},
			},
		},
	}
	var y YAML
	for k := range uu {
		u := uu[k]
		t.Run(k, func(t *testing.T) {
Repository: derailed/k9s
File: internal/view/live_view_test.go (Go)

Code before:
	uu := map[string]struct {
		lines   []string
		matches fuzzy.Matches
		e       []string
	}{
		"empty-lines": {
			e: []string{},
		},
		"no-match": {
			lines: []string{"bar"},
			e:     []string{"bar"},
		},
		"single-match": {
			lines: []string{"foo", "bar", "baz"},
			matches: fuzzy.Matches{
				{Index: 1, MatchedIndexes: []int{0, 3}},
			},
			e: []string{"foo", `<<<"search_0">>>bar<<<"">>>`, "baz"},
		},
		"multiple-matches": {
			lines: []string{"foo", "bar", "baz"},
			matches: fuzzy.Matches{
				{Index: 1, MatchedIndexes: []int{0, 3}},
				{Index: 2, MatchedIndexes: []int{0, 3}},
			},
			e: []string{"foo", `<<<"search_0">>>bar<<<"">>>`, `<<<"search_1">>>baz<<<"">>>`},
		},
		"multiple-matches-same-line": {
			lines: []string{"foosfoo baz", "dfbarfoos bar"},
			matches: fuzzy.Matches{
				{Index: 0, MatchedIndexes: []int{0, 3}},
				{Index: 0, MatchedIndexes: []int{4, 7}},
				{Index: 1, MatchedIndexes: []int{5, 8}},
			},
			e: []string{`<<<"search_0">>>foo<<<"">>>s<<<"search_1">>>foo<<<"">>> baz`, `dfbar<<<"search_2">>>foo<<<"">>>s bar`},
		},
	}
	v := LiveView{}
	for k := range uu {
		u := uu[k]
		t.Run(k, func(t *testing.T) {
			t.Parallel()
			assert.Equal(t, u.e, v.linesWithRegions(u.lines, u.matches))
		})
	}
}


Review comment (refactor):
In the test you could use a formatter helpers ie matchTag(i int, s string) string. Easier to track should syntax changes or for new test cases.

Code after:
func matchTag(i int, s string) string {
	return `<<<"search_` + strconv.Itoa(i) + `">>>` + s + `<<<"">>>`
}

func TestLiveView_linesWithRegions(t *testing.T) {
	uu := map[string]struct {
		lines   []string
		matches fuzzy.Matches
		e       []string
	}{
		"empty-lines": {
			e: []string{},
		},
		"no-match": {
			lines: []string{"bar"},
			e:     []string{"bar"},
		},
		"single-match": {
			lines: []string{"foo", "bar", "baz"},
			matches: fuzzy.Matches{
				{Index: 1, MatchedIndexes: []int{0, 3}},
			},
			e: []string{"foo", matchTag(0, "bar"), "baz"},
		},
		"multiple-matches": {
			lines: []string{"foo", "bar", "baz"},
			matches: fuzzy.Matches{
				{Index: 1, MatchedIndexes: []int{0, 3}},
				{Index: 2, MatchedIndexes: []int{0, 3}},
			},
			e: []string{"foo", matchTag(0, "bar"), matchTag(1, "baz")},
		},
		"multiple-matches-same-line": {
			lines: []string{"foosfoo baz", "dfbarfoos bar"},
			matches: fuzzy.Matches{
				{Index: 0, MatchedIndexes: []int{0, 3}},
				{Index: 0, MatchedIndexes: []int{4, 7}},
				{Index: 1, MatchedIndexes: []int{5, 8}},
			},
			e: []string{
				matchTag(0, "foo") + "s" + matchTag(1, "foo") + " baz",
				"dfbar" + matchTag(2, "foo") + "s bar",
			},
		},
	}
	var v LiveView
	for k := range uu {
		u := uu[k]
		t.Run(k, func(t *testing.T) {
			t.Parallel()
			assert.Equal(t, u.e, v.linesWithRegions(u.lines, u.matches))
Repository: derailed/k9s
File: internal/config/plugin.go (Go)

Code before:

// NewPlugins returns a new plugin.
func NewPlugins() Plugins {
	return Plugins{
		Plugin: make(map[string]Plugin),
	}
}

// Load K9s plugins.
func (p Plugins) Load() error {
	return p.LoadPlugins(K9sPlugins, K9sPluginDir)
}

// LoadPlugins loads plugins from a given file.
func (p Plugins) LoadPlugins(path string, pluginDir string) error {
	f, err := os.ReadFile(path)
	var pp Plugins
	if err == nil {
		if err := yaml.Unmarshal(f, &pp); err != nil {
			return err
		}
	}

	pluginFiles, err := os.ReadDir(pluginDir)
	if err == nil {
		for _, pluginName := range pluginFiles {
			if pluginName.IsDir() {
				continue
			}
			pluginFile, err := os.ReadFile(filepath.Join(K9sPluginDir, pluginName.Name()))
			if err != nil {
				return err
			}
			var plugin Plugin
			if err = yaml.Unmarshal(pluginFile, &plugin); err != nil {
				return err
			}
			p.Plugin[strings.TrimSuffix(pluginName.Name(), filepath.Ext(pluginName.Name()))] = plugin
		}
	}

	for k, v := range pp.Plugin {
		p.Plugin[k] = v
	}

	return nil
}


Review comment (suggestion):
```suggestion
		for _, file := range pluginFiles {
```

Because you just read a directory and it can have multiple non-plugin files :)

Code after:
	return fmt.Sprintf("[%s] %s(%s)", p.ShortCut, p.Command, strings.Join(p.Args, " "))
}

// NewPlugins returns a new plugin.
func NewPlugins() Plugins {
	return Plugins{
		Plugin: make(map[string]Plugin),
	}
}

// Load K9s plugins.
func (p Plugins) Load() error {
	var pluginDirs []string
	for _, dataDir := range xdg.DataDirs {
		pluginDirs = append(pluginDirs, filepath.Join(dataDir, K9sPluginDirectory))
	}
	return p.LoadPlugins(K9sPluginsFilePath, pluginDirs)
}

// LoadPlugins loads plugins from a given file and a set of plugin directories.
func (p Plugins) LoadPlugins(path string, pluginDirs []string) error {
	f, err := os.ReadFile(path)
	if err != nil {
		return err
	}
	var pp Plugins
	if err := yaml.Unmarshal(f, &pp); err != nil {
		return err
	}

	for _, pluginDir := range pluginDirs {
		pluginFiles, err := os.ReadDir(pluginDir)
		if err != nil {
			log.Warn().Msgf("Failed reading plugin path %s; %s", pluginDir, err)
			continue
		}
		for _, file := range pluginFiles {
			if file.IsDir() || !isYamlFile(file) {
				continue
			}
			pluginFile, err := os.ReadFile(filepath.Join(pluginDir, file.Name()))
			if err != nil {
				return err
			}
			var plugin Plugin
			if err = yaml.Unmarshal(pluginFile, &plugin); err != nil {
				return err
			}
			p.Plugin[strings.TrimSuffix(file.Name(), filepath.Ext(file.Name()))] = plugin
		}
	}
Repository: derailed/k9s
File: internal/view/app.go (Go)

Code before:
	if err != nil {
		return false, err
	}
	_, err = dial.CoreV1().Namespaces().Get(ctx, ns, metav1.GetOptions{})
	if err != nil {
		log.Warn().Err(err).Msgf("Validation failed for namespace: %q", ns)
	}

	return true, nil
}

func (a *App) switchContext(name string) error {
	log.Debug().Msgf("--> Switching Context %q--%q", name, a.Config.ActiveView())
	a.Halt()
	defer a.Resume()
	{
		ns, err := a.Conn().Config().CurrentNamespaceName()
		if err != nil {
			log.Warn().Msg("No namespace specified in context. Using K9s config")
		}
		a.initFactory(ns)

		if e := a.command.Reset(true); e != nil {
			return e
		}
		v := a.Config.ActiveView()
		if v == "" || isContextCmd(v) {
			v = "pod"
			a.Config.SetActiveView(v)
		}
		a.Config.Reset()
		a.Config.K9s.CurrentContext = name
		cluster, err := a.Conn().Config().CurrentClusterName()
		if err != nil {
			return err
		}
		a.Config.K9s.CurrentCluster = cluster
		if err := a.Config.SetActiveNamespace(ns); err != nil {
			log.Error().Err(err).Msg("unable to set active ns")
		}
		if err := a.Config.Save(); err != nil {
			log.Error().Err(err).Msg("config save failed!")
		}

		a.Flash().Infof("Switching context to %s", name)
		a.ReloadStyles(name)
		a.gotoResource(a.Config.ActiveView(), "", true)
		a.clusterModel.Reset(a.factory)
	}

	return nil

Review comment (suggestion):
Actually we no longer need to track v here and we can set the active view using the config solely ie 
```go
if a.Config.ActiveView() == "" || ... {
   a.Config.SetActiveView("pod")
}
...
```

Code after:
	if err != nil {
		return false, err
	}
	_, err = dial.CoreV1().Namespaces().Get(ctx, ns, metav1.GetOptions{})
	if err != nil {
		log.Warn().Err(err).Msgf("Validation failed for namespace: %q", ns)
	}

	return true, nil
}

func (a *App) switchContext(name string) error {
	log.Debug().Msgf("--> Switching Context %q--%q", name, a.Config.ActiveView())
	a.Halt()
	defer a.Resume()
	{
		ns, err := a.Conn().Config().CurrentNamespaceName()
		if err != nil {
			log.Warn().Msg("No namespace specified in context. Using K9s config")
		}
		a.initFactory(ns)

		if e := a.command.Reset(true); e != nil {
			return e
		}
		if a.Config.ActiveView() == "" || isContextCmd(a.Config.ActiveView()) {
			a.Config.SetActiveView("pod")
		}
		a.Config.Reset()
		a.Config.K9s.CurrentContext = name
		cluster, err := a.Conn().Config().CurrentClusterName()
		if err != nil {
			return err
		}
		a.Config.K9s.CurrentCluster = cluster
		if err := a.Config.SetActiveNamespace(ns); err != nil {
			log.Error().Err(err).Msg("unable to set active ns")
		}
		if err := a.Config.Save(); err != nil {
			log.Error().Err(err).Msg("config save failed!")
		}

		a.Flash().Infof("Switching context to %s", name)
		a.ReloadStyles(name)
		a.gotoResource(a.Config.ActiveView(), "", true)
		a.clusterModel.Reset(a.factory)
	}

	return nil
}
Repository: derailed/k9s
File: internal/render/sc.go (Go)

Code before:
package render

import (
	"fmt"

	storagev1 "k8s.io/api/storage/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/kubectl/pkg/util/storage"

	"github.com/derailed/k9s/internal/client"
)

// StorageClass renders a K8s StorageClass to screen.
type StorageClass struct {
	Base
}

// Header returns a header row.
func (StorageClass) Header(ns string) Header {
	return Header{
		HeaderColumn{Name: "NAME"},
		HeaderColumn{Name: "PROVISIONER"},
		HeaderColumn{Name: "RECLAIMPOLICY"},
		HeaderColumn{Name: "VOLUMEBINDINGMODE"},
		HeaderColumn{Name: "ALLOWVOLUMEEXPANSION"},
		HeaderColumn{Name: "AGE", Time: true},
	}
}

// Render renders a K8s resource to screen.
func (s StorageClass) Render(o interface{}, ns string, r *Row) error {
	raw, ok := o.(*unstructured.Unstructured)
	if !ok {
		return fmt.Errorf("Expected StorageClass, but got %T", o)
	}
	var sc storagev1.StorageClass
	err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &sc)
	if err != nil {
		return err
	}

	r.ID = client.FQN(client.ClusterScope, sc.ObjectMeta.Name)
	r.Fields = Fields{
		s.nameWithDefault(sc.ObjectMeta),
		sc.Provisioner,

Review comment (suggestion):
labels and valid columns should remain in the header as they are standard cols across all resources.

Code after:
package render

import (
	"fmt"

	"github.com/derailed/k9s/internal/client"
	storagev1 "k8s.io/api/storage/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/kubectl/pkg/util/storage"
)

// StorageClass renders a K8s StorageClass to screen.
type StorageClass struct {
	Base
}

// Header returns a header row.
func (StorageClass) Header(ns string) Header {
	return Header{
		HeaderColumn{Name: "NAME"},
		HeaderColumn{Name: "PROVISIONER"},
		HeaderColumn{Name: "RECLAIMPOLICY"},
		HeaderColumn{Name: "VOLUMEBINDINGMODE"},
		HeaderColumn{Name: "ALLOWVOLUMEEXPANSION"},
		HeaderColumn{Name: "LABELS", Wide: true},
		HeaderColumn{Name: "VALID", Wide: true},
		HeaderColumn{Name: "AGE", Time: true},
	}
}

// Render renders a K8s resource to screen.
func (s StorageClass) Render(o interface{}, ns string, r *Row) error {
	raw, ok := o.(*unstructured.Unstructured)
	if !ok {
		return fmt.Errorf("Expected StorageClass, but got %T", o)
	}
	var sc storagev1.StorageClass
	err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &sc)
	if err != nil {
		return err
	}

	r.ID = client.FQN(client.ClusterScope, sc.ObjectMeta.Name)
	r.Fields = Fields{
		s.nameWithDefault(sc.ObjectMeta),