create a http server and parse authorization headers in go

Here is an example code snippet to create a HTTP server in Go that parses authorization headers:

main.go
package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
)

func main() {
	// Define the http server
	http.HandleFunc("/", handleRequest)

	// Start the server
	log.Fatal(http.ListenAndServe(":8080", nil))
}

// handleRequest is used to handle incoming http requests
func handleRequest(w http.ResponseWriter, r *http.Request) {
	// Get the Authorization header from the request
	authHeader := r.Header.Get("Authorization")
	if authHeader == "" {
		// No authorization header was provided, send back a 401 Unauthorized status
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	// Parse the authorization header
	authParts := strings.Split(authHeader, " ")
	if len(authParts) != 2 || authParts[0] != "Bearer" {
		// Invalid authorization header format, send back a 401 Unauthorized status
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	// The token is in the second part of the Authorization header
	token := authParts[1]
	fmt.Fprintf(w, "Authorization token: %s", token)
}
987 chars
40 lines

This code creates a simple HTTP server that listens on port 8080. When an HTTP request is made, it will retrieve the Authorization header from the request, parse it, and return the token portion of the header back to the client in the response. If the Authorization header is not provided or is in an invalid format, it will return a 401 Unauthorized status.

gistlibby LogSnag