Skip to content

Instantly share code, notes, and snippets.

@bodokaiser
Created June 26, 2014 16:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bodokaiser/e59b8be339735c676be4 to your computer and use it in GitHub Desktop.
Save bodokaiser/e59b8be339735c676be4 to your computer and use it in GitHub Desktop.
// in this case we inject the database as argument to another package
package httpd
import (
"net/http"
"path/to/db"
)
var db *db.Database
func Setup(d *db.Database) {
db = d
http.HandleFunc("/", handle)
http.ListenAndServe(":3000", nil)
}
func handle(w http.ResponseWriter, r *http.Request) {
data, err := db.FindAll()
w.WriteHeader(200)
w.Write(data)
}
// in this use case we create an extra database with setup
package httpd
import (
"net/http"
"path/to/db"
)
var db *db.Database
func Setup() {
db = db.New()
http.HandleFunc("/", handle)
http.ListenAndServe(":3000", nil)
}
func handle(w http.ResponseWriter, r *http.Request) {
data, err := db.FindAll()
w.WriteHeader(200)
w.Write(data)
}
// in this case the "db" package exports a global variable we use in our handle
package httpd
import (
"net/http"
"path/to/db"
)
func Setup() {
http.HandleFunc("/", handle)
http.ListenAndServe(":3000", nil)
}
func handle(w http.ResponseWriter, r *http.Request) {
data, err := db.Db.FindAll()
w.WriteHeader(200)
w.Write(data)
}
// in this case the "db" package has a local instance of "Database" which can be accessed through exported functions
package httpd
import (
"net/http"
"path/to/db"
)
func Setup() {
http.HandleFunc("/", handle)
http.ListenAndServe(":3000", nil)
}
func handle(w http.ResponseWriter, r *http.Request) {
data, err := db.FindAll()
w.WriteHeader(200)
w.Write(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment