dij_gin

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 15, 2022 License: MIT Imports: 15 Imported by: 17

README

dij-gin

A dij-style gin library. gin is one of most popular web frameworks for golang. dij stands for dependency injection. This library provides a dij-style gin wrapper.

Refer to completed examples in go-examples.

Contents


Gin Style


Get method

The WebContext embeds gin.Context, any gin helper functions can be used directly.

package main

import (
	. "github.com/letscool/dij-gin"
	"log"
	"net/http"
)

type TWebServer struct {
	WebServer
}

// GetHello a http request with "get" method.
// Url should like this in local: http://localhost:8000/hello
func (s *TWebServer) GetHello(ctx WebContext) {
	ctx.IndentedJSON(http.StatusOK, "/hello")
}

func main() {
	//dij.EnableLog()
	if err := LaunchGin(&TWebServer{}); err != nil {
		log.Fatalln(err)
	}
}

The function name GetHello should combine a method and a path name. Method should be one of valid http methods, for examples: Get, Post, Delete, etc.

Hierarchy/Controller

You can group a few http functions in one controller, which likes what gin.router.Group function does.

package main

import (
	. "github.com/letscool/dij-gin"
	"log"
	"net/http"
)

type TWebServer struct {
	WebServer

	userCtl *TUserController `di:""` // inject dependency by class/default name
}

type TUserController struct {
	WebController `http:"user"` //group by 'user' path
}

// Get a http request with "get" method.
// Url should like this in local: http://localhost:8000/user
func (u *TUserController) Get(ctx WebContext) {
	ctx.IndentedJSON(http.StatusOK, "/user")
}

// GetMe a http request with "get" method.
// Url should like this in local: http://localhost:8000/user/me
func (u *TUserController) GetMe(ctx WebContext) {
	ctx.IndentedJSON(http.StatusOK, "/user/me")
}

func main() {
	//dij.EnableLog()
	if err := LaunchGin(&TWebServer{}); err != nil {
		log.Fatalln(err)
	}
}

dij-gin Style


dij-gin style includes many features:

  • Easy way to retrieve path parameters, query parameters, etc.
  • Easy way to response data with different http code.
  • Support OpenAPI(v3.0) generation.
  • Http functions support to enable or disable by runtime environment, aka: prod, dev, and test.
Query
package main

import (
  "fmt"
  . "github.com/letscool/dij-gin"
  "log"
  "net/http"
)

type TWebServer struct {
  WebServer
}

// GetHello a http request with "get" method.
// Url should like this in local: http://localhost:8000/hello?name=wayne&age=123.
// The result will be:
//
//	"/hello wayne, 123 years old"
func (s *TWebServer) GetHello(ctx struct {
  WebContext
  Name string `http:"name"`
  Age  int    `http:"age"`
}) {
  ctx.IndentedJSON(http.StatusOK, fmt.Sprintf("/hello %s, %d years old", ctx.Name, ctx.Age))
}

func main() {
  if err := LaunchGin(&TWebServer{}); err != nil {
    log.Fatalln(err)
  }
}
Where variable data came from?

Add an attribute "in=xxx" in http tag. About http tag setting, see the reference

package main

import (
	"fmt"
	. "github.com/letscool/dij-gin"
	"log"
	"net/http"
)

type TWebServer struct {
	WebServer

	userCtl *TUserController `di:""` // inject dependency by class/default name
}

type TUserController struct {
	WebController `http:"user"` //group by 'user' path
}

// PutUserById a http request with "get" method.
// Curl this url should like this in local:
//
//	curl -d "age=34&name=wayne" -X PUT http://localhost:8000/user/2345/profile
//
// The result should be:
//
//	"update user(#2345)'s name wayne and age 34"
func (u *TUserController) PutUserById(ctx struct {
	WebContext `http:":id/profile"`
	Id         int    `http:"id,in=path"`
	Name       string `http:"name,in=body"`
	Age        int    `http:"age,in=body"`
}) {
	ctx.IndentedJSON(http.StatusOK, fmt.Sprintf("update user(#%d)'s name %s and age %d", ctx.Id, ctx.Name, ctx.Age))
}

func main() {
	if err := LaunchGin(&TWebServer{}); err != nil {
		log.Fatalln(err)
	}
}
Customize path name and http method

Add http tag with the format "[path],method=[method]".

package main

import (
	. "github.com/letscool/dij-gin"
	"log"
	"net/http"
)

type TWebServer struct {
	WebServer
}

// SayHi a http request with "get" method.
// Url should like this in local: http://localhost:8000/hello.
func (s *TWebServer) SayHi(ctx struct {
	WebContext `http:"hello,method=get"`
}) {
	ctx.IndentedJSON(http.StatusOK, "hello")
}

func main() {
	if err := LaunchGin(&TWebServer{}); err != nil {
		log.Fatalln(err)
	}
}
No Route
package main

import (
	. "github.com/letscool/dij-gin"
	"log"
)

type TWebServer struct {
	WebServer
}

// NoRoute is entry for page not found, is only supported in root path currently.
// Any query will show the log.
func (s *TWebServer) NoRoute(ctx WebContext) {
	log.Printf("no route: %s\n", ctx.Request.RequestURI)
}

func main() {
	if err := LaunchGin(&TWebServer{}); err != nil {
		log.Fatalln(err)
	}
}
Validator

dij-gin uses go-playground/validator/v10 for validation. gin uses 'binding' as validation tag key instead of 'validate', 'validate' tag key is chose from go-playground/validator/v10 official. dij-gin still uses 'validate' tag key.

package main

import (
	"fmt"
	. "github.com/letscool/dij-gin"
	"log"
	"net/http"
)

type TWebServer struct {
	WebServer

	userCtl *TUserController `di:""` // inject dependency by class/default name
}

type TUserController struct {
	WebController `http:"user"` //group by 'user' path
}

// GetUserById a http request with "get" method.
// Url should like this in local: http://localhost:8000/user/2345/profile.
// The result will be:
//
//	{"message":"Key: 'Id' Error:Field validation for 'Id' failed on the 'lte' tag","code":"400"}
func (u *TUserController) GetUserById(ctx struct {
	WebContext `http:":id/profile"`
	Id         int `http:"id,in=path" validate:"gte=100,lte=999"`
}) {
	ctx.IndentedJSON(http.StatusOK, fmt.Sprintf("get user(#%d)'s profile", ctx.Id))
}

func main() {
	if err := LaunchGin(&TWebServer{}); err != nil {
		log.Fatalln(err)
	}
}
Response
package main

import (
  "errors"
  . "github.com/letscool/dij-gin"
  "log"
)

type TWebServer struct {
  WebServer
}

// GetResp a http request with "get" method.
// Url should like this in local: http://localhost:8000/resp?select=1 .
// Use *curl -v* command to see response code.
func (s *TWebServer) GetResp(ctx struct {
  WebContext
  Select int `http:"select"`
}) (result struct {
  Ok200       *string // the range of last three characters is between 2xx and 5xx, so the response code = 200
  Ok          *string `http:"201"` // force response code to 201
  Redirect302 *string // redirect data should be string type, because it is redirect location.
  Error       error   // default response code for error is 400
}) {
  switch ctx.Select {
  case 1:
    data := "ok"
    result.Ok200 = &data
  case 2:
    data := "ok"
    result.Ok = &data
  case 3:
    url := "https://github.com/letscool"
    result.Redirect302 = &url
  default:
    result.Error = errors.New("an error")
  }
  return
}

func main() {
  if err := LaunchGin(&TWebServer{}); err != nil {
    log.Fatalln(err)
  }
}
Middlewares
Log
  • Log all http methods for a controller and all it's sub-controllers
package main

import (
  "fmt"
  "github.com/gin-gonic/gin"
  . "github.com/letscool/dij-gin"
  "github.com/letscool/dij-gin/libs"
  "log"
  "net/http"
)

type TWebServer struct {
  WebServer `http:",middleware=log"`

  _ *libs.LogMiddleware `di:""`
}

// GetHello a http request with "get" method.
// Url should like this in local: http://localhost:8000/hello
func (t *TWebServer) GetHello(ctx WebContext) {
  ctx.IndentedJSON(http.StatusOK, "/hello")
}

func main() {
  //f, _ := os.Create("gin.log") // log to file
  config := NewWebConfig().
          //SetDefaultWriter(io.MultiWriter(f)).
          SetDependentRef(libs.RefKeyForLogFormatter, (gin.LogFormatter)(func(params gin.LogFormatterParams) string {
            // your custom format
            return fmt.Sprintf("[%s-%s] \"%s %s\"\n",
              params.ClientIP,
              params.TimeStamp.Format("15:04:05.000"),
              params.Method,
              params.Path,
            )
          }))
  if err := LaunchGin(&TWebServer{}, config); err != nil {
    log.Fatalln(err)
  }
}
  • Log functions only which set log middleware
package main

import (
  "fmt"
  "github.com/gin-gonic/gin"
  . "github.com/letscool/dij-gin"
  "github.com/letscool/dij-gin/libs"
  "log"
  "net/http"
)

type TWebServer struct {
  WebServer `http:""`

  _ *libs.LogMiddleware `di:""`
}

// GetHelloWithLog a http request with "get" method.
// Url should like this in local: http://localhost:8000/hello_with_log
func (t *TWebServer) GetHelloWithLog(ctx struct {
  WebContext `http:"hello_with_log,middleware=log"`
}) {
  ctx.IndentedJSON(http.StatusOK, "hello with log")
}

// GetHelloWithoutLog a http request with "get" method.
// Url should like this in local: http://localhost:8000/hello_without_log
func (t *TWebServer) GetHelloWithoutLog(ctx struct {
  WebContext `http:"hello_without_log"`
}) {
  ctx.IndentedJSON(http.StatusOK, "hello without log")
}

func main() {
  //f, _ := os.Create("gin.log") // log to file
  config := NewWebConfig().
          //SetDefaultWriter(io.MultiWriter(f)).
          SetDependentRef(libs.RefKeyForLogFormatter, (gin.LogFormatter)(func(params gin.LogFormatterParams) string {
            // your custom format
            return fmt.Sprintf("[%s-%s] \"%s %s\"\n",
              params.ClientIP,
              params.TimeStamp.Format("15:04:05.000"),
              params.Method,
              params.Path,
            )
          }))
  if err := LaunchGin(&TWebServer{}, config); err != nil {
    log.Fatalln(err)
  }
}
Basic Auth

This sample also enables OpenAPI document.

package main

import (
  . "github.com/letscool/dij-gin"
  "github.com/letscool/dij-gin/libs"
  "github.com/letscool/go-examples/dij-gin/shared"
  "log"
)

type TWebServer struct {
  WebServer
  _ *libs.SwaggerController `di:""` // Bind OpenApi controller in root.
  _ *TUserController        `di:""`
}

type TUserController struct {
  WebController `http:"user"`

  _ *shared.BasicAuthMiddleware `di:""`
}

// GetMe a http request with "get" method.
// Url should like this in local: http://localhost:8000/user/me.
// And login with username "john" and password "abc".
func (u *TUserController) GetMe(ctx struct {
  WebContext `http:",middleware=basic_auth" security:"basic_auth_1"`
}) (result struct {
  Account *shared.Account `http:"200,json"`
}) {
  result.Account = ctx.MustGet(shared.BasicAuthUserKey).(*shared.Account)
  return
}

func main() {
  ac := &shared.FakeAccountDb{} // This object should implement shared.BasicAuthAccountCenter interface.
  ac.InitFakeDb()
  config := NewWebConfig().
    SetDependentRef(shared.RefKeyForBasicAuthAccountCenter, ac).
          SetOpenApi(func(o *OpenApiConfig) {
            o.Enable().UseHttpOnly().SetDocPath("doc").
              AppendBasicAuth("basic_auth_1")
          })
  if err := LaunchGin(&TWebServer{}, config); err != nil {
    log.Fatalln(err)
  }
}
Bearer

This sample also enables OpenAPI document.

package main

import (
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	. "github.com/letscool/dij-gin"
	"github.com/letscool/dij-gin/libs"
	"github.com/letscool/go-examples/dij-gin/shared"
	"log"
	"time"
)

type TWebServer struct {
	WebServer
	_ *libs.SwaggerController `di:""` // Bind OpenApi controller in root.
	_ *TUserController        `di:""`
}

type TUserController struct {
	WebController `http:"user"`

	_ *shared.BearerMiddleware `di:""`
}

// GetMe a http request with "get" method.
// Url should like this in local: http://localhost:8000/user/me.
// And login with username "john" and password "abc".
func (u *TUserController) GetMe(ctx struct {
	WebContext `http:",middleware=bearer" security:"bearer_1"`
}) (result struct {
	Account *shared.Account `http:"200,json"`
}) {
	result.Account = ctx.MustGet(shared.BearerUserKey).(*shared.Account)
	return
}

func main() {
	ac := &shared.FakeAccountDb{} // This object must implement shared.BearerValidator interface.
	accounts := ac.InitFakeDb()
	// generate a jwt token for test
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(5 * time.Minute)),
		IssuedAt:  jwt.NewNumericDate(time.Now()),
		Issuer:    "dij-gin-samples",
		ID:        accounts[0].User,
	})
	// Sign and get the complete encoded token as a string using the secret
	tokenString, err := token.SignedString([]byte(ac.BearerSecret()))
	if err != nil {
		log.Panicln(err)
	} else {
		fmt.Println("*************************")
		fmt.Printf("User: %s\n", accounts[0].User)
		fmt.Printf("Bearer token: %s\n", tokenString)
		fmt.Println("*************************")
	}
	//
	config := NewWebConfig().
		SetDependentRef(shared.RefKeyForBearerValidator, ac).
		SetOpenApi(func(o *OpenApiConfig) {
			o.Enable().UseHttpOnly().SetDocPath("doc").
				AppendBearerAuth("bearer_1")
		})
	if err := LaunchGin(&TWebServer{}, config); err != nil {
		log.Fatalln(err)
	}
}
CORS

(on-going)

OpenAPI generation

When you use dij-gin style to setup server, dij-gin server will automatically generate OpenAPI document if you need.

// Copyright 2022 Yuchi Chen. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package main

import (
	"errors"
	. "github.com/letscool/dij-gin"
	"github.com/letscool/dij-gin/libs"
	"log"
)

type TWebServer struct {
	WebServer

	openapi *libs.SwaggerController `di:""` // Bind OpenApi controller in root.
}

// GetResp a http request with "get" method.
// Url should like this in local: http://localhost:8000/resp?select=1 .
// Use *curl -v* command to see response code.
func (s *TWebServer) GetResp(ctx struct {
	WebContext
	Select int `http:"select"`
}) (result struct {
	Ok200 *string // the range of last three characters is between 2xx and 5xx, so the response code = 200
	Ok    *string `http:"201"` // force response code to 201
	Error error   // default response code for error is 400
}) {
	switch ctx.Select {
	case 1:
		data := "ok"
		result.Ok200 = &data
	case 2:
		data := "ok"
		result.Ok = &data
	default:
		result.Error = errors.New("an error")
	}
	return
}

// The OpenAPI page will be enabled in location: http://localhost:8000/doc.
func main() {
	config := NewWebConfig().
		SetOpenApi(func(o *OpenApiConfig) {
			o.SetEnabled(true).UseHttpOnly().SetDocPath("doc")
		})
	if err := LaunchGin(&TWebServer{}, config); err != nil {
		log.Fatalln(err)
	}
}

Http Tag


(on-going)

Attributes
  • path
  • name
  • method
  • env
  • tag
  • middleware
Coding/Media Type for Request Input

The http tag includes an attribute "[AttrKey]" for request and response body. and "mime=[MIME_TYPE]" for response body only.

AttrKey Req/Resp MIME Type
form, multipart Req multipart/form-data
urlenc, urlencoded BOTH application/x-www-form-urlencoded
json Both application/json
xml Both application/xml
plain Resp text/plain
page, html Resp text/html
octet Resp application/octet-stream
jpeg, png Resp image/jpeg,png
Data way for Request Input Variables

The http tag includes an attribute "in=[AttrKey]"

AttrKey Default situation Meaning
header
cookie
path If variable name is included in path
query
body

TODO List


Still many function should be implemented, such as:

  • Redirect response
  • Response urlencoded data
  • More middlewares
  • Fix bugs
  • More examples for http tag settings
  • Add unit tests
  • Dynamic path for controller
  • NoRoute

Documentation

Index

Constants

View Source
const (
	DefaultWebServerPort    = 8000
	DefaultValidatorTagName = "validate"
)
View Source
const (
	HttpTagName            = "http"
	DescriptionTagName     = "description"
	SecurityTagName        = "security"
	RefKeyForWebConfig     = "_.webserver.config"
	RefKeyForWebSpecRecord = "_.webserver.spec.record"
	RefKeyForWebValidator  = "_.webserver.validator"
	RefKeyForWebDijRef     = "_.webserver.dij.ref"
)

Variables

View Source
var TypeOfWebError reflect.Type
View Source
var WebCtxType reflect.Type

Functions

func GetPreferredResponseFormat added in v0.0.3

func GetPreferredResponseFormat(typ reflect.Type) spec.MediaTypeTitle

func IsCorrectInWay added in v0.0.3

func IsCorrectInWay(way InWay) bool

func IsTypeOfWebContext

func IsTypeOfWebContext(typ reflect.Type) bool

func IsTypeOfWebController

func IsTypeOfWebController(typ reflect.Type) bool

func IsTypeOfWebMiddleware

func IsTypeOfWebMiddleware(typ reflect.Type) bool

func IsTypeOfWebServer

func IsTypeOfWebServer(typ reflect.Type) bool

func LaunchGin

func LaunchGin(webServerTypeOrInst any, others ...any) error

LaunchGin launches a web server. The webServerTypeOrInst should be a struct type which is embedded WebServer or an instance (pointer) of a struct type which is embedded WebServer.

A new web server definition:

type WebSer struct {
  WebServer
}

func main() {
  webTyp = reflect.TypeOf(WebSer{})
  LaunchGin(webTyp) // launch by type

  webInst = &WebSer{}
  LaunchGin(webInst) // launch by instance
}

func PrepareGin

func PrepareGin(webServerTypeOrInst any, others ...any) (*gin.Engine, dij.DependencyReferencePtr, error)

Types

type BaseParamField added in v0.0.3

type BaseParamField struct {
	Index         int
	FieldSpec     reflect.StructField
	ExistsTag     bool           // exists http tag
	Attrs         StructTagAttrs // come from http tag
	PreferredName string
	Description   string
}

func (*BaseParamField) PreferredMediaTypeTitleForResponse added in v0.0.3

func (c *BaseParamField) PreferredMediaTypeTitleForResponse() spec.MediaTypeTitle

func (*BaseParamField) SupportedMediaTypesForRequest added in v0.0.3

func (c *BaseParamField) SupportedMediaTypesForRequest() []spec.MediaTypeSupport

type HandlerSpec added in v0.0.3

type HandlerSpec struct {
	Purpose         HandlerWrapperPurpose
	MethodType      reflect.Method
	BaseParamType   reflect.Type
	Method          string // lower case, ex: get, post, etc.
	Path            string // lower cast path, does it need to support case-sensitive?
	InFields        []BaseParamField
	MiddlewareNames []string
	OutFields       []BaseParamField
	CtxAttrs        StructTagAttrs // tag attr come from the base field in InFields
	Description     string         // description comes from the base field in InFields
	Security        string         // security comes from the tag of base field
}

func (*HandlerSpec) UpperMethod added in v0.0.3

func (s *HandlerSpec) UpperMethod() string

type HandlerWrapper

type HandlerWrapper struct {
	Spec    HandlerSpec
	Handler gin.HandlerFunc
}

func GenerateHandlerWrappers

func GenerateHandlerWrappers(instPtr any, purpose HandlerWrapperPurpose, refPtr dij.DependencyReferencePtr) []HandlerWrapper

GenerateHandlerWrappers generates handler for the instance TODO: consider to cache result for same instance.

func (*HandlerWrapper) ConcatOpenapiPath added in v0.0.3

func (w *HandlerWrapper) ConcatOpenapiPath(basePath string) (fullPath string, params []string)

func (*HandlerWrapper) ReqMethod added in v0.0.3

func (w *HandlerWrapper) ReqMethod() string

func (*HandlerWrapper) ReqPath added in v0.0.3

func (w *HandlerWrapper) ReqPath() string

func (*HandlerWrapper) UpperReqMethod added in v0.0.3

func (w *HandlerWrapper) UpperReqMethod() string

type HandlerWrapperPurpose

type HandlerWrapperPurpose int
const (
	HandlerForReq HandlerWrapperPurpose = iota // for http request
	HandlerForMid                              // for middleware
)

func (HandlerWrapperPurpose) BaseKey added in v0.0.3

func (h HandlerWrapperPurpose) BaseKey() string

func (HandlerWrapperPurpose) Regexp added in v0.0.3

func (h HandlerWrapperPurpose) Regexp() *regexp.Regexp

type InWay added in v0.0.3

type InWay = string
const (
	InHeaderWay InWay = "header" // one kind of way for parameter
	InCookieWay InWay = "cookie" // one kind of way for parameter
	InQueryWay  InWay = "query"  // one kind of way for parameter
	InPathWay   InWay = "path"   // one kind of way for parameter
	InBodyWay   InWay = "body"   // one kind of way for request body
)

type OpenApiConfig added in v0.0.3

type OpenApiConfig struct {
	Enabled         bool // Default is false
	Title           string
	Description     string
	Version         string
	Schemes         []string // ex: "http", "https". Default is "https".
	Address         string
	Port            int
	DocPath         string // Default is "doc"
	SecuritySchemes spec.SecuritySchemes
}

func (*OpenApiConfig) AppendApiKeyAuth added in v0.1.0

func (o *OpenApiConfig) AppendApiKeyAuth(name string, paramIn InWay, paramName string) *OpenApiConfig

func (*OpenApiConfig) AppendBasicAuth added in v0.1.0

func (o *OpenApiConfig) AppendBasicAuth(name string) *OpenApiConfig

func (*OpenApiConfig) AppendBearerAuth added in v0.1.0

func (o *OpenApiConfig) AppendBearerAuth(name string) *OpenApiConfig

func (*OpenApiConfig) AppendSecurityScheme added in v0.1.0

func (o *OpenApiConfig) AppendSecurityScheme(name string, scheme spec.SecurityScheme) *OpenApiConfig

func (*OpenApiConfig) ApplyDefaultValues added in v0.0.3

func (o *OpenApiConfig) ApplyDefaultValues()

func (*OpenApiConfig) Enable added in v0.0.3

func (o *OpenApiConfig) Enable() *OpenApiConfig

func (*OpenApiConfig) SetAddress added in v0.0.8

func (o *OpenApiConfig) SetAddress(addr string) *OpenApiConfig

func (*OpenApiConfig) SetDescription added in v0.0.5

func (o *OpenApiConfig) SetDescription(description string) *OpenApiConfig

func (*OpenApiConfig) SetDocPath added in v0.0.3

func (o *OpenApiConfig) SetDocPath(path string) *OpenApiConfig

func (*OpenApiConfig) SetEnabled added in v0.0.3

func (o *OpenApiConfig) SetEnabled(en bool) *OpenApiConfig

func (*OpenApiConfig) SetPort added in v0.0.8

func (o *OpenApiConfig) SetPort(port int) *OpenApiConfig

func (*OpenApiConfig) SetTitle added in v0.0.5

func (o *OpenApiConfig) SetTitle(title string) *OpenApiConfig

func (*OpenApiConfig) SetVersion added in v0.0.5

func (o *OpenApiConfig) SetVersion(version string) *OpenApiConfig

func (*OpenApiConfig) UseHttpAndHttps added in v0.0.3

func (o *OpenApiConfig) UseHttpAndHttps() *OpenApiConfig

func (*OpenApiConfig) UseHttpOnly added in v0.0.3

func (o *OpenApiConfig) UseHttpOnly() *OpenApiConfig

func (*OpenApiConfig) UseHttpsOnly added in v0.0.3

func (o *OpenApiConfig) UseHttpsOnly() *OpenApiConfig

type RuntimeEnv added in v0.0.3

type RuntimeEnv string
const (
	RtProd  RuntimeEnv = "prod"
	RtDev   RuntimeEnv = "dev"
	RtDebug RuntimeEnv = "debug"
	RtTest  RuntimeEnv = "test"
)

func (RuntimeEnv) IsInOnlyEnv added in v0.0.3

func (r RuntimeEnv) IsInOnlyEnv(onlyEnv string) bool

type WebConfig added in v0.0.3

type WebConfig struct {
	Address          string // default is localhost
	Port             int    // if not setting, 8000 will be used.
	MaxConn          int
	BasePath         string // Default is empty
	ValidatorTagName string // Default is "validate", but go-gin preferred "binding".
	DependentRefs    map[string]any
	RtEnv            RuntimeEnv // Default is "dev"
	OpenApi          OpenApiConfig
	DefaultWriter    io.Writer
}

func NewWebConfig added in v0.0.3

func NewWebConfig() *WebConfig

NewWebConfig returns an instance with default values.

func (*WebConfig) ApplyDefaultValues added in v0.0.3

func (c *WebConfig) ApplyDefaultValues()

ApplyDefaultValues if some properties are zero or empty, it will set the default values.

func (*WebConfig) SetAddress added in v0.0.3

func (c *WebConfig) SetAddress(addr string) *WebConfig

func (*WebConfig) SetBasePath added in v0.0.3

func (c *WebConfig) SetBasePath(path string) *WebConfig

func (*WebConfig) SetDefaultWriter added in v0.0.4

func (c *WebConfig) SetDefaultWriter(writer io.Writer) *WebConfig

func (*WebConfig) SetDependentRef added in v0.0.4

func (c *WebConfig) SetDependentRef(key string, ref any) *WebConfig

func (*WebConfig) SetOpenApi added in v0.0.3

func (c *WebConfig) SetOpenApi(f func(o *OpenApiConfig)) *WebConfig

func (*WebConfig) SetPort added in v0.0.3

func (c *WebConfig) SetPort(port int) *WebConfig

func (*WebConfig) SetRtMode added in v0.0.3

func (c *WebConfig) SetRtMode(mode RuntimeEnv) *WebConfig

type WebContext

type WebContext struct {
	*gin.Context
}

func (*WebContext) GetRequestHeader added in v0.0.4

func (c *WebContext) GetRequestHeader(key string) string

func (*WebContext) GetRequestValue

func (c *WebContext) GetRequestValue(key string, instPtr any) (exists bool)

func (*WebContext) GetRequestValueForType

func (c *WebContext) GetRequestValueForType(key string, typ reflect.Type, inWay InWay) (data any, exists bool)

type WebContextSpec

type WebContextSpec interface {
	GetRequestHeader(key string) string
	// contains filtered or unexported methods
}

type WebController

type WebController struct {
	// contains filtered or unexported fields
}

func (*WebController) GetRef added in v0.0.5

func (w *WebController) GetRef(keyOfRef string) (any, bool)

func (*WebController) SetupRouter added in v0.0.3

func (w *WebController) SetupRouter(_ WebRouter, _ ...any)

type WebControllerSpec

type WebControllerSpec interface {

	// SetupRouter only be implemented for dynamic routing in runtime.
	SetupRouter(router WebRouter, others ...any)
	// contains filtered or unexported methods
}

type WebError added in v0.0.3

type WebError struct {
	Message string `json:"message"`
	Code    string `json:"code"`
	// contains filtered or unexported fields
}

func ToWebError added in v0.0.3

func ToWebError(err error, code string) WebError

type WebMiddleware

type WebMiddleware struct {
}

type WebMiddlewareSpec

type WebMiddlewareSpec interface {
	// contains filtered or unexported methods
}

type WebRouter added in v0.0.3

type WebRouter interface {
	gin.IRouter
	BasePath() string
}

type WebRoutes added in v0.0.3

type WebRoutes interface {
	gin.IRoutes
	BasePath() string
}

type WebServer

type WebServer struct {
	WebController
}

type WebServerSpec

type WebServerSpec interface {
	WebControllerSpec
	// contains filtered or unexported methods
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL