Skip to content
Snippets Groups Projects
Volker Schukai's avatar
59f7404d
History

HTTP Negotiation

Installation

go get gitlab.schukai.com/oss/libraries/go/network/http-negotiation

Note: This library uses Go Modules to manage dependencies.

What do this library?

This library provides a simple way to negotiate the content type of HTTP request.

It supports:

Usage

Content Negotiation

With the Type function you can negotiate the content type of HTTP request.

package main

import (
	"net/http"
	"gitlab.schukai.com/oss/libraries/go/network/http-negotiation"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {
	n := negotiation.New(r.Header)

	if n.Type("application/json") == "application/json" {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{"message": "Hello World!"}`))
		return
	}

}

Accept Content Type

With the ContentType function you can negotiate the content type of HTTP request.

package main

import (
	"net/http"
	"gitlab.schukai.com/oss/libraries/go/network/http-negotiation"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {
	n := negotiation.New(r.Header)

	if n.ContentType("application/json") != "" {
		// ...
	}

}

Language Negotiation

With the Language function you can negotiate the language of HTTP request.

package main

import (
	"net/http"
	"gitlab.schukai.com/oss/libraries/go/network/http-negotiation"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {
	n := negotiation.New(r.Header)

	if n.Language("en-GB", "en") != "en" {
		// ...
	}

}

Charset Negotiation

With the Charset function you can negotiate the charset of HTTP request.

package main

import (
	"net/http"
	"gitlab.schukai.com/oss/libraries/go/network/http-negotiation"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {
	n := negotiation.New(r.Header)

	if n.Charset("utf-8", "iso-8859-1") != "utf-8" {
		// ...
	}

}

Encoding Negotiation

With the Encoding function you can negotiate the encoding of HTTP request.

package main

import (
	"net/http"
	"gitlab.schukai.com/oss/libraries/go/network/http-negotiation"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {
	n := negotiation.New(r.Header)

	if n.Encoding("gzip", "deflate") != "gzip" {
		// ...
	}

}

Changelog

1.1.0

  • Add ContentType function

1.0.0

  • Initial release

Contributing

Merge requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

AGPL-3.0