Web Development
This section will house resources related to web development in Go.
Server-Side
Struct Validation via validator - Validate structs using tags.
Example:
package main
import (
  "fmt"
  "github.com/go-playground/validator/v10"
)
type User struct {
  FirstName string `validate:"required"`
  LastName  string `validate:"required"`
  Age       int    `validate:"gte=0,lte=130"`
  Email     string `validate:"required,email"`
}
func main() {
  user := User{
      FirstName: "John",
      LastName:  "Doe",
      Age:       30,
      Email:     "doe@john.com",
  }
  validate := validator.New()
  err := validate.Struct(user)
  for _, err := range err.(validator.ValidationErrors) {
      fmt.Println("Errors: ", err)
  }
}
- Also supports adding custom validatorfunctions. (Ex:validate:"customFunc")
RBAC, ACL, ABAC with casbin - Authorization library.
Define policies in a policy.csv file.
p, alice, /route1, GET
p, bob, /route1, POST
p, admin, /route1, *
p, admin, /route2, *
With a model.conf file.
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.sub == p.sub && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")
An enforcer can be created with the model.conf and policy.csv files.
package main
import (
    "fmt"
    "github.com/casbin/casbin/v2"
    "github.com/casbin/casbin/v2/model"
    "github.com/casbin/casbin/v2/persist"
    "github.com/casbin/casbin/v2/persist/file-adapter"
)
func main() {
    m, _ := model.NewModelFromFile("model.conf")
    a, _ := fileadapter.NewAdapter("policy.csv")
    e, _ := casbin.NewEnforcer(m, a)
    sub := "alice"
    obj := "/route1"
    act := "GET"
    if e.Enforce(sub, obj, act) {
        fmt.Println("Access granted")
    } else {
        fmt.Println("Access denied")
    }
}
- The rules can also be read from a database.
http-swagger - Swagger 2.0 implementation for go-chi.
Example:
package main
import (
    "net/http"
    "github.com/go-chi/chi"
    "github.com/swaggo/http-swagger/v2"
    _ "github.com/swaggo/http-swagger/example/go-chi/docs" // docs is generated by Swag CLI, you have to import it.
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host petstore.swagger.io
// @BasePath /v2
func main() {
    r := chi.NewRouter()
    r.Get("/swagger/*", httpSwagger.Handler(
        httpSwagger.URL("http://localhost:5000/swagger/doc.json"), //The url pointing to API definition
    ))
    http.ListenAndServe(":5000", r)
}
- Docs can be generated with swag init.