Skip to content

Instantly share code, notes, and snippets.

@alexedwards
alexedwards / app.rb
Created January 24, 2013 09:42
Ajax content loading with Sinatra, jQuery and HTML5 Pushstate.
require 'sinatra'
before do
response['Cache-Control'] = 'no-cache, no-store' if request.xhr?
end
get '/' do
erb :home, layout: ! request.xhr?
end
@alexedwards
alexedwards / app.rb
Created January 24, 2013 09:42
Ajax content loading with Sinatra, jQuery and HTML5 Pushstate.
require 'sinatra'
before do
response['Cache-Control'] = 'no-cache, no-store' if request.xhr?
end
get '/' do
erb :home, layout: ! request.xhr?
end
@alexedwards
alexedwards / gist:4d20c505f389597c3360
Last active January 25, 2016 02:07
Illustration of using httprouter and stack
package main
import (
"fmt"
"github.com/alexedwards/stack"
"github.com/julienschmidt/httprouter"
"net/http"
)
func main() {
@alexedwards
alexedwards / main.go
Created May 5, 2017 08:38
02.02-01.gist
package main
import (
"flag"
"log"
"net/http"
"os"
"snippetbox.org/pkg/handlers/web"
)
@alexedwards
alexedwards / main.go
Created June 26, 2017 17:01
Usage of Flusher
package main
import (
"log"
"net/http"
"time"
)
func main() {
log.Fatal(http.ListenAndServe(":4000", http.HandlerFunc(multiWriteResponse)))
@alexedwards
alexedwards / main.go
Created December 27, 2017 14:45
Real IP
func realIP(r *http.Request) string {
xRealIP := r.Header.Get("X-Real-Ip")
xForwardedFor := r.Header.Get("X-Forwarded-For")
if xRealIP == "" && xForwardedFor == "" {
return r.RemoteAddr
}
for _, address := range strings.Split(xForwardedFor, ",") {
return strings.TrimSpace(address)
}
@alexedwards
alexedwards / application.rb
Created March 18, 2018 20:03
I18n for Sinatra
configure do
enable :protection
set :sessions, key: "session", expire_after: 25920000, path: "/"
set :session_secret, ENV["SESSION_SECRET"]
helpers Sinatra::Helpers
use Rack::Flash
use Rack::Protection::AuthenticityToken
I18n.load_path = ["./blog/locales/en.yml", "./blog/locales/de.yml"]
@alexedwards
alexedwards / _results
Last active September 30, 2018 13:51
SCS and Gorilla Sessions benchmarks
# SCS
BenchmarkSCSMemstore-8 200000 9573 ns/op 3643 B/op 49 allocs/op
BenchmarkSCSCookies-8 100000 23220 ns/op 7516 B/op 83 allocs/op
BenchmarkSCSRedis-8 30000 45783 ns/op 4459 B/op 76 allocs/op
BenchmarkSCSMySQL-8 300 5782698 ns/op 4382 B/op 73 allocs/op
BenchmarkSCSPostgres-8 500 3715685 ns/op 5585 B/op 96 allocs/op
# Gorilla
post "/cart/checkout/" do
begin
# Uses stripe Rubygem v3.15.0
Stripe.api_key = ENV["STRIPE_SECRET_KEY"]
customer = {
email: @params[:email],
source: @params[:stripeToken],
metadata: {name: params[:full_name]},
}
type MyService interface {
Create() error
}
type MyDB {
DB *sql.DB
}
func (m *MyDB) Create() error {