It's a typed HTTP server in Go, using generics that is expected to come out with 1.18

typed-http-server-in-go

This is a prototype of a typed HTTP server in Go via generics. Generics are scheduled to come out with Go 1.18, and you can play around with this example by using gotip.

I've written an entire blog post about my experimentation with this over here: Type-safe HTTP Servers in Go via Generics. The important part is that I think values you attach to a context should be typed, and this seemed to be the most reasonable approach to do so.

All middleware, encoding and decoding is done with type safe transforms that doesn't use any kind of reflection. The end result is that you can make an HTTP server that has HTTP endpoints looking like this:

type pingInput struct {
	Message string `json:"message"`
}

type pingOutput struct {
	Message string `json:"message"`
	Author middleware.UserID `json:"author"`
}

func pingHandler(ctx middleware.MyAppContext, in pingInput, req *http.Request) (*pingOutput, error) {
	ctx.Logger.WithField("user_id", ctx.UserID).Infof("Ping pong, message %s", in.Message)
	return &pingOutput{
		Message: fmt.Sprintf("PONG! Received %q", in.Message),
		Author: ctx.UserID,
	}, nil
}

With as little middleware as this:

func handlerWithMiddleware[In, Out any](handler typedhttp.Handler[middleware.MyAppContext,In,Out]) http.Handler {
	withAppContext := middleware.AttachUserAndLogger[context.Context,In,Out](handler)
	return httpjson.HandleTyped(withAppContext)
}

Running

Assuming you have gotip installed, you can run the entire thing by going to the directory cmd/server, then run gotip run server.go.

If you then pop over to a different terminal, you can run a call to the server like so:

curl localhost:8080/ping -XPOST --header "X-User-Id: 123" --data-binary '{"message": "Hello"}'

Structure

I've tried to group code into different packages, all of which resides in the directory pkg. I suspect most of it will be code local to your project, but I've added comments to all the files to denote whether I think it will be a project-specific thing or a library you can import.

But who knows, this is only a prototype, and whether we'll even use this format at all is not something I'm sure of.

License

Typically I'd say "Copyright © 2021 Jean Niklas L'orange", but I've waived those rights by applying a CC0 license to this repo. Do whatever you want with the code that resides here, although I don't mind a referral back to this repo or to my original blog post.

Similar Resources

A tool allows you to inspect in-bound and out-bound dns messages

A tool allows you to inspect in-bound and out-bound dns messages

This tool allows you to inspect in-bound and out-bound dns messages. You can use the tool to poison your own cache. Call ./dns-mitm to start the appli

Dec 11, 2021

Go-http-sleep: Delayed response http server, useful for testing various timeout issue for application running behind proxy

delayed response http server, useful for testing various timeout issue for application running behind proxy

Jan 22, 2022

An experimental package that rely on go generics to implement collection functions utilities

go-underscore go-underscore is a utility-belt library for Golang that provides s

Mar 20, 2022

Netkit - A type parameter(generics) net kit, support tcp kcp, customize packet

Netkit Netkit is a type parameter(generics) golang package Get Started Need Go i

Jan 12, 2022

Echo-server - An HTTP echo server designed for testing applications and proxies

echo-server An HTTP echo server designed for testing applications and proxies. R

Dec 20, 2022

“Dear Port80” is a zero-config TCP proxy server that hides SSH connection behind a HTTP server!

Dear Port80 About The Project: “Dear Port80” is a zero-config TCP proxy server that hides SSH connection behind a HTTP server! +---------------------

Jun 29, 2022

Cert bound sts server - Certificate Bound Tokens using Security Token Exchange Server (STS)

Cert bound sts server - Certificate Bound Tokens using Security Token Exchange Server (STS)

Certificate Bound Tokens using Security Token Exchange Server (STS) Sample demonstration of Certificate Bound Tokens acquired from a Security Token Ex

Jan 2, 2022

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

fasthttp Fast HTTP implementation for Go. Currently fasthttp is successfully used by VertaMedia in a production serving up to 200K rps from more than

Jan 5, 2023

Go HTTP tunnel is a reverse tunnel based on HTTP/2.

Go HTTP tunnel is a reverse tunnel based on HTTP/2. It enables you to share your localhost when you don't have a public IP.

Dec 28, 2022
Example of strongly typed go/graphql/typescript web application

go-gql-typescript-example Example of strongly typed go/graphql/typescript web application Overview This is an example web application. On the server i

May 27, 2022
For your server and all of its waifus <3

waifud A few tools to help me manage and run virtual machines across a homelab cluster. waifud was made for my own personal use and I do not expect it

Dec 12, 2022
Http-server - A HTTP server and can be accessed via TLS and non-TLS mode

Application server.go runs a HTTP/HTTPS server on the port 9090. It gives you 4

Feb 3, 2022
Golang implementation of JSON-RPC 2.0 server with generics

JSON-RPC 2.0 Golang implementation of JSON-RPC 2.0 server with generics. Go 1.18+ required Features: Batch request and responses WebSockets Usage Crea

Oct 11, 2022
DeepValueNetwork is a peer-to-peer database network managed and hosted by its community.

DeepValueNetwork To understand what DeepValueNetwork will be, I suggest you read this document. In progress This software is currently being developed

Dec 10, 2022
Antenna RPC is an RPC protocol for distributed computing, it's based on QUIC and Colfer. its currently an WIP.

aRPC - Antenna Remote Procedure Call Antenna remote procedure call (aRPC) is an RPC protocol focused on distributed processing and HPC. aRPC is implem

Jun 16, 2021
🎉 An awesome version control tool for protoc and its related plugins.
🎉 An awesome version control tool for protoc and its related plugins.

❤️ PowerProto is actively maintained! Any questions in use can be directly raised issue, I will respond to you as fast as possible. If you think the p

Dec 29, 2022
Terraform ACI Provider. Started before Cisco's release and stopped when Cisco released its own.

terraform-provider-aci This was before Cisco released their own (I did ask them if they were doing one and they said no !!) :-) I would have liked to

Nov 10, 2021
Jun 6, 2022
Coral, a friendly Cobra fork with nearly all its features, but only 4 dependencies
Coral, a friendly Cobra fork with nearly all its features, but only 4 dependencies

Coral Preamble I love Cobra and I love Viper. They are great projects, incredibly useful and outstandingly important for the Go community. But sometim

Dec 29, 2022