parse authorization headers in go

In Go, one can easily parse the authorization header using the net/http package. The authorization header contains an encoded username and password, which can be decoded and used for authenticating requests.

Here is an example of how to parse the authorization header in Go:

main.go
package main

import (
    "encoding/base64"
    "fmt"
    "net/http"
    "strings"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        authHeader := r.Header.Get("Authorization")
        if authHeader != "" {
            // The Authorization header should look like "Basic <base64-encoded string>"
            auth := strings.SplitN(authHeader, " ", 2)
            if len(auth) != 2 || auth[0] != "Basic" {
                http.Error(w, "Invalid Authorization header", http.StatusBadRequest)
                return
            }

            // Decode the base64-encoded string
            payload, err := base64.StdEncoding.DecodeString(auth[1])
            if err != nil {
                http.Error(w, "Invalid Authorization header", http.StatusBadRequest)
                return
            }

            // The payload should look like "<username>:<password>"
            pair := strings.SplitN(string(payload), ":", 2)
            if len(pair) != 2 {
                http.Error(w, "Invalid Authorization header", http.StatusBadRequest)
                return
            }

            // At this point, `pair[0]` is the username and `pair[1]` is the password
            username := pair[0]
            password := pair[1]

            // Do something with the username and password, like authenticate the request
            fmt.Fprintf(w, "Welcome, %s!", username)
        } else {
            // No Authorization header provided
            http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
        }
    })

    http.ListenAndServe(":8080", nil)
}
1637 chars
49 lines

This code listens for incoming HTTP requests and parses the Authorization header for each request. If the header is present, it verifies that it is valid, decodes it, and splits it into the username and password. It then uses those values to authenticate the request.

gistlibby LogSnag