Skip to content

Commit

Permalink
feat: initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
dunglas committed Aug 26, 2020
0 parents commit 27431fa
Show file tree
Hide file tree
Showing 45 changed files with 2,884 additions and 0 deletions.
76 changes: 76 additions & 0 deletions .github/CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Contributor Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, ethnicity, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at contact+coc@mercure.rocks. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
1 change: 1 addition & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
github: dunglas
23 changes: 23 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!--
The commit message must follow the [Conventional Commits specification](https://www.conventionalcommits.org/).
The following types are allowed:
* `fix`: bug fix
* `feat`: new feature
* `docs`: change in the documentation
* `test`: test-related change
* `perf`: performance optimization
* `ci`: CI-related change
Examples:
fix: Fix something
feat: Introduce X
feat!: Introduce Y, BC break
docs: Add docs for X
spec: Z disambiguation
-->
41 changes: 41 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: CI

on:
push:
pull_request:

env:
GO111MODULE: 'on'

jobs:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@master
- name: Lint Go Code
uses: docker://golangci/golangci-lint:latest
with:
args: golangci-lint run ./...

test:
name: Test
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@master
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: '1.15'
- name: Install project dependencies
run: go get
- name: Test
run: go test -race -covermode atomic -coverprofile=profile.cov ./...
- name: Upload coverage results
env:
COVERALLS_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
GO111MODULE=off go get github.com/mattn/goveralls
$(go env GOPATH)/bin/goveralls -coverprofile=profile.cov -service=github
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "structured-field-tests"]
path = structured-field-tests
url = https://github.com/httpwg/structured-field-tests
14 changes: 14 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
run:
tests: true

linters:
enable-all: true
disable:
- testpackage
- godox

issues:
exclude-rules:
- path: _test\.go
linters:
- funlen
27 changes: 27 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Copyright (c) 2020 Kévin Dunglas. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# httpsfv: Structured Field Values for HTTP in Go

This [Go (golang)](https://golang.org) library implements parsing and serialization for [Structured Field Values for HTTP](https://httpwg.org/http-extensions/draft-ietf-httpbis-header-structure.html).

[![PkgGoDev](https://pkg.go.dev/badge/github.com/dunglas/httpsfv)](https://pkg.go.dev/github.com/dunglas/httpsfv)
![CI](https://github.com/dunglas/httpsfv/workflows/CI/badge.svg)
[![Coverage Status](https://coveralls.io/repos/github/dunglas/httpsfv/badge.svg?branch=master)](https://coveralls.io/github/dunglas/httpsfv?branch=master)
[![Go Report Card](https://goreportcard.com/badge/github.com/dunglas/httpsfv)](https://goreportcard.com/report/github.com/dunglas/httpsfv)

## Features

* Implements the latest version (19) of the Internet-Draft
* Compliant with [the official test suite](https://github.com/httpwg/structured-field-tests)
* Unit tested
* Strongly-typed
* Fast (see [the benchmark](httpwg_test.go))

## Docs

[Browse the documentation on Go.dev](https://pkg.go.dev/dunglas/httpsfv).

## Credits

Created by [Kévin Dunglas](https://dunglas.fr). Sponsored by [Les-Tilleuls.coop](https://les-tilleuls.coop).
102 changes: 102 additions & 0 deletions bareitem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package httpsfv

import (
"errors"
"fmt"
"reflect"
"strings"
)

// ErrInvalidBareItem is returned when a bare item is invalid.
var ErrInvalidBareItem = errors.New(
"invalid bare item type (allowed types are bool, string, int64, float64, []byte and Token)",
)

// assertBareItem asserts that v is a valid bare item
// according to https://httpwg.org/http-extensions/draft-ietf-httpbis-header-structure.html#item.
//
// v can be either:
//
// * an integer (Section 3.3.1.)
// * a decimal (Section 3.3.2.)
// * a string (Section 3.3.3.)
// * a token (Section 3.3.4.)
// * a byte sequence (Section 3.3.5.)
// * a boolean (Section 3.3.6.)
func assertBareItem(v interface{}) {
switch v.(type) {
case bool,
string,
int,
int8,
int16,
int32,
int64,
uint,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
[]byte,
Token:
return
default:
panic(fmt.Errorf("%w: got %s", ErrInvalidBareItem, reflect.TypeOf(v)))
}
}

// marshalBareItem serializes as defined in
// https://httpwg.org/http-extensions/draft-ietf-httpbis-header-structure.html#ser-bare-item.
func marshalBareItem(b *strings.Builder, v interface{}) error {
switch v := v.(type) {
case bool:
return marshalBoolean(b, v)
case string:
return marshalString(b, v)
case int64:
return marshalInteger(b, v)
case int, int8, int16, int32:
return marshalInteger(b, reflect.ValueOf(v).Int())
case uint, uint8, uint16, uint32, uint64:
// Casting an uint64 to an int64 is possible because the maximum allowed value is 999,999,999,999,999
return marshalInteger(b, int64(reflect.ValueOf(v).Uint()))
case float32, float64:
return marshalDecimal(b, v.(float64))
case []byte:
return marshalBinary(b, v)
case Token:
return v.marshalSFV(b)
default:
panic(ErrInvalidBareItem)
}
}

// parseBareItem parses as defined in
// https://httpwg.org/http-extensions/draft-ietf-httpbis-header-structure.html#parse-bare-item.
func parseBareItem(s *scanner) (interface{}, error) {
if s.eof() {
return nil, &UnmarshalError{s.off, ErrUnexpectedEndOfString}
}

c := s.data[s.off]
switch c {
case '"':
return parseString(s)
case '?':
return parseBoolean(s)
case '*':
return parseToken(s)
case ':':
return parseBinary(s)
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
return parseNumber(s)
default:
if isAlpha(c) {
return parseToken(s)
}

return nil, &UnmarshalError{s.off, ErrUnrecognizedCharacter}
}
}
61 changes: 61 additions & 0 deletions bareitem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package httpsfv

import (
"reflect"
"strings"
"testing"
"time"
)

func TestParseBareItem(t *testing.T) {
data := []struct {
in string
out interface{}
err bool
}{
{"?1", true, false},
{"?0", false, false},
{"22", int64(22), false},
{"-2.2", -2.2, false},
{`"foo"`, "foo", false},
{"abc", Token("abc"), false},
{"*abc", Token("*abc"), false},
{":YWJj:", []byte("abc"), false},
{"", nil, true},
{"~", nil, true},
}

for _, d := range data {
s := &scanner{data: d.in}

i, err := parseBareItem(s)
if d.err && err == nil {
t.Errorf("parseBareItem(%s): error expected", d.in)
}

if !d.err && !reflect.DeepEqual(d.out, i) {
t.Errorf("parseBareItem(%s) = %v, %v; %v, <nil> expected", d.in, i, err, d.out)
}
}
}

func TestMarshalBareItem(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()

var b strings.Builder
_ = marshalBareItem(&b, time.Second)
}

func TestAssertBareItem(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()

assertBareItem(time.Second)
}

0 comments on commit 27431fa

Please sign in to comment.