Skip to content
hakk
  • Home
  • Blog
  • Docs
  • DSA
  • Snippets

Snippets

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

    2023-01-01

    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

    2022-11-04

    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

    2022-11-04

    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)
    

Recent posts
  • Understanding the ss Command: A Modern Alternative to netstat
  • Understanding HTTP from Scratch with Python Sockets
  • When Environment Variables Mysteriously Reset...
  • How to Generate a 32-byte Key for AES Encryption
  • Streamlining Deployment: Installing Docker, Gitea, Gitea Act Runner, and Nginx on Ubuntu
© 2025 hakk
  • Home
  • Blog
  • Docs
  • DSA
  • Snippets