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.
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
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) fs := http.FileServer(http.Dir(*pathPtr)) err := http.ListenAndServe(fmt.Sprintf("%s:%s", *interfacePtr, *portPtr), customHeaders(fs)) if err != nil { log.Fatal(err) } } func customHeaders(fs http.Handler) http.HandlerFunc { // found at https://stackoverflow.com/a/65905091 return func(w http.ResponseWriter, r *http.Request) { // add headers etc here // return if you do not want the FileServer handle a specific request w.Header().Set("Cache-Control", "no-cache") w.Header().Set("x-server", "hello, world!") fs.ServeHTTP(w, r) } }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!'} ) ) resp.headers = headers return resp if __name__ == '__main__': app.run(debug=True)