Created
May 5, 2020 16:24
-
-
Save nikhilsaraf/e4edafb1384d2e5db5eca641d2e74c55 to your computer and use it in GitHub Desktop.
Handle HTTP requests using Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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