Al desarrollar Go, los desarrolladores a menudo escriben sus propias variables o constantes y luego las reutilizan en código que accede a la biblioteca estándar. Por esta razón, nuestro desarrollador de Go, Sasha Melentyev, creó el linter usetdlibvars, que determina la capacidad de reutilizar variables o constantes de la biblioteca estándar. Entonces, en lugar de escribir sus propias constantes, puede reutilizar las constantes que ya están en la biblioteca estándar.
Por ejemplo, necesita hacer algún tipo de solicitud. En general, necesita usar un método, como getpost, en cuyo caso muchos desarrolladores escriben la palabra recibir directo. Alternativamente, puede tomar una constante de la biblioteca estándar y reutilizarla. Esto se vuelve aún más visible a medida que se nombra apropiadamente y se llama desde la biblioteca estándar. Entonces podemos decir que el linter ahorra tiempo dedicado a escribir código adicional.
Por ejemplo en cambio http.NewRequest("GET", "", nil)
tu puedes tener http.NewRequest(http.MethodGet, "", nil)
– la pelusa hará que se destaque.
El hecho de que la biblioteca estándar tenga muchas variables diferentes que se pueden reutilizar y que no siempre son necesarias también juega un papel importante. De forma predeterminada, nuestro linter solo contiene dos opciones (por ejemplo, verificar la biblioteca http interna) para que no haya falsas alarmas.
El nombre del linter, UseStdLibvars, es esencialmente una llamada a la acción. El linter ya está incluido en golangci-lint.
instalación
go install github.com/sashamelentyev/usestdlibvars@latest
propósito de uso
$ usestdlibvars -h
usestdlibvars: A linter that detect the possibility to use variables/constants from the Go standard library.
Usage: usestdlibvars [-flag] [package]
Flags:
-V print version and exit
-all
no effect (deprecated)
-c int
display offending line with this many lines of context (default -1)
-constant-kind
suggest the use of constant.Kind.String()
-cpuprofile string
write CPU profile to this file
-crypto-hash
suggest the use of crypto.Hash.String()
-debug string
debug flags, any subset of "fpstv"
-fix
apply all suggested fixes
-flags
print analyzer flags in JSON
-http-method
suggest the use of http.MethodXX (default true)
-http-status-code
suggest the use of http.StatusXX (default true)
-json
emit JSON output
-memprofile string
write memory profile to this file
-os-dev-null
suggest the use of os.DevNull
-rpc-default-path
suggest the use of rpc.DefaultXXPath
-source
no effect (deprecated)
-sql-isolation-level
suggest the use of sql.LevelXX.String()
-tags string
no effect (deprecated)
-test
indicates whether test files should be analyzed, too (default true)
-time-layout
suggest the use of time.Layout
-time-month
suggest the use of time.Month.String()
-time-weekday
suggest the use of time.Weekday.String()
-tls-signature-scheme
suggest the use of tls.SignatureScheme.String()
-trace string
write trace log to this file
-v no effect (deprecated)
ejemplos
package response
import (
"bytes"
"encoding/json"
"net/http"
)
// JSON marshals v to JSON, automatically escaping HTML,
// setting the Content-Type header as "application/json; charset=utf-8",
// sends an HTTP response header with the provided statusCode and
// writes the marshaled v as bytes to the connection as part of an HTTP reply.
func JSON(w http.ResponseWriter, statusCode int, v any) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(true)
if err := enc.Encode(v); err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
if _, err := w.Write(buf.Bytes()); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
usestdlibvars ./...
response.go:18:30: "500" can be replaced by http.StatusInternalServerError
response.go:24:30: "500" can be replaced by http.StatusInternalServerError
planes para el futuro
Planeamos monitorear qué hay de nuevo en el idioma. Si hay nuevas constantes que se pueden reutilizar en ciertos casos, agregaremos funcionalidad al linter. También puede participar y enviarnos solicitudes de incorporación de cambios.
Si desea obtener más información sobre el uso de soluciones de código abierto en su proyecto o necesita ayuda para desarrollar su proyecto desde cero, simplemente envíenos un mensaje utilizando el formulario a continuación. ¡Nos pondremos en contacto para discutir los detalles y ver cómo podemos trabajar con usted para desarrollar juntos su próximo gran proyecto!