Last active
January 6, 2025 17:39
-
-
Save poolski/ec56354b123c6b84fc8ffcccf42dcc4e to your computer and use it in GitHub Desktop.
Fake JSON API server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/base64" | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"strings" | |
) | |
const ( | |
apiKey = "test-api-key" | |
port = 9876 | |
) | |
func main() { | |
fmt.Printf("Server running on port %d...\n", port) | |
http.HandleFunc("/poll", func(w http.ResponseWriter, r *http.Request) { | |
authHeader := r.Header.Get("Authorization") | |
if authHeader != "" { | |
fmt.Printf("Authorization Header: %s\n", authHeader) | |
} else { | |
fmt.Println("No Authorization Header received") | |
} | |
if !validateAuth(authHeader) { | |
w.Header().Set("WWW-Authenticate", `Basic realm="API Access"`) | |
http.Error(w, "Unauthorized", http.StatusUnauthorized) | |
return | |
} | |
responseData := map[string]interface{}{ | |
"y_axis": map[string]string{ | |
"format": "currency", | |
"unit": "USD", | |
}, | |
"series": []map[string]interface{}{ | |
{ | |
"name": "GBP -> USD", | |
"data": []float64{ | |
1.62529, 1.56991, 1.50420, 1.52265, 1.55356, | |
1.51930, 1.52148, 1.51173, 1.55170, 1.61966, | |
1.59255, 1.63762, | |
}, | |
}, | |
}, | |
} | |
w.Header().Set("Content-Type", "application/json") | |
json.NewEncoder(w).Encode(responseData) | |
}) | |
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil { | |
fmt.Println("Error starting server:", err) | |
} | |
} | |
func validateAuth(authHeader string) bool { | |
if !strings.HasPrefix(authHeader, "Basic ") { | |
return false | |
} | |
encodedCredentials := strings.TrimPrefix(authHeader, "Basic ") | |
decodedBytes, err := base64.StdEncoding.DecodeString(encodedCredentials) | |
if err != nil { | |
fmt.Printf("Error decoding Authorization header: %v\n", err) | |
return false | |
} | |
credentials := string(decodedBytes) | |
username := strings.SplitN(credentials, ":", 2)[0] | |
fmt.Println("Received API Key:", username) | |
return username == apiKey | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment