Skip to content

Instantly share code, notes, and snippets.

@nikhilsaraf
Created May 5, 2020 16:24
Show Gist options
  • Save nikhilsaraf/e4edafb1384d2e5db5eca641d2e74c55 to your computer and use it in GitHub Desktop.
Save nikhilsaraf/e4edafb1384d2e5db5eca641d2e74c55 to your computer and use it in GitHub Desktop.
Handle HTTP requests using Golang
package main
import (
"io/ioutil"
"log"
"net/http"
"github.com/go-chi/chi"
)
// works for the specific chosen method by using a router
func main() {
r := chi.NewRouter()
/* POST / */
r.Method("POST", "/", http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
bts, e := ioutil.ReadAll(req.Body)
if e != nil {
writer.WriteHeader(http.StatusInternalServerError)
panic(e)
}
log.Printf("%s\n", string(bts))
writer.WriteHeader(http.StatusOK)
writer.Write([]byte("Hello World\n"))
}))
r.Route("/api/test”, func(r chi.Router) {
/* GET /api/test/somehandler */
r.Get(“/somehandler”, http.HandlerFunc(somehandlerGet))
/* POST /api/test/somehandler */
r.Get(“/somehandler”, http.HandlerFunc(somehandlerPost))
})
http.ListenAndServe("localhost:8020", r)
}
// works for all methods without using a router
func main2() {
http.HandleFunc("/", func(writer http.ResponseWriter, req *http.Request) {
bts, e := ioutil.ReadAll(req.Body)
if e != nil {
writer.WriteHeader(http.StatusInternalServerError)
panic(e)
}
log.Printf("%s\n", string(bts))
writer.WriteHeader(http.StatusOK)
writer.Write([]byte("Hello World\n"))
})
http.ListenAndServe("localhost:8020”, nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment