hakk

software development, devops, and other drivel
Tree lined path

Snippets

Pick a random element in an array or slice in Go (Golang)

Using the ‘math/rand’ package of golang to generate a pseudo-random number between [x,n). The bracket at the end means that n is exclusive and x could be any number 0 or greater. The package contains a function Intn which can be utilized to pick a random element in an array or slice of int or string. This example also uses the time package to seed the generator. Otherwise the it would be seeded with a 1 and the generated numbers wouldn’t be random. Read more...

A quick HTTP file server example in Go

Basic example to serve directory. package main import ( "flag" "fmt" "log" "net/http" ) func main() { // Simple static webserver: pathPtr := flag.String("d", ".", "Directory path to serve") portPtr := flag.String("p", "8080", "Port to listen on") interfacePtr := flag.String("i", "", "Interface to listen on (default all)") flag.Parse() log.Printf("Serving %s on %s:%s", *pathPtr, *interfacePtr, *portPtr) err := http.ListenAndServe(fmt.Sprintf("%s:%s", *interfacePtr, *portPtr), http.FileServer(http.Dir(*pathPtr))) if err != nil { log.Fatal(err) } } Example with ability to set custom headers Read more...

Example of adding CORS headers Flask

An example of adding CORS headers to a Flask app without using Flask-CORS. from flask import Flask, request, jsonify, make_response from werkzeug.datastructures import Headers app = Flask(__name__) @app.route('/', methods=['OPTIONS', 'GET', 'POST']) def index(): # output all request headers to terminal print(request.headers) if request.method == 'POST': # handle json post data here... print(request.get_json()) headers = Headers() headers.add('Access-Control-Allow-Origin', '*') headers.add('Access-Control-Allow-Methods', 'OPTIONS', 'GET', 'POST') headers.add('Access-Control-Allow-Headers', 'Content-Type') headers.add('Access-Control-Max-Age', '300') resp = make_response( jsonify( {'msg':'nailed it! Read more...