A Go library for encoding structs into Header fields.

go-httpheader

go-httpheader is a Go library for encoding structs into Header fields.

Build Status Coverage Status Go Report Card GoDoc

install

go get -u github.com/mozillazg/go-httpheader

usage

package main

import (
	"fmt"
	"net/http"

	"github.com/mozillazg/go-httpheader"
)

type Options struct {
	hide         string
	ContentType  string `header:"Content-Type"`
	Length       int
	XArray       []string `header:"X-Array"`
	TestHide     string   `header:"-"`
	IgnoreEmpty  string   `header:"X-Empty,omitempty"`
	IgnoreEmptyN string   `header:"X-Empty-N,omitempty"`
	CustomHeader http.Header
}

func main() {
	opt := Options{
		hide:         "hide",
		ContentType:  "application/json",
		Length:       2,
		XArray:       []string{"test1", "test2"},
		TestHide:     "hide",
		IgnoreEmptyN: "n",
		CustomHeader: http.Header{
			"X-Test-1": []string{"233"},
			"X-Test-2": []string{"666"},
		},
	}
	h, _ := httpheader.Header(opt)
	fmt.Printf("%#v", h)
	// h:
	// http.Header{
	//	"X-Test-1":     []string{"233"},
	//	"X-Test-2":     []string{"666"},
	//	"Content-Type": []string{"application/json"},
	//	"Length":       []string{"2"},
	//	"X-Array":      []string{"test1", "test2"},
	//	"X-Empty-N":    []string{"n"},
	// }
	
	// decode
	var decode Options
	httpheader.Decode(h, &decode)
}
Similar Resources

Go module for encoding structs into URL query parameters

qs Package sonh/qs encodes structs into url.Values. Installation go get github.com/sonh/qs Usage import ( "github.com/sonh/qs" ) Package qs export

Jan 7, 2023

go-eexcel implements encoding and decoding of XLSX like encoding/json

go-eexcel go-eexcel implements encoding and decoding of XLSX like encoding/json Usage func ExampleMarshal() { type st struct { Name string `eexce

Dec 9, 2021

A codec for Go structs with support for chainable encoding/decoding hooks.

structool A codec for Go structs with support for chainable encoding/decoding hooks. Features Provide a uniform codec by combining mapstructure and st

Jan 15, 2022

K8s-go-structs - All k8s API Go structs

k8s-api go types Why? Its nice to have it all in a single package. . |-- pkg |

Jul 17, 2022

Go library for encoding native Go structures into generic map values.

wstructs origin: github.com/things-go/structs Go library for encoding native Go structures into generic map values. Installation Use go get. go ge

Jan 10, 2022

Library for scanning data from a database into Go structs and more

scany Overview Go favors simplicity, and it's pretty common to work with a database via driver directly without any ORM. It provides great control and

Jan 9, 2023

Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs.

go-attr Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs. This package provides user frien

Dec 16, 2022

A Go library for doing header-based OAuth over HTTP or HTTPS.

Installation goinstall github.com/alloy-d/goauth Usage import ( "github.com/alloy-d/goauth" "os" ) func someFuncThatDoesStuffWithOAuth() (er

Sep 2, 2020

GoLobby DotEnv is a lightweight package for loading dot env (.env) files into structs for Go projects

DotEnv GoLobby DotEnv is a lightweight package for loading dot env (.env) files into structs for Go projects Documentation Supported Versions It requi

Dec 30, 2022

Converts a database into gorm structs and RESTful api

gen The gen tool produces a CRUD (Create, read, update and delete) REST api project template from a given database. The gen tool will connect to the d

Dec 28, 2022

Envopts - Provides a code generator for turning env structs into functional options

envopts Provides a code generator to turn structs annotated for the popular env

Jan 10, 2022

A fast, easy-of-use and dependency free custom mapping from .csv data into Golang structs

csvparser This package provides a fast and easy-of-use custom mapping from .csv data into Golang structs. Index Pre-requisites Installation Examples C

Nov 14, 2022

Automatically sets up command line flags based on struct fields and tags.

Automatically sets up command line flags based on struct fields and tags.

Commandeer Commandeer sets up command line flags based on struct fields and tags. Do you... like to develop Go apps as libraries with tiny main packag

Dec 1, 2022

goconfig uses a struct as input and populates the fields of this struct with parameters from command line, environment variables and configuration file.

goconfig goconfig uses a struct as input and populates the fields of this struct with parameters from command line, environment variables and configur

Dec 15, 2022

A distributed Configuration Center server that manages config in a container. The container is composed of fields (abstract layer includes: KV, LIST, DICT type). The Field contains basic datatypes (int, float, bool, string, list, dict).

A distributed Configuration Center server that manages config in a container. The container is composed of fields (abstract layer includes: KV, LIST, DICT type). The Field contains basic datatypes (int, float, bool, string, list, dict).

cassem config assembler from key-value pairs' container which include basic datatypes, such as int, string, float, bool, list, dict Features HTTP Rest

Nov 1, 2022

Go generator to copy values from type to type and fields from struct to struct. Copier without reflection.

Copygen is a command-line code generator that generates type-to-type and field-to-field struct code without adding any reflection or dependenc

Dec 29, 2022

Memory-Alignment: a tool to help analyze layout of fields in struct in memory

Memory-Alignment: a tool to help analyze layout of fields in struct in memory

Memory Alignment Memory-Alignment is a tool to help analyze layout of fields in struct in memory. Usage go get github.com/vearne/mem-aligin Example p

Oct 26, 2022

Kubectl-explore - A kubectl plugin for fuzzy-find fields to explain.

kubectl-explore This command is a better kubectl explain with the fuzzy-finder. What kubectl-explore finds fields associated with each supported API r

Dec 29, 2022

A simple golang api generator that stores struct fields in key/value based databases

Backgen A simple golang API generator that uses key/value based databases. It does not provide the database itself, only uses a interface to access se

Feb 4, 2022
Comments
  • fillValues case reflect.Int, reflect.Int64 provides error if header is not set

    fillValues case reflect.Int, reflect.Int64 provides error if header is not set

    fillValues function returns error if header with int value is not set.

    type ControllerPostParams struct { IntegerInJsonBody int json:"integerInJsonBody" validate:"min=1,max=100000" stringInHeader string header:"X-String,omitempty" }

    The error occurs in switch case case reflect.Int, reflect.Int64: var v int64 if v, err = strconv.ParseInt(value, 10, 64); err != nil { return err } sv.SetInt(v) return nil

    in case of an empty header value = "" strconv.ParseInt throws an error. I guess the same problem will occur in all number based switch cases from fillValues. I recommended to check if the header is set and otherwise exit the loop.

    I know you can also set header:"-" in the struct tags, but this can be easily forgotten. Additionally we initialise our params with defaults and httpheader.Decode overwrites everything if we do not set header:"-", which adds a lot of overhead in our stuct tags.

    My proposal: add an option that struct fields are left unharmed and are not overwritten with empty strings if no header is present.

  • Configure WhiteSource Bolt for GitHub

    Configure WhiteSource Bolt for GitHub

    Welcome to WhiteSource Bolt for GitHub! This is an onboarding PR to help you understand and configure settings before WhiteSource starts scanning your repository for security vulnerabilities.

    :vertical_traffic_light: WhiteSource Bolt for GitHub will start scanning your repository only once you merge this Pull Request. To disable WhiteSource Bolt for GitHub, simply close this Pull Request.


    What to Expect

    This PR contains a '.whitesource' configuration file which can be customized to your needs. If no changes were applied to this file, WhiteSource Bolt for GitHub will use the default configuration.

    Before merging this PR, Make sure the Issues tab is enabled. Once you merge this PR, WhiteSource Bolt for GitHub will scan your repository and create a GitHub Issue for every vulnerability detected in your repository.

    If you do not want a GitHub Issue to be created for each detected vulnerability, you can edit the '.whitesource' file and set the 'minSeverityLevel' parameter to 'NONE'.


    :question: Got questions? Check out WhiteSource Bolt for GitHub docs. If you need any further assistance then you can also request help here.

This library is a complementary library for Gorm (v2) which resolves the first available pool passed to it.

This library is a complementary library for Gorm (v2) which resolves the first available pool passed to it.

Feb 2, 2022
ORM-ish library for Go

We've moved! gorp is now officially maintained at: https://github.com/go-gorp/gorp This fork was created when the project was moved, and is provided f

Aug 23, 2022
A simple and fast Redis backed key-value store library for Go

store store is a data-store library for Go that provides a set of platform-independent interfaces to persist and retrieve data. Its primary goal is to

Sep 27, 2022
An orm library support nGQL for Golang

norm An ORM library support nGQL for Golang. Overview Build insert nGQL by struct / map (Support vertex, edge). Parse Nebula execute result to struct

Dec 1, 2022
The fantastic ORM library for Golang, aims to be developer friendly

GORM The fantastic ORM library for Golang, aims to be developer friendly. Overview Full-Featured ORM Associations (Has One, Has Many, Belongs To, Many

Nov 11, 2021
Mikorm - Library ORM Mikrotik API using go
Mikorm - Library ORM Mikrotik API using go

Mikrotik ORM (mikorm) Library Mikrotik API menggunakan ORM untuk mempermudah int

Jun 28, 2022
Traefik proxy plugin to extract HTTP header value and create a new header with extracted value

Copy header value Traefik plugin Traefik plugin that copies HTTP header value with format key1=value1; key2=value2 into a new header. Motivation for t

May 26, 2022
Krakend-jwt-header-rewriter - Kraken Plugin - JWT Header Rewriter

Kraken Plugin - JWT Header Rewriter 1 Plugin Configuration Name Desciption Defau

Feb 15, 2022
go-querystring is Go library for encoding structs into URL query strings.

go-querystring go-querystring is a Go library for encoding structs into URL query parameters. Usage import "github.com/google/go-querystring/query" go

Jan 9, 2023
Library for setting values to structs' fields from env, flags, files or default tag

Configuration is a library for injecting values recursively into structs - a convenient way of setting up a configuration object. Available features:

Dec 7, 2022