@@ -117,9 +117,9 @@ func Handle(req handler.Request) (handler.Response, error) {
117117}
118118```
119119
120- ## go -middleware
120+ ## golang -middleware
121121
122- This template uses the http.HandlerFunc as entry point.
122+ This template uses the [ http.HandlerFunc] ( https://golang.org/pkg/net/http/#HandlerFunc ) as entry point.
123123
124124### Status of the template
125125
@@ -179,3 +179,74 @@ func Handle(w http.ResponseWriter, r *http.Request) {
179179 w.Write (resBody)
180180}
181181```
182+
183+ Example persistent database connection pool between function calls:
184+
185+ ``` go
186+ package function
187+
188+ import (
189+ " database/sql"
190+ " fmt"
191+ " io/ioutil"
192+ " net/http"
193+ " strings"
194+ _ " github.com/go-sql-driver/mysql"
195+ )
196+
197+ // db pool shared between function calls
198+ var db *sql.DB
199+
200+ func init () {
201+ var err error
202+ db, err = sql.Open (" mysql" , " user:password@/dbname" )
203+ if err != nil {
204+ panic (err.Error ())
205+ }
206+
207+ err = db.Ping ()
208+ if err != nil {
209+ panic (err.Error ())
210+ }
211+ }
212+
213+ func Handle (w http .ResponseWriter , r *http .Request ) {
214+ // read request payload
215+ body , err := ioutil.ReadAll (r.Body )
216+ if err != nil {
217+ http.Error (w, err.Error (), http.StatusInternalServerError )
218+ return
219+ }
220+ query := string (body)
221+
222+ // log to stdout
223+ fmt.Printf (" executing query: %s " , query)
224+
225+ rows , err := db.Query (query)
226+ if err != nil {
227+ http.Error (w, err.Error (), http.StatusInternalServerError )
228+ return
229+ }
230+ defer rows.Close ()
231+
232+ ids := make ([]string , 0 )
233+ for rows.Next () {
234+ var id int
235+ if err := rows.Scan (&id); err != nil {
236+ http.Error (w, err.Error (), http.StatusInternalServerError )
237+ return
238+ }
239+ ids = append (ids, string (id))
240+ }
241+ if err := rows.Err (); err != nil {
242+ http.Error (w, err.Error (), http.StatusInternalServerError )
243+ return
244+ }
245+
246+ result := fmt.Sprintf (" ids %s " , strings.Join (ids, " , " ))
247+
248+ // write result
249+ w.WriteHeader (http.StatusOK )
250+ w.Write ([]byte (result))
251+ }
252+ ```
0 commit comments