goose

package module
v1.6.6 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2025 License: MIT Imports: 14 Imported by: 0

README

goose

goose 参考 Google API 设计方案,通过定义 proto 文件,快速生成Go语言的Restful服务路由。

路由规则

goose 底层基于 Go 1.22 HTTP Router 管理http路由。详细定义规则见Enhanced ServeMux routing

优点

  1. 基于proto文件,快速生成Restful服务路由
  2. 零配置
  3. 低依赖
  4. 非反射取值,效率非常高
  5. 稳定,所有方法经过单元测试
  6. 代码简单,良好的代码设计,减少出错

安装

go install github.com/go-leo/goose/cmd/protoc-gen-goose@latest

Example

syntax = "proto3";
package leo.goose.example.user.v1;
option go_package = "github.com/go-leo/goose/example/user/v1;user";

import "google/api/annotations.proto";

service User {

  // CreateUser 创建用户
  // `POST /v1/user { "name": "Leo" }` | `CreateUserRequest(name: "Leo")`
  rpc CreateUser (CreateUserRequest) returns (CreateUserResponse) {
    option (google.api.http) = {
      post : "/v1/user"
      body : "*"
    };
  }

  // DeleteUser 删除用户
    // `DELETE /v1/user/10000 | `DeleteUserRequest(id: 10000)`
  rpc DeleteUser (DeleteUserRequest) returns (DeleteUserResponse) {
    option (google.api.http) = {
      delete : "/v1/user/{id}"
    };
  }

  // ModifyUser 修改用户
  // `PUT /v1/user/10000 { "name": "Leo" }` | `ModifyUserRequest(id: 10000, name: "Leo")`
  rpc ModifyUser (ModifyUserRequest) returns (ModifyUserResponse) {
    option (google.api.http) = {
      put : "/v1/user/{id}"
      body : "*"
    };
  }

  // UpdateUser 更新用户
  // `PUT /v1/user/10000 { "id": "99999" ,"name": "Leo" }` | `UpdateUserRequest(id: 10000, UserItem(id: 9999, name: "Leo"))`
  rpc UpdateUser (UpdateUserRequest) returns (UpdateUserResponse) {
    option (google.api.http) = {
      patch : "/v1/user/{id}"
      body : "item"
    };
  }

  // GetUser 获取用户
  // `GET /v1/user/10000` | `GetUserRequest(id: 10000)`
  rpc GetUser (GetUserRequest) returns (GetUserResponse) {
    option (google.api.http) = {
      get : "/v1/user/{id}"
    };
  }

  // ListUser 获取用户列表
  // `GET /v1/users?page_num=1&page_size=10` | `ListUserRequest(page_num: 1, page_size: 10)`
  rpc ListUser (ListUserRequest) returns (ListUserResponse) {
    option (google.api.http) = {
      get : "/v1/users"
    };
  }
}

message UserItem {
  int64 id = 1;
  string name = 2;
}

message CreateUserRequest {
  string name = 1;
}

message CreateUserResponse {
  UserItem item = 1;
}

message DeleteUserRequest {
  int64 id = 1;
}

message DeleteUserResponse {
  int64 id = 1;
}

message ModifyUserRequest {
  int64 id = 1;
  string name = 2;
}

message ModifyUserResponse {
    int64 id = 1;
  string name = 2;
}

message UpdateUserRequest {
  int64 id = 1;
  UserItem item = 2;
}

message UpdateUserResponse {
  int64 id = 1;
  UserItem item = 2;
}

message GetUserRequest {
  int64 id = 1;
}

message GetUserResponse {
  UserItem item = 1;
}

message ListUserRequest {
  int64 page_num = 1;
  int64 page_size = 2;
}

message ListUserResponse {
  int64 page_num = 1;
  int64 page_size = 2;
  repeated UserItem list = 3;
}

定义了6个接口:分别是

  1. 创建用户,POST请求
  2. 删除用户,DELETE请求
  3. 修改用户,PUT请求
  4. 更新用户,PATCH请求
  5. 获取用户, GET请求
  6. 获取用户列表, GET请求

生成路由

执行命令

protoc \
--proto_path=. \
--proto_path=../third_party \
--proto_path=../../ \
--go_out=. \
--go_opt=paths=source_relative \
--goose_out=. \
--goose_opt=paths=source_relative \
user/user.proto

生成一下文件

user
├── user_goose.pb.go
├── user_test.go
├── user.pb.go
└── user.proto

实现UserService代码:


type MockUserService struct{}

func (m *MockUserService) CreateUser(ctx context.Context, req *CreateUserRequest) (*CreateUserResponse, error) {
	return &CreateUserResponse{Item: &UserItem{Id: 1, Name: req.Name}}, nil
}

func (m *MockUserService) DeleteUser(ctx context.Context, req *DeleteUserRequest) (*DeleteUserResponse, error) {
	return &DeleteUserResponse{Id: req.GetId()}, nil
}

func (m *MockUserService) ModifyUser(ctx context.Context, req *ModifyUserRequest) (*ModifyUserResponse, error) {
	return &ModifyUserResponse{Id: req.GetId(), Name: req.GetName()}, nil
}

func (m *MockUserService) UpdateUser(ctx context.Context, req *UpdateUserRequest) (*UpdateUserResponse, error) {
	return &UpdateUserResponse{Id: req.GetId(), Item: &UserItem{Id: req.GetItem().GetId(), Name: req.GetItem().GetName()}}, nil
}

func (m *MockUserService) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, error) {
	return &GetUserResponse{Item: &UserItem{Id: req.Id, Name: "test"}}, nil
}

func (m *MockUserService) ListUser(ctx context.Context, req *ListUserRequest) (*ListUserResponse, error) {
	return &ListUserResponse{
		PageNum:  req.GetPageNum(),
		PageSize: req.GetPageSize(),
		List: []*UserItem{
			{Id: 1, Name: "a"},
			{Id: 2, Name: "b"},
		},
	}, nil
}

创建Server

func main() {
	router := http.NewServeMux()
	router = AppendUserGooseRoute(router, &MockUserService{})
	server := http.Server{Addr: ":8000", Handler: router}
	server.ListenAndServe()
}

更多示例见 [example]https://github.com/go-leo/goose/tree/example/user/server

子妹项目

Documentation

Index

Constants

View Source
const (
	// ContentTypeKey is the key for the content type header.
	ContentTypeKey = "Content-Type"

	// JsonContentType is the content type for JSON.
	JsonContentType = "application/json; charset=utf-8"

	// PlainContentType is the content type for plain text.
	PlainContentType = "text/plain; charset=utf-8"
)

Variables

This section is empty.

Functions

func AppendPProf

func AppendPProf(router *http.ServeMux) *http.ServeMux

func Chain

func Chain(handler http.Handler, middlewares ...MiddlewareFunc) http.Handler

Chain applies a series of middleware functions to an HTTP handler in reverse order. This allows middleware to be executed in the order they are provided (first middleware wraps the original handler, subsequent middlewares wrap the previous chain).

Parameters:

  • handler: The base HTTP handler to be wrapped by middlewares.
  • middlewares: A variadic list of middleware functions to be applied. These will be executed in reverse order (last middleware in the list is applied first).

Returns:

  • http.Handler: The final handler wrapped by all middlewares in the chain.

func CustomDecodeRequest

func CustomDecodeRequest(ctx context.Context, r *http.Request, req proto.Message) (bool, error)

CustomDecodeRequest provides custom request decoding functionality Parameters:

  • ctx: Context object
  • r: HTTP request object
  • req: Proto.Message to be decoded

Returns:

  • bool: Indicates whether custom decoding was performed
  • error: Any error that occurred during decoding

Behavior:

  1. Checks if req implements UnmarshalRequest method
  2. If implemented, invokes the method for decoding
  3. If not implemented, returns false indicating no custom decoding was done

func DecodeForm

func DecodeForm[T any](pre error, form url.Values, key string, f FormGetter[T]) (T, error)

DecodeForm decodes form data Parameters:

  • pre: Pre-existing error (if any, will be returned immediately)
  • form: Form data
  • key: Form field key
  • f: Form data getter function

Returns:

  • T: Decoded value
  • error: Decoding error if any

Behavior:

  1. If pre is not nil, returns pre error immediately
  2. Otherwise invokes f to get form value

func DecodeHttpBody

func DecodeHttpBody(ctx context.Context, r *http.Request, body *httpbody.HttpBody) error

DecodeHttpBody decodes HTTP request body into HttpBody object Parameters:

  • ctx: Context object
  • r: HTTP request object
  • body: Target HttpBody object

Returns:

  • error: Decoding error if any

Behavior:

  1. Reads the request body data
  2. Sets HttpBody's Data and ContentType fields

func DecodeHttpRequest

func DecodeHttpRequest(ctx context.Context, r *http.Request, request *rpchttp.HttpRequest) error

DecodeHttpRequest decodes HTTP request into HttpRequest object Parameters:

  • ctx: Context object
  • r: HTTP request object
  • request: Target HttpRequest object

Returns:

  • error: Decoding error if any

Behavior:

  1. Reads the request body data
  2. Sets method, URI, headers and body fields

func DecodeRequest

func DecodeRequest(ctx context.Context, r *http.Request, req proto.Message, unmarshalOptions protojson.UnmarshalOptions) error

DecodeRequest decodes HTTP request body into a proto.Message Parameters:

  • ctx: Context object
  • r: HTTP request object
  • req: Target proto.Message
  • unmarshalOptions: protojson unmarshal options

Returns:

  • error: Decoding error if any

Behavior:

  1. Reads the request body
  2. Unmarshals the data into target proto.Message using protojson

func DefaultEncodeError

func DefaultEncodeError(ctx context.Context, err error, w http.ResponseWriter)

DefaultEncodeError encodes errors into HTTP responses with appropriate status codes and content type. Handles several error types: - json.Marshaler: encodes error as JSON if implemented - Headers() http.Header: adds headers to response if implemented - StatusCode() int: uses custom status code if implemented

Parameters:

ctx - context.Context for the request
err - error to encode
w - http.ResponseWriter to write the error response

func DefaultTransformResponse

func DefaultTransformResponse(ctx context.Context, resp proto.Message) proto.Message

DefaultTransformResponse is the default response transformer that returns the response unchanged.

Parameters:

ctx - context.Context for the request
resp - proto.Message to transform

Returns:

proto.Message - the same response unchanged

func EncodeHttpBody

func EncodeHttpBody(ctx context.Context, w http.ResponseWriter, resp *httpbody.HttpBody) error

EncodeHttpBody encodes an httpbody.HttpBody into an HTTP response. Sets Content-Type from the HttpBody and status code to 200 OK.

Parameters:

ctx - context.Context for the request
w - http.ResponseWriter to write the response
resp - *httpbody.HttpBody to encode

Returns:

error - if writing fails

func EncodeHttpResponse

func EncodeHttpResponse(ctx context.Context, w http.ResponseWriter, resp *rpchttp.HttpResponse) error

EncodeHttpResponse encodes an rpchttp.HttpResponse into an HTTP response. Sets headers, status code and body from the HttpResponse.

Parameters:

ctx - context.Context for the request
w - http.ResponseWriter to write the response
resp - *rpchttp.HttpResponse to encode

Returns:

error - if writing fails

func EncodeResponse

func EncodeResponse(ctx context.Context, w http.ResponseWriter, resp proto.Message, marshalOptions protojson.MarshalOptions) error

EncodeResponse encodes a protobuf message as JSON into an HTTP response. Sets Content-Type to application/json and status code to 200 OK.

Parameters:

ctx - context.Context for the request
w - http.ResponseWriter to write the response
resp - proto.Message to encode
marshalOptions - protojson.MarshalOptions for JSON encoding

Returns:

error - if encoding or writing fails

func FormFromPath

func FormFromPath(r *http.Request, keys ...string) url.Values

FormFromPath extracts specified key-value pairs from HTTP request path parameters and constructs them into url.Values format.

Parameters:

r: HTTP request object used to retrieve path parameters
keys: list of path parameter key names to extract

Returns:

url.Values: form data containing specified path parameter key-value pairs,
            returns nil if keys is nil

func GetBool

func GetBool(form url.Values, key string) (bool, error)

GetBool retrieves a boolean value from URL form values. Returns false if key doesn't exist without error.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

bool - parsed boolean value
error - parsing error if any

func GetBoolPtr

func GetBoolPtr(form url.Values, key string) (*bool, error)

GetBoolPtr retrieves a boolean value from form and returns its pointer.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*bool - pointer to parsed value
error - parsing error if any

func GetBoolSlice

func GetBoolSlice(form url.Values, key string) ([]bool, error)

GetBoolSlice retrieves a slice of boolean values from URL form values.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]bool - slice of parsed values
error - parsing error if any

func GetBoolValue

func GetBoolValue(form url.Values, key string) (*wrapperspb.BoolValue, error)

GetBoolValue retrieves a boolean value wrapped in protobuf BoolValue.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*wrapperspb.BoolValue - protobuf wrapped boolean
error - parsing error if any

func GetBoolValueSlice

func GetBoolValueSlice(form url.Values, key string) ([]*wrapperspb.BoolValue, error)

GetBoolValueSlice retrieves a slice of boolean values wrapped in protobuf BoolValue.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]*wrapperspb.BoolValue - slice of protobuf wrapped booleans
error - parsing error if any

func GetFloat

func GetFloat[Float constraints.Float](form url.Values, key string) (Float, error)

GetFloat retrieves and parses a floating-point value from URL form values. If the key doesn't exist, returns zero value of the generic type Float. Uses ParseFloat with 64 bit size for conversion.

Parameters:

form - the URL form values
key - the key to look up in form values

Returns:

Float - the parsed floating-point value
error - if parsing fails

func GetFloat32

func GetFloat32(form url.Values, key string) (float32, error)

GetFloat32 retrieves a float32 value from URL form values.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

float32 - parsed floating-point value
error - parsing error if any

func GetFloat32Ptr

func GetFloat32Ptr(form url.Values, key string) (*float32, error)

GetFloat32Ptr retrieves a float32 value from form and returns its pointer.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*float32 - pointer to parsed value
error - parsing error if any

func GetFloat32Slice

func GetFloat32Slice(form url.Values, key string) ([]float32, error)

GetFloat32Slice retrieves a slice of float32 values from URL form values.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]float32 - slice of parsed values
error - parsing error if any

func GetFloat32Value

func GetFloat32Value(form url.Values, key string) (*wrapperspb.FloatValue, error)

GetFloat32Value retrieves a float32 value wrapped in protobuf FloatValue.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*wrapperspb.FloatValue - protobuf wrapped float32
error - parsing error if any

func GetFloat32ValueSlice

func GetFloat32ValueSlice(form url.Values, key string) ([]*wrapperspb.FloatValue, error)

GetFloat32ValueSlice retrieves a slice of float32 values wrapped in protobuf FloatValue.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]*wrapperspb.FloatValue - slice of protobuf wrapped float32s
error - parsing error if any

func GetFloat64

func GetFloat64(form url.Values, key string) (float64, error)

GetFloat64 retrieves a float64 value from URL form values.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

float64 - parsed floating-point value
error - parsing error if any

func GetFloat64Ptr

func GetFloat64Ptr(form url.Values, key string) (*float64, error)

GetFloat64Ptr retrieves a float64 value from form and returns its pointer.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*float64 - pointer to parsed value
error - parsing error if any

func GetFloat64Slice

func GetFloat64Slice(form url.Values, key string) ([]float64, error)

GetFloat64Slice retrieves a slice of float64 values from URL form values.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]float64 - slice of parsed values
error - parsing error if any

func GetFloat64Value

func GetFloat64Value(form url.Values, key string) (*wrapperspb.DoubleValue, error)

GetFloat64Value retrieves a float64 value wrapped in protobuf DoubleValue.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*wrapperspb.DoubleValue - protobuf wrapped float64
error - parsing error if any

func GetFloat64ValueSlice

func GetFloat64ValueSlice(form url.Values, key string) ([]*wrapperspb.DoubleValue, error)

GetFloat64ValueSlice retrieves a slice of float64 values wrapped in protobuf DoubleValue.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]*wrapperspb.DoubleValue - slice of protobuf wrapped float64s
error - parsing error if any

func GetFloatPtr

func GetFloatPtr[Float constraints.Float](form url.Values, key string) (*Float, error)

GetFloatPtr retrieves and parses a floating-point value from URL form values, returning a pointer to the value. If the key doesn't exist, returns zero value of the generic type Float.

Parameters:

form - the URL form values
key - the key to look up in form values

Returns:

*Float - pointer to the parsed floating-point value
error - if parsing fails

func GetFloatSlice

func GetFloatSlice[Float constraints.Float](form url.Values, key string) ([]Float, error)

GetFloatSlice retrieves and parses a slice of floating-point numbers from URL form values. If the key doesn't exist, returns nil slice. Uses ParseFloatSlice with 64 bit size for conversion.

Parameters:

form - the URL form values
key - the key to look up in form values

Returns:

[]Float - the parsed float slice
error - if any element fails to parse

func GetInt

func GetInt[Signed constraints.Signed](form url.Values, key string) (Signed, error)

GetInt retrieves and parses a signed integer value from URL form values. If the key doesn't exist, returns zero value of the generic type Signed. Uses ParseInt with base 10 and 64 bit size for conversion.

Parameters:

form - the URL form values
key - the key to look up in form values

Returns:

Signed - the parsed integer value
error - if parsing fails

func GetInt32

func GetInt32(form url.Values, key string) (int32, error)

GetInt32 retrieves an int32 value from URL form values.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

int32 - parsed integer value
error - parsing error if any

func GetInt32Ptr

func GetInt32Ptr(form url.Values, key string) (*int32, error)

GetInt32Ptr retrieves an int32 value from form and returns its pointer.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*int32 - pointer to parsed value
error - parsing error if any

func GetInt32Slice

func GetInt32Slice(form url.Values, key string) ([]int32, error)

GetInt32Slice retrieves a slice of int32 values from the given url.Values by key.

Parameters:

  • form: url.Values containing the form data to retrieve values from
  • key: string key to look up in the form values

Returns:

  • []int32: slice of int32 values if successful
  • error: any error that occurred during parsing or retrieval

func GetInt32Value

func GetInt32Value(form url.Values, key string) (*wrapperspb.Int32Value, error)

GetInt32Value retrieves an int32 value wrapped in protobuf Int32Value.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*wrapperspb.Int32Value - protobuf wrapped int32
error - parsing error if any

func GetInt32ValueSlice

func GetInt32ValueSlice(form url.Values, key string) ([]*wrapperspb.Int32Value, error)

GetInt32ValueSlice retrieves a slice of int32 values wrapped in protobuf Int32Value.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]*wrapperspb.Int32Value - slice of protobuf wrapped int32s
error - parsing error if any

func GetInt64

func GetInt64(form url.Values, key string) (int64, error)

GetInt64 retrieves an int64 value from URL form values.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

int64 - parsed integer value
error - parsing error if any

func GetInt64Ptr

func GetInt64Ptr(form url.Values, key string) (*int64, error)

GetInt64Ptr retrieves an int64 value from form and returns its pointer.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*int64 - pointer to parsed value
error - parsing error if any

func GetInt64Slice

func GetInt64Slice(form url.Values, key string) ([]int64, error)

GetInt64Slice retrieves a slice of int64 values from the given url.Values by the specified key.

Parameters:

  • form: The url.Values containing the form data to be parsed.
  • key: The key used to lookup the values in the form data.

Returns:

  • []int64: The parsed slice of int64 values if successful.
  • error: An error if the parsing fails or if the key is not found.

func GetInt64Value

func GetInt64Value(form url.Values, key string) (*wrapperspb.Int64Value, error)

GetInt64Value retrieves an int64 value wrapped in protobuf Int64Value.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*wrapperspb.Int64Value - protobuf wrapped int64
error - parsing error if any

func GetInt64ValueSlice

func GetInt64ValueSlice(form url.Values, key string) ([]*wrapperspb.Int64Value, error)

GetInt64ValueSlice retrieves a slice of int64 values wrapped in protobuf Int64Value.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]*wrapperspb.Int64Value - slice of protobuf wrapped int64s
error - parsing error if any

func GetIntPtr

func GetIntPtr[Signed constraints.Signed](form url.Values, key string) (*Signed, error)

GetIntPtr retrieves and parses a signed integer value from URL form values, returning a pointer to the value. If the key doesn't exist, returns zero value of the generic type Signed.

Parameters:

form - the URL form values
key - the key to look up in form values

Returns:

*Signed - pointer to the parsed integer value
error - if parsing fails

func GetIntSlice

func GetIntSlice[Signed constraints.Signed](form url.Values, key string) ([]Signed, error)

GetIntSlice retrieves and parses a slice of signed integers from URL form values. If the key doesn't exist, returns nil slice. Uses ParseIntSlice with base 10 and 64 bit size for conversion.

Parameters:

form - the URL form values
key - the key to look up in form values

Returns:

[]Signed - the parsed integer slice
error - if any element fails to parse

func GetUint

func GetUint[Unsigned constraints.Unsigned](form url.Values, key string) (Unsigned, error)

GetUint retrieves and parses an unsigned integer value from URL form values. If the key doesn't exist, returns zero value of the generic type Unsigned. Uses ParseUint with base 10 and 64 bit size for conversion.

Parameters:

form - the URL form values
key - the key to look up in form values

Returns:

Unsigned - the parsed unsigned integer value
error - if parsing fails

func GetUint32

func GetUint32(form url.Values, key string) (uint32, error)

GetUint32 retrieves a uint32 value from URL form values.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

uint32 - parsed unsigned integer value
error - parsing error if any

func GetUint32Ptr

func GetUint32Ptr(form url.Values, key string) (*uint32, error)

GetUint32Ptr retrieves a uint32 value from form and returns its pointer.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*uint32 - pointer to parsed value
error - parsing error if any

func GetUint32Slice

func GetUint32Slice(form url.Values, key string) ([]uint32, error)

GetUint32Slice retrieves a slice of uint32 values from the given url.Values by key.

Parameters:

  • form: url.Values containing the form data to parse
  • key: string key to look up in the form values

Returns:

  • []uint32: slice of parsed uint32 values if successful
  • error: any error that occurred during parsing, such as invalid format

func GetUint32Value

func GetUint32Value(form url.Values, key string) (*wrapperspb.UInt32Value, error)

GetUint32Value retrieves a uint32 value wrapped in protobuf UInt32Value.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*wrapperspb.UInt32Value - protobuf wrapped uint32
error - parsing error if any

func GetUint32ValueSlice

func GetUint32ValueSlice(form url.Values, key string) ([]*wrapperspb.UInt32Value, error)

GetUint32ValueSlice retrieves a slice of uint32 values wrapped in protobuf UInt32Value.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]*wrapperspb.UInt32Value - slice of protobuf wrapped uint32s
error - parsing error if any

func GetUint64

func GetUint64(form url.Values, key string) (uint64, error)

GetUint64 retrieves a uint64 value from URL form values.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

uint64 - parsed unsigned integer value
error - parsing error if any

func GetUint64Ptr

func GetUint64Ptr(form url.Values, key string) (*uint64, error)

GetUint64Ptr retrieves a uint64 value from form and returns its pointer.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*uint64 - pointer to parsed value
error - parsing error if any

func GetUint64Slice

func GetUint64Slice(form url.Values, key string) ([]uint64, error)

GetUint64Slice parses a URL form value as a slice of uint64 integers.

Parameters:

  • form: The URL form values containing the target key-value pairs.
  • key: The form field key whose value should be parsed as a []uint64.

Returns:

  • []uint64: The parsed slice of uint64 integers if successful.
  • error: An error if the parsing fails (e.g., invalid format or empty key).

Note: This is a convenience wrapper around GetUintSlice[uint64] for uint64-specific parsing.

func GetUint64Value

func GetUint64Value(form url.Values, key string) (*wrapperspb.UInt64Value, error)

GetUint64Value retrieves a uint64 value wrapped in protobuf UInt64Value.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

*wrapperspb.UInt64Value - protobuf wrapped uint64
error - parsing error if any

func GetUint64ValueSlice

func GetUint64ValueSlice(form url.Values, key string) ([]*wrapperspb.UInt64Value, error)

GetUint64ValueSlice retrieves a slice of uint64 values wrapped in protobuf UInt64Value.

Parameters:

form - URL form values containing the data
key - form field key to retrieve

Returns:

[]*wrapperspb.UInt64Value - slice of protobuf wrapped uint64s
error - parsing error if any

func GetUintPtr

func GetUintPtr[Unsigned constraints.Unsigned](form url.Values, key string) (*Unsigned, error)

GetUintPtr retrieves and parses an unsigned integer value from URL form values, returning a pointer to the value. If the key doesn't exist, returns zero value of the generic type Unsigned.

Parameters:

form - the URL form values
key - the key to look up in form values

Returns:

*Unsigned - pointer to the parsed unsigned integer value
error - if parsing fails

func GetUintSlice

func GetUintSlice[Unsigned constraints.Unsigned](form url.Values, key string) ([]Unsigned, error)

GetUintSlice retrieves and parses a slice of unsigned integers from URL form values. If the key doesn't exist, returns nil slice. Uses ParseUintSlice with base 10 and 64 bit size for conversion.

Parameters:

form - the URL form values
key - the key to look up in form values

Returns:

[]Unsigned - the parsed unsigned integer slice
error - if any element fails to parse

func ParseBool

func ParseBool(s string) (bool, error)

ParseBool converts a string to a boolean value. It wraps strconv.ParseBool to provide the same functionality.

Parameters:

s - the string to be parsed into a boolean

Returns:

bool - the parsed boolean value
error - if parsing fails

func ParseBoolSlice

func ParseBoolSlice(s []string) ([]bool, error)

ParseBoolSlice converts a slice of strings to a slice of booleans. Returns nil if the input slice is nil.

Parameters:

s - the string slice to be parsed

Returns:

[]bool - the parsed boolean slice
error - if any element fails to parse

func ParseBytesSlice

func ParseBytesSlice(s []string) [][]byte

ParseBytesSlice converts a slice of strings to a slice of byte slices. Returns nil if the input slice is nil.

Parameters:

s - the string slice to be converted

Returns:

[][]byte - the resulting byte slice

func ParseFloat

func ParseFloat[Float constraints.Float](s string, bitSize int) (Float, error)

ParseFloat converts a string to a floating-point number of the specified type. It wraps strconv.ParseFloat and converts the result to the generic type Float.

Parameters:

s - the string to be parsed
bitSize - the size of the float (32 or 64)

Returns:

Float - the parsed floating-point value
error - if parsing fails

func ParseFloatSlice

func ParseFloatSlice[Float constraints.Float](s []string, bitSize int) ([]Float, error)

ParseFloatSlice converts a slice of strings to a slice of floating-point numbers. Returns nil if the input slice is nil.

Parameters:

s - the string slice to be parsed
bitSize - the size of the float (32 or 64)

Returns:

[]Float - the parsed float slice
error - if any element fails to parse

func ParseInt

func ParseInt[Signed constraints.Signed](s string, base int, bitSize int) (Signed, error)

ParseInt converts a string to a signed integer of the specified type. It wraps strconv.ParseInt and converts the result to the generic type Signed.

Parameters:

s - the string to be parsed
base - the base for conversion (0, 2 to 36)
bitSize - the size of the integer (0, 8, 16, 32, 64)

Returns:

Signed - the parsed integer value
error - if parsing fails

func ParseIntSlice

func ParseIntSlice[Signed constraints.Signed](s []string, base int, bitSize int) ([]Signed, error)

ParseIntSlice converts a slice of strings to a slice of signed integers. Returns nil if the input slice is nil.

Parameters:

s - the string slice to be parsed
base - the base for conversion (0, 2 to 36)
bitSize - the size of the integer (0, 8, 16, 32, 64)

Returns:

[]Signed - the parsed integer slice
error - if any element fails to parse

func ParseUint

func ParseUint[Unsigned constraints.Unsigned](s string, base int, bitSize int) (Unsigned, error)

ParseUint converts a string to an unsigned integer of the specified type. It wraps strconv.ParseUint and converts the result to the generic type Unsigned.

Parameters:

s - the string to be parsed
base - the base for conversion (0, 2 to 36)
bitSize - the size of the integer (0, 8, 16, 32, 64)

Returns:

Unsigned - the parsed unsigned integer value
error - if parsing fails

func ParseUintSlice

func ParseUintSlice[Unsigned constraints.Unsigned](s []string, base int, bitSize int) ([]Unsigned, error)

ParseUintSlice converts a slice of strings to a slice of unsigned integers. Returns nil if the input slice is nil.

Parameters:

s - the string slice to be parsed
base - the base for conversion (0, 2 to 36)
bitSize - the size of the integer (0, 8, 16, 32, 64)

Returns:

[]Unsigned - the parsed unsigned integer slice
error - if any element fails to parse

func ValidateRequest

func ValidateRequest(ctx context.Context, req proto.Message, fast bool, callback OnValidationErrCallback) (err error)

ValidateRequest validates the request parameters Parameters:

  • ctx: Context object
  • req: Proto.Message to validate
  • fast: Whether to perform fast validation (skip deep validation)
  • callback: Callback function for validation errors

Returns:

  • error: Validation error if any

Behavior:

Based on fast parameter:
- fast=true: Attempts to call Validate() or Validate(false)
- fast=false: Attempts to call ValidateAll() or Validate(true) or Validate()
If validation fails and callback is provided, invokes the callback

func WrapBoolSlice

func WrapBoolSlice(s []bool) []*wrapperspb.BoolValue

WrapBoolSlice converts a slice of primitive bool values into a slice of BoolValue wrappers. This is useful for protobuf message fields that require wrapper types instead of primitive types.

Parameters:

s []bool - the input slice of boolean values. If nil, the function returns nil.

Returns:

[]*wrapperspb.BoolValue - a new slice containing wrapped boolean values.
The returned slice will be nil if the input is nil, otherwise it will contain
a BoolValue wrapper for each element in the input slice.

func WrapFloat32Slice

func WrapFloat32Slice(s []float32) []*wrapperspb.FloatValue

WrapFloat32Slice converts a slice of float32 values into a slice of FloatValue wrappers. This is typically used for protobuf message construction where primitive types need to be wrapped.

Parameters:

s []float32 - The input slice of float32 values. If nil, the function returns nil.

Returns:

[]*wrapperspb.FloatValue - A new slice containing wrapped FloatValue pointers corresponding
                           to the input values. Returns nil if input is nil.

func WrapFloat64Slice

func WrapFloat64Slice(s []float64) []*wrapperspb.DoubleValue

WrapFloat64Slice converts a slice of float64 values into a slice of DoubleValue wrappers. This is useful for protobuf message fields that require wrapped double values instead of plain float64.

Parameters:

  • s: The input slice of float64 values. If nil, the function returns nil.

Returns:

  • []*wrapperspb.DoubleValue: A new slice containing DoubleValue wrappers for each input value. Returns nil if the input slice is nil.

func WrapInt32Slice

func WrapInt32Slice(s []int32) []*wrapperspb.Int32Value

WrapInt32Slice converts a slice of int32 values into a slice of Int32Value wrappers. This is typically used for protobuf message construction where primitive types need to be wrapped.

Parameters:

  • s: The input slice of int32 values. If nil, the function returns nil.

Returns:

  • []*wrapperspb.Int32Value: A new slice containing Int32Value wrappers for each input value. Returns nil if the input slice is nil.

func WrapInt64Slice

func WrapInt64Slice(s []int64) []*wrapperspb.Int64Value

WrapInt64Slice converts a slice of int64 values into a slice of Int64Value wrappers. This is typically used for protobuf message construction where wrapper types are required.

Parameters:

  • s: The input slice of int64 values. If nil, the function returns nil.

Returns:

  • []*wrapperspb.Int64Value: A new slice containing Int64Value wrappers for each input value, or nil if the input slice was nil.

func WrapStringSlice

func WrapStringSlice(s []string) []*wrapperspb.StringValue

WrapStringSlice converts a slice of string values into a slice of StringValue wrappers.

Parameters:

  • s: The input string slice to be wrapped. If nil, the function returns nil.

Returns:

  • []*wrapperspb.StringValue: A new slice containing StringValue wrappers for each input string, or nil if the input was nil.

func WrapUint32Slice

func WrapUint32Slice(s []uint32) []*wrapperspb.UInt32Value

WrapUint32Slice converts a slice of uint32 values into a slice of protocol buffer UInt32Value wrappers. This is useful for converting native Go types to their corresponding protobuf wrapper types for serialization.

Parameters:

  • s: The input slice of uint32 values. If nil, the function returns nil.

Returns:

  • []*wrapperspb.UInt32Value: A new slice containing protobuf UInt32Value wrappers for each uint32 value in the input. Returns nil if the input slice is nil.

func WrapUint64Slice

func WrapUint64Slice(s []uint64) []*wrapperspb.UInt64Value

WrapUint64Slice converts a slice of uint64 values into a slice of UInt64Value wrappers. This is typically used for protobuf message construction where wrapper types are required.

Parameters:

  • s: The input slice of uint64 values. If nil, the function returns nil.

Returns:

  • []*wrapperspb.UInt64Value: A new slice containing wrapped UInt64Value pointers. Returns nil if the input slice is nil.

Types

type ErrorEncoder

type ErrorEncoder func(ctx context.Context, err error, w http.ResponseWriter)

ErrorEncoder defines a function type for encoding errors into HTTP responses. Implementations should write the error to the provided http.ResponseWriter.

type FormGetter

type FormGetter[T any] func(form url.Values, key string) (T, error)

FormGetter defines a generic function type for form data retrieval Parameters:

  • form: Form data
  • key: Form field key

Returns:

  • T: Retrieved value
  • error: Retrieval error if any

type MiddlewareFunc

type MiddlewareFunc func(http.Handler) http.Handler

MiddlewareFunc is a function which receives an http.Handler and returns another http.Handler. Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc.

type OnValidationErrCallback

type OnValidationErrCallback func(ctx context.Context, err error)

OnValidationErrCallback defines a callback function type for validation errors This callback will be invoked when ValidateRequest encounters a validation error

type Option

type Option func(o *options)

Option defines a function type for modifying options

func WithErrorEncoder

func WithErrorEncoder(encoder ErrorEncoder) Option

WithErrorEncoder configures custom error encoder

func WithFailFast

func WithFailFast() Option

WithFailFast enables fail-fast mode

func WithMarshalOptions

func WithMarshalOptions(opts protojson.MarshalOptions) Option

WithMarshalOptions sets protojson marshal options

func WithMiddlewares

func WithMiddlewares(middlewares ...MiddlewareFunc) Option

WithMiddlewares appends middlewares to the chain

func WithOnValidationErrCallback

func WithOnValidationErrCallback(onValidationErrCallback OnValidationErrCallback) Option

WithOnValidationErrCallback sets validation error callback

func WithResponseTransformer

func WithResponseTransformer(transformer ResponseTransformer) Option

WithResponseTransformer sets response transformer

func WithUnmarshalOptions

func WithUnmarshalOptions(opts protojson.UnmarshalOptions) Option

WithUnmarshalOptions sets protojson unmarshal options

type Options

type Options interface {
	// Returns protojson unmarshal options
	UnmarshalOptions() protojson.UnmarshalOptions

	// Returns protojson marshal options
	MarshalOptions() protojson.MarshalOptions

	// Gets the error encoder function
	ErrorEncoder() ErrorEncoder

	// Gets the response transformer
	ResponseTransformer() ResponseTransformer

	// Returns list of middlewares
	Middlewares() []MiddlewareFunc

	// Indicates if fail-fast mode is enabled
	ShouldFailFast() bool

	// Gets validation error callback
	OnValidationErrCallback() OnValidationErrCallback
}

Options interface defines methods to access all configurable options

func NewOptions

func NewOptions(opts ...Option) Options

NewOptions creates new Options instance with defaults and applies provided options

type ResponseTransformer

type ResponseTransformer func(ctx context.Context, resp proto.Message) proto.Message

ResponseTransformer defines a function type for transforming protobuf responses before encoding. Can be used to modify or wrap responses.

Directories

Path Synopsis
cmd
example
internal
gen
middleware

Jump to

Keyboard shortcuts

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