Skip to content

Instantly share code, notes, and snippets.

@Harsimran1
Created February 17, 2019 14:40
Show Gist options
  • Save Harsimran1/8b81b6d3b591684a33098dfeff2d74a3 to your computer and use it in GitHub Desktop.
Save Harsimran1/8b81b6d3b591684a33098dfeff2d74a3 to your computer and use it in GitHub Desktop.
Minimal http server connected with database
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
// pq is postgres driver for database/sql
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres", fmt.Sprintf(
"user=%s password=%s dbname=%s host=%s sslmode=%s port=%d",
"postgres", "postgres", "postgres", "localhost", "disable", 5432))
if err != nil {
log.Fatal(err)
}
router := http.NewServeMux()
router.HandleFunc("/probes/readiness", func(res http.ResponseWriter, req *http.Request) {
if err := db.PingContext(req.Context()); err != nil {
res.WriteHeader(503)
}
})
srv := &http.Server{
Handler: router,
Addr: fmt.Sprintf(":%s", "8081"),
}
log.Fatal(srv.ListenAndServe())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment